Flask Framework Learning Guide for user login Management _python

Source: Internet
Author: User
Tags anonymous

Continue to flask the journey of learning. Today introduced Flask login Management module, remember the blog in a small project, login is our own written verification code, there are probably the following several steps:

1. Enter the username and password in the login box

2. The Flask view function gets the user's password and then queries the user's information in the database for matching

3, if successful, write session, redirect to the first page

4. If you have to log in to access a particular view, you need to verify that the user exists in the session for each view function.

Today continue to transform the blog project, the introduction of the Flask-login module is for us to handle these less business relevance of the common functions, it can help us:

Storing the current active user ID in a session allows you to login and log in freely.
Lets you limit the views that users can access by logging in (or logging out).
Deal with the tricky "Remember Me" feature.
Help protect your users ' conversations from cookies being stolen.
can be integrated with Flask-principal or other certification extensions that may be used later.

First, how to use the Flask-login module?

1. Installation Flask-login

E:\workdir\dct-server-5055187\src>pip install flask-login

2. Use Flask-login

2.1 Add in/blog2/__init__.py:

#引用包 from
flask.ext.login import loginmanager

#登陆管理
#声明login对象
login_manager = Loginmanager ()
# Initialization is bound to the application
Login_manager.init_app (APP)

#声明默认视图函数为login, when we do @require_login, if not landing will automatically skip to the View function processing
login_ Manager.login_view = "Login"

#当登陆成功后, this function automatically reloads the user object from the user ID stored in the session. It should accept a user's Unicode ID as a parameter and return the corresponding user object.
@login_manager. User_loader
def load_user (userid): Return
User.query.get (int (userid))

2.2 Modify the user model (the Red section is the new code)

From Flask.ext.login import usermixin from

blog2 Import DB

class User (db. Model, usermixin):
  __tablename__ = ' b_user '
  id = db. Column (db. Integer,primary_key=true)
  username = db. Column (db. String (a), unique=true)
  password = db. Column (db. String ()

  def __init__ (self,username,password):
    self.username = username
    self.password = password
  def __repr__ (self): return
    ' <user%r> '% self.username

The user class must implement the following methods:

is_authenticated

Returns True when the user passes the validation, i.e., when a valid proof is provided (only the authenticated user satisfies the login_required condition). )

is_active

Returns True If this is an active user and is authenticated, the account has been activated, has not been deactivated, and does not qualify for any application that rejects an account. Inactive accounts may not be logged in (of course, without coercion).

is_anonymous

Returns True if it is an anonymous user. (True user should return False.) )

get_id()

Returns a Unicode that uniquely identifies a user and can be used to load a user from a User_loader callback. Note that must be a unicode--if the ID is originally an int or other type, you need to convert it to Unicode.
To easily implement a user class, you can inherit from Usermixin, which provides a default implementation of all of these methods. We use Usermixin implementations here.

2.3) Modify the View function (the Red section is new)

From Flask.ext.login import login_required, Login_user, logout_user to blog2.model.User import user from blog2.model.c Ategory Import Category import os from blog2 import app,db from flask import Request,render_template,flash,abort,url_for, Redirect,session,flask,g @app. Route ('/') @login_required def show_entries (): Categorys = Category.query.all () return Render_template (' show_entries.html ', Entries=categorys) @app. Route ('/add ', methods=[' POST ')) @login_required def add _entry (): # —————————————————————————————————————————————— # The first version of the login method # if not Session.get (' logged_in '): # Abort (4
  # —————————————————————————————————————————————— title = request.form[' title '] content = request.form[' text '] Category = Category (Title,content) db.session.add (category) Db.session.commit () Flash (' New entry was successfully PO 
  Sted ') return redirect (Url_for (' show_entries ')) @app. Route ('/login ', methods=[' get ', ' POST ']) def login (): Error = None if Request.method = = ' POST ':
    user = User.query.filter_by (username=request.form[' username '). # ————————————————————————————————————————— ————————————————————————————————— #第一版登陆方式 # passwd = User.query.filter_by (password=request.form[' password ')). Firs T () # If User is none: # error = ' Invalid username ' # elif passwd is none: # error = ' Invalid pa ssWOrd ' # Else: # session[' logged_in ' = True # Flash (' You were logged in ') # return redirect (Url_fo
    R (' Show_entries ') # —————————————————————————————————————————————————————————————————————————— login_user (user)
    Flash (' logged in successfully. ') Return Redirect (Url_for (' show_entries ')) return render_template (' login.html ', Error=error) @app. Route ('/logout ') @ login_required def Logout (): # —————————————————————————————————————————————— # first page logout Way # session.pop (' logged_in ', N One) # —————————————————————————————————————————————— logout_user () Flash (' were logged out ') RetuRN Redirect (Url_for (' show_entries '))

 

By Flask-login Management login, the code is very concise and simple:

@login_required: The adorner is placed on a view that needs to be logged in to access, and if there is no login access restricted view will jump to the login page, Login_manager.login_view = "Login" Control in __init__.py
Login_user (user): Pass in a User object for login authentication, return true correctly, or false
Logout_user (): Logout function, clear user information in session

2.4 Reference User in Template

{% if current_user.is_authenticated ()%}
 Hi {{Current_user.name}}!
{% ENDIF%}

Use the previous layout.html and show_entries.html templates to determine whether the user logged in as a flask-login in the form of:

{% if not current_user.is_authenticated() %}

Current_User value: The value is <flask_login when the user does not log in. Anonymoususermixin object at 0x0000000003dcf550>, or anonymous user
After user login, the value is <user u ' admin ' >

Of course, user login can also be customized according to the actual situation, specifically not one by one details.

"Reference Documentation"

       flask-login Chinese version: http://www.pythondoc.com/flask-login/
        flask-login English: http://flask-login.readthedocs.io/en/latest/

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.