Flask Notes: 6: User login log Out

Source: Internet
Author: User
Tags openid

User Login login required to use the Flask-login plugin
InitializeModifying a configuration file app/__init__.py
From flask import flaskfrom flask.ext.sqlalchemy import sqlalchemyimport osfrom flask.ext.login import loginmanagerapp= Flask (__name__) app.config.from_object (' config ') db=sqlalchemy (APP) lm = Loginmanager () Lm.init_app (APP) Lm.login_ View = ' Login ' from app import views,models# importing login module #flask-lonin requires a loginmanager () instance #init_app (app name) configuration to the app #login_view That view allows you to log in



Refactoring the user modelModifying model app/models.py
From app import Dbclass User (db. Model): id = db. Column (db. Integer, primary_key=true) nickname = db. Column (db. String (+), index=true, unique=true) email = db. Column (db. String (+), Index=true, unique=true) posts = db.relationship (' Post ', backref= ' author ', lazy= ' dynamic ') def is_authe Nticated (self): return true def is_active (self): return true def is_anonymous (self): return Fa LSE DEF GET_ID (self): Try:return Unicode (self.id) # python 2 except Nameerror:re Turn str (self.id) # python 3 def __repr__ (self): return ' <user%r> '% (Self.nickname) class Post (db. Model): id = db. Column (db. Integer, Primary_key = True) BODY = db. Column (db. String (timestamp) = db. Column (db. DateTime) user_id = db. Column (db. Integer, Db. ForeignKey (' user.id ') def __repr__ (self): return ' <post%r> '% (self.body) # is_authenticated allows user authentication, returns only TR ue# is_active Valid account returns True unless the account # is_anonymous is disabledFake users are true# get_id returns the user unique identifier in Unicode format 


Log in log out viewModify View app/views.py
From flask import render_template, Flash, redirect, session, Url_for, request, Gfrom flask.ext.login import Login_user, lo Gout_user, Current_User, login_requiredfrom app Import app, DB, LM, Modelsfrom forms import Loginformfrom models import Us Er@lm.user_loaderdef Load_user (ID): Return User.query.get (int (id)) @app. Before_requestdef before_request (): G.user = Current_user@app.route ('/') @app. Route ('/index ') @login_requireddef index (): User=g.user posts=[{' Author '             : {' nickname ': ' John '}, ' body ': ' Beautiful day in portland! '}, {' author ': {' nickname ': ' Susan '},           ' Body ': ' The Avengers movie was so cool! '} ] Return render_template ("index.html", title= "Home", User=user, Posts=posts) @app. Route ('/login ', methods = [' G    ET ', ' POST ']) def login (): If G.user is not None and G.user.is_authenticated:return redirect (Url_for (' index ')) form = LoginForm () if Form.validate_on_submit (): If models. User.query.filter_by (Nickname=form.openid.data). First (): User = User.query.filter_by (nickname=form.openid.data). first_or_404 () Login_user (user) return redirect (Url_for (' index ')) Else:return render_template (' Log        In.html ', title = ' Sign in ', error= ' [NO] ', form = form) return render_template (' login.html ', title = ' Sign in ', form = form) @app. Route ('/logout ') @login_requireddef logout (): Logout_user () return redir The ECT (url_for (' Index ')) # @user_loader callback, which reloads the user object from the user ID stored in the session, accepts a user's Unicodeid as a parameter, and returns the appropriate user object. If the ID is not valid, it should return none (instead of throwing an exception). (In this case, the ID will be manually removed from the session and processing will continue) # Load_user () is used to return the user unique identifier # before_request () to store a flag to determine if the user is logged in # Current_User gets the current login user information # is The Before_request bound function executes when the request is received (the web says it will execute before the request is received, it is not clear) # G holds the global variables for the current request, and different requests have different global variables # The user logged in to the logout view with @login_required, Some places (such as password change) need to add fresh_login_required instead of login_required, the difference is that the former must be user manually logged in, the latter also contains the case of automatic cookie landing, @login_ Required is also used to ensure that only the logged-in user is visible # if G.user is not None and G.user.is_authenticated (): To determine whether the user is logged in, whether to allow login # if models. User.query.filter_by (Nickname=form.openid.data). First (): Determine whether the input is consistent with the database #user.query.filter_by (nickname= Form.openid.data). first_or_404 () If the input is inconsistent with the database, the request to return 404#login_user () is to log the user in (personal understanding) #logout_user () the user is logged out and clears the cookie# Redirect (Url_for (' View handler function name ') jump page



Modify Template app/templates/base.html


#if g.user.is_authenticated To determine if the user is logged in to display the logout link
Modify App/templates/login.html
{% extends "base.html"%} {% block content%}



Display:without login, the index URL will be automatically redirected to the login screen .

user names not in the input database will be displayed [No]

Login Success will return to the index page and show the logout link

log out and jump to login screen
#出现 the log in to access the this page. It could be that Flask-login brought a flash and was captured by the Get_flashed_messages () function (guessed).#本来应该跳转到 The Index interface, just index has@login_required, only the logged-in user is visible, so it points to the login interface

Flask Notes: 6: User login log Out

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.