Log user account login status details (python)

Source: Internet
Author: User
A Web application based on Flask Sixth, this article mainly introduces the logging user account login status function development, with a certain reference value, interested in small partners can refer to

Before the registration of the function has been completed, but login successfully back home to find or a vast expanse of whiteness, right, the title has been written blog, then the ultimate goal is to write a light blog, but, before publishing the article is to record the status of the login?

User Login

There are many ways to log in, and the first thing to think about is to use the session that comes with flask, but Flask also provides a more convenient extension, the Flask-login package, which is used as before, and needs to be installed first:

pip3.6 Install Flask-login

Then initialize in default.py:

From Flask.ext.login import Loginmanager......login_manager=loginmanager () login_manager.session_protection= " Strong "#可设置为None, Basic,strong has a different security level login_manager.login_view=" Login "#设置登录页

The user model is then modified as required because Flask-login requires the user model to implement four methods, namely:

is_authenticated () to determine if login, login returns True, otherwise return false
is_active () whether to allow logon, that is, whether the user has been disabled, such as disabling return false
is_anonymous () False for normal user
get_id () returns the user unique identifier, using Unicode encoding

These four methods are implemented directly in the user model, but there is an easier way to inherit the Usermixin class provided by Flask-login, which contains the default implementations of these methods, and 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 that has been used by the specified identifier home in the user:

@login_manager. User_loaderdef Load_user (user_id):  return User.query.get (int (user_id))

After that, it is convenient to use the Flask-login framework and continue to modify the navigation section of the homepage template to display the user name and the corresponding information:

{%extends "bootstrap/base.html"%} {% block title%} Cattle blog {% endblock%}<!--Overwrite title tag-->{% block NavBar%}<nav class= "NavBar navbar-inverse" ><!  --Navigation section--<p class= "Navbar-header" > <a class= "Navbar-brand" href= "#" rel= "external nofollow" rel= "external nofollow "> Cattle blog </a> </p> <p class=" collapse navbar-collapse "id=" bs-example-navbar-collapse-1 "   ; <ul class= "Nav navbar-nav" > <li><a href= "/" rel= "external nofollow" > Home </a></li> </u l> <ul class= "nav navbar-nav navbar-right" > {% if current_user.is_authenticated%} <li><p clas s= "Navbar-text" ><a href= "#" rel= "external nofollow" rel= "external nofollow" class= "Navbar-link" >{{current_ user.username}}</a> Hello </p></li> <li><a href= "{{url_for (' logout ')}}" rel= "external Nofollow "> Logout </a></li> {% Else%} <li><a href=" {{url_for (' login ')}} "rel=" External Nofollo W> Login </a></li> {% endif%} </ul> </p><!--/.navbar-collapse--></nav>{% endbloc K%}{% block content%} <!--specific content--><p class= "container" ></p>{% endblock%}

Here the new Url_for method, its main function is to use the information in the program to generate a URL, such as the method name of the incoming view, generate the corresponding URL, but also through the method's dynamic parameters to generate URL parameters, such as url_for (' index ', age=5) result is/?age=5

The main content is to determine whether to log in, if the login display {{username}} Hello, and provide logout function, otherwise display the login link.

To modify a login form:

Class LoginForm (Form):  Username=stringfield ("Please enter user name", validators=[datarequired ()])  password= Passwordfield ("Please enter password")  Remember_me=booleanfield ("Remember Me")  Submit=submitfield ("login")

Add remember my project, booleanfield default to multi-select button

To modify the login view method:

@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 ("The user name or password you entered is wrong")      return Render_template ("/login.html", form= form) # Returns the return  render_template ("/login.html", Form=form) that is still the login page

Where Login_user is provided for the Flask_login plug-in, which is used to set the user login, where the second parameter is the Remember me option, if you enter true, provide a cookie storage state, or close the browser state is canceled

New Log Out Method:

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

This method is simple, just use the Logout method provided by Flask-login, note that the @login_required adorner indicates that only the logged-on user can access this view method.

Run the test, enter the home address:

Click the login key in the upper-right corner:

Enter user name Zhangji password 123 and select Remember Me, click OK:

Note the Red Line section, the display is normal, at this point click Log Out:

Note the Red Line section, back to the initial state.

Chapter Conclusion

Then it should be post and focus on the function, but it is clear that the code is now in the default.py, the code structure is becoming more and more difficult, so the length of this chapter is relatively small, the next chapter will focus on the existing code refactoring, and the functions are grouped, and then continue to write the next function. Thank you for watching.

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.