django lazy user実装

1734 ワード

コードは次のとおりです.
 
from people.service import userQueryService 

class LazyUser(object):
    
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_user'):
            request._cached_user = self.get_user(request) 
        return request._cached_user
    
    def get_user(self,request):
        print 'request.user_id=%s'%request.user_id
        return userQueryService.findUserById(request.user_id)
    
class UserMiddleware(object):
    def process_request(self, request):
        print 'user session process_request'
        request.user_id = request.session.get('_auth_user_id')
        request.__class__.user = LazyUser()
        return None

 
 
この魔法コードは
request.__class__.user

 
requestにアクセスします.userがトリガーされます_get__メソッドを返し、データを返します.これはdemoです.
class LazyUser(object):
    def __init__(self,id):
        self.id = id
        
    def __get__(self, request, obj_type=None):
        if not hasattr(request, '_cached_user'):
            request._cached_user = self.get_user(request) 
        return request._cached_user
    
    def get_user(self,request):
        return self.id
    
class Request(object):
    pass

request1 = Request()
request1.__class__.user = LazyUser(1)

print request1.user

request2 = Request() 
request2.__class__.user = LazyUser(2)


print request2.user
print request1.user