Home  >  Article  >  Backend Development  >  How to use Flask-Login to implement user login and session management

How to use Flask-Login to implement user login and session management

PHPz
PHPzOriginal
2023-08-02 17:57:151678browse

How to use Flask-Login to implement user login and session management

Introduction:
Flask-Login is a user authentication plug-in for the Flask framework, through which we can easily implement user login and session management Session management functionality. This article will introduce how to use Flask-Login for user login and session management, and provide corresponding code examples.

1. Preparation
Before using Flask-Login, we need to install it in the Flask project. You can use pip to install it with the following command:

pip install Flask-Login

2. Create a Flask application and configure it
First, we need to create a Flask application and configure it accordingly. Write the following code in app.py:

from flask import Flask
from flask_login import LoginManager

app = Flask(__name__)
# 配置SECRET_KEY,用于加密会话数据
app.config['SECRET_KEY'] = 'your-secret-key'

login_manager = LoginManager(app)

Among them, LoginManager is used to manage logins and sessions. SECRET_KEY is configured through app.config['SECRET_KEY'] to encrypt session data, which can be a random string.

3. Create a user model
Next, we need to create a user model to store user information, such as user name, password, etc. Write the following code in app.py:

from flask_login import UserMixin

class User(UserMixin):
    def __init__(self, id):
        self.id = id
        self.username = None
        self.password = None
    
    def get_id(self):
        return str(self.id)

Here we simplify the implementation of the user model by inheriting the UserMixin class, and implement the get_id method to return the user's unique identifier.

4. Writing the login view
Next, we need to write a login view to handle the user's login request. Write the following code in app.py:

from flask import request, redirect, url_for, render_template
from flask_login import login_user

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        # 验证用户名和密码
        user = User(1)  # 根据用户名和密码查询数据库获取用户对象
        if user.username == username and user.password == password:
            login_user(user)  # 登录用户
            return redirect(url_for('index'))
        
        return render_template('login.html', error='用户名或密码错误')
    
    return render_template('login.html')

Here, request.form.get is used to obtain the user name and password in the user request, and then verify whether the user name and password are correct according to the actual situation. If correct, the login_user function is called. Log in the user and redirect to the homepage.

5. Write session management related code
In the above code, we use the login_user function of Flask-Login to realize user login. Next, we also need to write some code to implement session management related functions.

  1. Login success callback function

    from flask_login import login_user, login_required, logout_user, current_user
    
    @login_manager.user_loader
    def load_user(user_id):
     return User(int(user_id))

    @login_manager.user_loader decorator will be used by Flask-Login to load user objects. In this loading function, we return the user object based on the user's unique identifier.

  2. Protected view function

    @app.route('/')
    @login_required
    def index():
     return 'Hello, {}!'.format(current_user.username)

    @login_required decorator will protect the index view function, and only logged-in users can access the view.

  3. Logout view

    @app.route('/logout')
    @login_required
    def logout():
     logout_user()  # 登出用户
     return redirect(url_for('login'))

    Users log out of the currently logged in user by accessing the /logout path.

6. Create a login page
Finally, we need to create a login page, create the login.html file in the templates directory, and write the following code:

{% if error %}
<p style="color: red;">{{ error }}</p>
{% endif %}
<form method="post" action="{{ url_for('login') }}">
    <input type="text" name="username" placeholder="用户名" required>
    <input type="password" name="password" placeholder="密码" required>
    <button type="submit">登录</button>
</form>

In the login page, we display the error message and provide input boxes for username and password, as well as a login button.

7. Run the application
At this point, we have completed all the code for using Flask-Login to implement user login and session management. Run the application and access the /login path to enter the login page for user login.

Summary:
This article introduces how to use Flask-Login to implement user login and session management, and provides corresponding code examples. Using Flask-Login can easily manage user logins and sessions, improving application security and user experience. I hope this article will help you learn Flask-Login.

The above is the detailed content of How to use Flask-Login to implement user login and session management. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn