flask_login中current_user问题

在用户未登陆(匿名用户)情况下:

print 'current_user: %s'  % current_user
print 'AnonymousUser: %s' % AnonymousUser
print isinstance(current_user, AnonymousUser)

结果:

current_user: 
AnonmousUser: 
False

current_userAnonymousUser的实例对象,isinstance(current_user, AnonymousUser)应该返回True,结果却是False.为什么?
current_user应该是对AnonymousUser进行了封装,隐藏了真正的实例对象.这个真正的对象可以通过_get_current_object()获取.

print 'current_user: %s'  % current_user._get_current_object()
print 'AnonymousUser: %s' % AnonymousUser
print isinstance(current_user._get_current_object(), AnonymousUser)

结果:

current_user: 
AnonmousUser: 
True

在用flask-login时若想获取真正的当前用户,用current_user._get_current_object()方法.

流程

# 代码1
current_user = LocalProxy(lambda: _request_ctx_stack.top.user)

指定current_user为代理

# 代码2
# LoginManager类
def set_up(self, app, add_context_processor=True):
    if add_context_processor:
        app.context_processor(_user_context_processor)

在loginmanager实例化app时, 利用flask中context_processor添加current_user

# 代码3
def _user_context_processor():
    return dict(current=_get_user())
# 代码4
def _get_user():
    return getattr(_request_ctx_stack.top, 'user', None)
# 代码5
# flask.Flask  -- app.context_processor 
def context_processor(self, f):
    self.template_context_processors.append(f)
    return f
# 代码6
# flask.Flask -- self.tempalte_context_processors
def __init__(self, package_name):
    ...
    self.template_context_processors = [_default_template_ctx_processor]
    ...
# 代码7
# flask -- _default_template_ctx_processor
def _default_template_ctx_processor():
    reqctx = _request_ctx_stack.top
    return dict(
        request=reqctx.request,
        session=reqctx.session,
        g=reqctx.g
    ) 

你可能感兴趣的:(python,flask-web)