[关闭]
@StrGlee 2016-10-19T14:13:43.000000Z 字数 5821 阅读 1290

flask-login

flask

is_authenticated

当用户通过验证时,返回有效的凭证True

  1. def is_authenticated(self):
  2. return True

is_active

一个活动用户具有 1)通用验证 2)账号也已经激活 3)未被停用 4)也不符合任何的应用拒绝登录的条件,返回True。不活动的账号无法登录

  1. def is_active(self):
  2. return True

is_anonyous

如果是一个如果是一个匿名用户,返回True;如果是一个登录用户则返回false

  1. def get_id(self):
  2. return self.id

get_id

返回一个能唯一识别用户的,并能用户从user_loader回调中加载用户的ID,这个ID必须是unicode

  1. @property
  2. def is_anonymous(self):
  3. return False

配置登录

@user_loader

解析: 这个API设置返回一个回调,用于从缓存中加载用户登录信息。你构造的函数需要设置一个user id 并且返回一个用户的实体。如果用户不存在则返回None

  1. @login_manager.user_loader
  2. def load_user(user_id):
  3. from .models.user_model import UserModel
  4. from .models.admin_model import AdminModel
  5. model_dict = {
  6. 'user_bp': UserModel,
  7. 'admin_bp': AdminModel,
  8. }
  9. if request.blueprint in model_dict:
  10. try:
  11. user = model_dict[request.blueprint].query.\
  12. filter_by(id=user_id).one()
  13. except:
  14. db.session.rollback()
  15. user = None
  16. else:
  17. user = None
  18. return user

@request_loader(@header_loader)

解析:设置一个从flask请求加载用户的回调。你需要给函数一个Flask请求,函数返回用户的实体,用户不存在则返回None

  1. @login_manager.request_loader
  2. def loader_user_from_request(request):
  3. # first, try to login using the api key url arg
  4. api_key = request.args.get('api_key')
  5. if api_key:
  6. user = User.query.filter_by(api_key=api_key).first()
  7. if user:
  8. return user
  9. # next, try to login using Basic Auth
  10. api_key = request.headers.get('Authorization')
  11. if api_key:
  12. api_key = api_key.replace('Basic', '', 1)
  13. try:
  14. api_key = base64.b64decode(api_key)
  15. excet TypeError:
  16. pass
  17. user = User.query.filter_by(api_key=api_key).first()
  18. if user:
  19. return user
  20. # finally, return None if both methods did not login the user
  21. return None

anonymous_user

解析:提供了一个游客用户,该用户是在没有登录状态下时使用

使用实例:(你可以判断当前用户的is_anonymous属性,是不是True来看是不是随机用户)

  1. if current_user.is_anonymous == True

未经授权的配置

API: flask_login.login_view

解析:当用户需要登录时,将用户重定向到的界面。

使用举例(将非法登录强制重定向到登录界面):

  1. login_manager.login_view = 'login'

API: flask_login.login_message

解析:当用户重定向时,flash出的消息。

使用举例:

  1. login_manager.login_message = 'Please enter your account'

API:@unauthorized_handler

解析:如果你不想用默认的重定向定制你的登录,你可以在代码视图实体中显示的写出一个函数体,将@unauthorized_handler装饰器添加到函数体之上。这样做之后,当你用@login_required阻止用户非法登录,将执行我们新定义的函数体中的内容。

使用举例(将非法登录强制重定向到登录界面):

  1. @login_manager.unauthorized_handler
  2. def unauthorized_handler():
  3. return redirect('/login')

需要活跃登录的配置

API: flask_login.refresh_view

解析:当用户需要活跃登录时,将用户重定向到的界面。

使用举例(将非法登录强制重定向到登录界面):

  1. login_manager.refresh_view = 'login'

API: flask_login.needs_refresh_message

解析:当需要活跃登录的用户重定向时,flash出的消息。

使用举例:

  1. login_manager.needs_refresh_message = 'You need a fresh log in.Please enter your account'

API:@needs_refresh_handler

解析:作用和unauthorized_handler类似,当你需要登录的用户是输入用户名密码登录时,而你又不想使用默认的重定向方法,那么,你可以显示的定义你自己处理函数。
使用举例(将非活跃登录强制重定向到登录界面,并flash出消息):

  1. @login_manager.needs_refresh_handler
  2. def refresh():
  3. flash('You should log in!')
  4. return logout()
  1. @login_manager.needs_refresh_handler
  2. def refresh():
  3. flask.ext.login.logout_user()
  4. from .models.user_model import UserModel
  5. from .models.admin_model import AdminModel
  6. model_dict = {
  7. 'user_bp': 'user_bp.',
  8. 'admin_bp': 'admin_bp.',
  9. }
  10. if request.blueprint in model_dict:
  11. try:
  12. return redirect(url_for(model_dict[request.blueprint]))
  13. except:
  14. return redirect(url_for('user_bp.'))

登录机制

API:flask_login.current_user

解析:获取当前缓存中保存的用户帐户信息(一个当前用户的代理)

API:flask_login.login_fresh()

如果当前用户是活跃登录,则返回True。

API:flask_login.login_user(user, remember=False, force=False,fresh=True)

解析Ⅰ:登录用户。你需要向函数中传进一个用户对象。如果用户'is_active'属性为'Flase',只有当'force'是'True'时才会允许登录。当登录成功后返回'True',当失败时返回'False'。
这里特别提一下函数参数'fresh',当设置为'False'时,将登陆用户的缓存(Session)中标志为不是活跃登录。默认值为'True'

举例:

  1. @app.route('/post')
  2. @login_required
  3. def post():
  4. pass

解析Ⅱ:如果只有当前时刻你需要要求你的用户登录,你可以这样做:

  1. if not current_user.is_authenticated:
  2. return current_app.login_manager.unauthorized()

实际上,将上边的代码添加到你的视图中去就可以达到要求了。
当单体测试的时候它可以很方便的全局关闭认证。将'LOGIN_DISABLED'设置为True,装饰器就会被忽略了。

API:flask_login.logout_user()

解析:用户登出(你不需要通过实际用户)。这个函数同时会清除remember me中的cookie(如果存在的话)。
作用就是清除一系列的cookie信息。

API:flask_login.confirm_login()

解析:函数将会将当前Sesslion设置为活跃。当从cookie加载之后,Sesson会变成不活跃状态。

保护视图

API:flask_login.login_required

解析:如果你将这个装饰器放在视图上,它会保证你的当前用户是登录状态,并且在调用实际视图之前进行认证。

    如果当前用户不是系统认证的登录状态,它将调用LoginManager.unauthorized回调。

API:flask_login.fresh_login_required

解析:如果用这个装饰器放在视图上,它将确保当前用户是活跃登录的。用户的Session不是从'remember me'的cookie中加载的。
敏感的操作,例如修改密码或者邮箱,应该用这个装饰器保护,来阻止cookie被盗取。
如果用户没有认证,通常调用'LoginManager.unauthorized'。
如果用户被认证了,但是缓存不是活跃登陆,它将会'LoginManager.needs_refresh'代替,而且你需要提供一个'LoginManager.refresh_view'。

load_user

Flask-login doesn't actually have a user backend, it just handles the session machinery to help you login and logout users. You have to tell it (by decorating methods), what represents a user and it is also up to you to figure out how to know if a user is "active" or not (since being "active" can mean different things in different applications).
You should read the documentation and be sure what it does and does not do. Here I am only going to concentrate on wiring it up with the db backend.
To start off with, define a user object; which represents properties for your users. This object can then query databases, or LDAP, or whatever and it is the hook that connects the login mechanism with your database backend.
I will be using the login example script for this purpose.

  1. class User(UserMixin):
  2. def __init__(self, name, id, active=True):
  3. self.name = name
  4. self.id = id
  5. self.active = active
  6. def is_active(self):
  7. # Here you should write whatever the code is
  8. # that checks the database if your user is active
  9. return self.active
  10. def is_anonymous(self):
  11. return False
  12. def is_authenticated(self):
  13. return True

Once you have the user object created, you need to write a method that loads the user (basically, creates an instance of the User class from above). This method is called with the user id.

  1. @login_manager.user_loader
  2. def load_user(id):
  3. # 1. Fetch against the database a user by `id`
  4. # 2. Create a new object of `User` class and return it.
  5. u = DBUsers.query.get(id)
  6. return User(u.name,u.id,u.active)

Once you have these steps, your login method does this:

1.Checks to see if the username and password match (against your database) - you need to write this code yourself.
2.If authentication was successful, get the id of the user and pass it to login_user()
ref:http://stackoverflow.com/questions/12075535/flask-login-cant-understand-how-it-works?answertab=active#tab-top
解释一下答案中的最后几个点,
1)你需要由你自己写出这段代码。,检查用户名和密码是否匹配(非请求到数据库的情况下)。
也就是说,用户的cookie中可以存在非法的登录信息,你需要自己写出代码校验是否符合你所用数据库的格式。
2)如果认证成功,取得用户ID,然后将用户实体它传递给login_user()。

标签(空格分隔): 未分类


在此输入正文

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注