如何从Django中的会话登录用户的uid?

时间:2021-01-28 12:59:12

I have implemented a registration/login/authentication system using this Django guide.

我已经使用这个Django指南实现了注册/登录/认证系统。

But, how would I access a user's information from my views so I can send the user's information to a template file?

但是,我如何从我的视图中访问用户的信息,以便将用户的信息发送到模板文件?

I want to be able to access a user's ID so I can submit a form with the user's ID attached to the form.

我希望能够访问用户的ID,以便我可以提交一个表格,其中附有表格的用户ID。

5 个解决方案

#1


9  

There is a django.contrib.auth.models.User object attached to the request; you can access it in a view via request.user. You must have the auth middleware installed, though.

有一个附加到请求的django.contrib.auth.models.User对象;您可以通过request.user在视图中访问它。但是,您必须安装auth中间件。

#2


46  

In case anyone wants to actually extract a user ID from an actual Session object (for whatever reason - I did!), here's how:

如果有人想从实际的Session对象中提取实际的用户ID(无论出于何种原因 - 我做过!),请按以下步骤操作:

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
session_data = session.get_decoded()
print session_data
uid = session_data.get('_auth_user_id')
user = User.objects.get(id=uid)

Credit should go to Scott Barnham

应该归功于Scott Barnham

#3


6  

This:

这个:

def view(request):
    if request.user.is_authenticated():
         user = request.user
         # do something with user

#4


2  

An even easier way to do this is to install django-extensions and run the management command print_user_for_session.

更简单的方法是安装django-extensions并运行管理命令print_user_for_session。

And this is how they do it:

这就是他们这样做的方式:

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

#5


0  

In case hwjp solution doesn't work for you ("Data is corrupted"), here is another solution:

如果hwjp解决方案不适合你(“数据已损坏”),这是另一种解决方案:

import base64
import hashlib
import hmac
import json

def session_utoken(msg, secret_key, class_name='SessionStore'):
    key_salt = "django.contrib.sessions" + class_name
    sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
    utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
    return utoken


def decode(session_data, secret_key, class_name='SessionStore'):
    encoded_data = base64.b64decode(session_data)
    utoken, pickled = encoded_data.split(b':', 1)
    expected_utoken = session_utoken(pickled, secret_key, class_name)
    if utoken.decode() != expected_utoken:
        raise BaseException('Session data corrupted "%s" != "%s"',
                            utoken.decode(),
                            expected_utoken)
    return json.loads(pickled.decode('utf-8'))

s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))

credit to: http://joelinoff.com/blog/?p=920

信用:http://joelinoff.com/blog/?p = 920

#1


9  

There is a django.contrib.auth.models.User object attached to the request; you can access it in a view via request.user. You must have the auth middleware installed, though.

有一个附加到请求的django.contrib.auth.models.User对象;您可以通过request.user在视图中访问它。但是,您必须安装auth中间件。

#2


46  

In case anyone wants to actually extract a user ID from an actual Session object (for whatever reason - I did!), here's how:

如果有人想从实际的Session对象中提取实际的用户ID(无论出于何种原因 - 我做过!),请按以下步骤操作:

from django.contrib.sessions.models import Session
from django.contrib.auth.models import User

session_key = '8cae76c505f15432b48c8292a7dd0e54'

session = Session.objects.get(session_key=session_key)
session_data = session.get_decoded()
print session_data
uid = session_data.get('_auth_user_id')
user = User.objects.get(id=uid)

Credit should go to Scott Barnham

应该归功于Scott Barnham

#3


6  

This:

这个:

def view(request):
    if request.user.is_authenticated():
         user = request.user
         # do something with user

#4


2  

An even easier way to do this is to install django-extensions and run the management command print_user_for_session.

更简单的方法是安装django-extensions并运行管理命令print_user_for_session。

And this is how they do it:

这就是他们这样做的方式:

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

https://github.com/django-extensions/django-extensions/blob/master/django_extensions/management/commands/print_user_for_session.py

#5


0  

In case hwjp solution doesn't work for you ("Data is corrupted"), here is another solution:

如果hwjp解决方案不适合你(“数据已损坏”),这是另一种解决方案:

import base64
import hashlib
import hmac
import json

def session_utoken(msg, secret_key, class_name='SessionStore'):
    key_salt = "django.contrib.sessions" + class_name
    sha1 = hashlib.sha1((key_salt + secret_key).encode('utf-8')).digest()
    utoken = hmac.new(sha1, msg=msg, digestmod=hashlib.sha1).hexdigest()
    return utoken


def decode(session_data, secret_key, class_name='SessionStore'):
    encoded_data = base64.b64decode(session_data)
    utoken, pickled = encoded_data.split(b':', 1)
    expected_utoken = session_utoken(pickled, secret_key, class_name)
    if utoken.decode() != expected_utoken:
        raise BaseException('Session data corrupted "%s" != "%s"',
                            utoken.decode(),
                            expected_utoken)
    return json.loads(pickled.decode('utf-8'))

s = Session.objects.get(session_key=session_key)
decode(s.session_data, 'YOUR_SECRET_KEY'))

credit to: http://joelinoff.com/blog/?p=920

信用:http://joelinoff.com/blog/?p = 920