Detailed description of user account logon status instances (python)

Source: Internet
Author: User
A flask-based web application was born in the sixth article. This article mainly introduces the development of the function for recording the logon status of user accounts, which has some reference value, if you are interested, please refer to the sixth article about the birth of a flask-based web application. This article mainly introduces the development of the function for recording logon status of user accounts, which has some reference value, for more information, see

Previously, all the login and registration functions have been completed. However, when I log on to the home page, I find that I am still white-faced. right, I have always written a blog title, so the ultimate goal is to write a simple blog, however, do you need to record the logon status before publishing an article?

User logon

There are many ways to record the logon status. The first thought should be to use the session that comes with flask, but flask also provides a more convenient extension, that is, the flask-login package, the usage is the same as before. you must first install:

pip3.6 install flask-login

Then initialize in default. py:

From flask. ext. login import LoginManager ...... login_manager = LoginManager () login_manager.session_protection = "strong" # it can be set to None, basic. strong provides different security levels: login_manager.login_view = "login" # set the logon page

Then modify the User model as needed, because the Flask-Login requires that the User model implement four methods:

Is_authenticated () determines whether to log on. True is returned for logon; otherwise, False is returned.
Is_active (): whether to allow logon, that is, whether the user has been disabled. if disabled, False is returned.
Is_anonymous () False is a common user
Get_id () returns the unique identifier of the user, which is encoded in Unicode.

These four methods can be directly implemented in the User model, but there is also a simpler way to inherit the UserMixin class provided by Flask-Login, which contains the default implementations of these methods, the modified User model is:

from flask.ext.login import UserMixinclass User(UserMixin,db.Model):  __tablename__="users"  id=db.Column(db.Integer,primary_key=True)  ......

Flask-login also requires the program to implement a callback function. the specified identifier is already used by the user:

@login_manager.user_loaderdef load_user(user_id):  return User.query.get(int(user_id))

Then, you can easily use the flask-login framework and continue to modify the navigation section of the homepage Template to display the user name and corresponding information:

{% Extends "bootstrap/base.html" % }{% block title %} blog {% endblock %}
 {% Block navbar %}
 
   
  

Blog

  • Homepage
    {% If current_user.is_authenticated %}
  • Hello, {current_user.username}

  • Logout
  • {% Else %}
  • Login
  • {% Endif %}

{% Endblock %} {% block content %}

{% Endblock %}

The url_for method is introduced here. its main function is to generate a URL using information in the program, such as passing in the method name of the view and generating the corresponding url, you can also use dynamic parameters of the method to generate url parameters, such as url_for ('index', age = 5). The result is /? Age = 5

The main content is to determine whether or not to log on. if login shows {User name} Hello, and the logout Function is provided, otherwise the logon link is displayed.

Modify the logon form:

Class LoginForm (Form): username = StringField ("Enter the user name", validators = [DataRequired ()]) password = PasswordField ("enter the password ") remember_me = BooleanField ("Remember Me") submit = SubmitField ("login ")

Add the Remember Me project. BooleanField is selected by default.

Modify the logon view:

@ App. route ("/login", methods = ["GET", "POST"]) def login (): form = LoginForm () if form. validate_on_submit (): username = form. username. data password = form. password. data user = User. query. filter_by (username = username, password = password ). first () if user is not None: login_user (user, form. remember_me.data) return redirect (url_for ("index") else: flash ("your username or password is incorrect") return render_template ("/login.html", form = form) # return to the logon page: return render_template ("/login.html", form = form)

Login_user is provided by the flask_login plug-in to set user logon. The second parameter is the Remember Me option. if True is entered, the cookie storage status is provided. Otherwise, the browser is disabled and the status is canceled.

New logout method:

@app.route("/logout",methods=["GET","POST"])@login_requireddef logout():  logout_user()  return redirect(url_for("index"))

This method is very simple. you can simply use the logout method provided by flask-login. Note that the @ login_required modifier indicates that only login users can access this view method.

Run the test and enter the home address:

Pay attention to the red line and return to the initial status.

Chapter conclusion

The Post and follow-up functions should be followed, but obviously, the code is now default. in py, the code structure is increasingly inadequate, so this chapter is relatively small. the next chapter will focus on restructuring existing code and grouping functions, then, continue to write the following functions. Thank you for watching.

The above is a detailed description of the user account logon status instance (python). For more information, see other related articles in the first PHP community!

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.