2011-11-03 68 views

回答

5

此:

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

如果有人想以實際提取的實際會話對象的用戶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) 

信貸應該去Scott Barnham

+0

很酷,這可以節省1查詢:'request.session.get('_ auth_user_id')',而不是'request.user.id',但似乎'請求中間件「或」RequestContext「實際上做了一個查詢來檢索auth用戶,所以這在某些情況下並不實際存儲。 –

+0

什麼時候'_auth_user_id'在創建一個新的'Session'時被附加到'Session'對象? –

0

如果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')) 

貸:http://joelinoff.com/blog/?p=920

相關問題