


Python server programming: using Flask-Login to implement user login
Python server programming: Using Flask-Login to implement user login
With the development and popularity of web applications, user login has become an essential function for many applications. In Python server programming, Flask is a widely used web development framework. In addition, Flask also provides many third-party extensions, such as Flask-Login, which can help us quickly implement user login functions.
This article will introduce how to use the Flask-Login extension to implement user login function in Python server. Before that, we need to install Flask and Flask-Login extension. You can use the pip command to install:
pip install Flask Flask-Login
Now let’s implement our user login system.
- Create a Flask application
First, we need to create a Flask application. Create an app.py file in the root directory and write the following code in it:
from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "Hello World!" if __name__ == "__main__": app.run(debug=True)
In this example, we created a Flask application and defined a route. The root route returns "Hello World !". We also use the __name__ == "__main__"
conditional statement to ensure that the Flask application only runs when we run the script.
Now, we have successfully created a simple Flask application.
2. Create a user model
In this example, we assume that the user's username and password have been saved to the database. So we need to define the user model first so that on login we can check if the user exists.
Add the following code in the app.py file:
from flask_login import UserMixin class User(UserMixin): def __init__(self, id): super().__init__() self.id = id def __repr__(self): return f"<User {self.id}>"
In this example, we define a User class, which inherits from Flask-Login’s UserMixin
class . UserMixin
provides some useful properties and methods, including:
is_authenticated
: True if the user has been authenticated.is_active
: True if the user is active.is_anonymous
: True if the user is not authenticated.get_id
: Returns the string representation of the user ID.
In the constructor of the User class, we pass in the user's ID. We also define a __repr__
method to see more information about the user object during debugging and testing.
- Writing the Login View
Now, we need to write a login view that lets the user enter their username and password. If the user's username and password are correct, the login is successful and the user object is added to Flask-Login's user session.
Add the following code in the app.py file:
from flask_login import LoginManager, login_user, current_user login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(user_id): return User(user_id) @app.route("/login") def login(): user_id = request.args.get("user_id") password = request.args.get("password") if user_id and password: # 省略查询数据库的代码 user = User(user_id) login_user(user) return "Login success!" else: return "Login failed!" @app.route("/logout") def logout(): logout_user() return "Logout success!"
In this example, we first create a LoginManager
object. Then, we define a user_loader
callback function that takes the user ID as a parameter and returns the user object corresponding to that ID. In this example, we create a new User
object and pass the ID as a parameter.
Next, we define a login view. In the view function, we use the request.args.get
method to get the user ID and password from the query string. Then we check if the user ID and password are valid. If the user's username and password are correct, a new User
object is created and the object is added to Flask-Login's user session using the login_user
function. If a user's username and password are incorrect, the user cannot log in.
Finally, we define a logout view, which uses the logout_user
function to delete the current user object from Flask-Login's user session and returns a message indicating successful logout.
- Protect other views
Now, we have implemented the user login system, but we are not using it to protect other views. In this example, we will protect a page called "profile" that is only accessible when the user is logged in. If the user is not logged in, they will be redirected to the login page.
Add the following code in the app.py file:
from flask_login import login_required @app.route("/profile") @login_required def profile(): return f"Welcome, {current_user.id}!"
In this example, we use the login_required
decorator to protect the "profile" route. If the user is not logged in, this decorator will redirect to the login page.
When protecting the view, we also use the current_user
global variable to access the information of the currently logged in user. In this example, we add a simple welcome message that contains the ID of the currently logged in user.
- Run the application
Now, we have completed all implementations of the user login system. Let's run the application and test it.
Enter the following command in the terminal to launch the application:
python app.py
Enter the following URL in the browser to access the homepage:
http://localhost:5000/
You should see "Hello World !" string. Now try to access the following URL:
http://localhost:5000/profile
Since you are not an authenticated user, you will be redirected to the login page. Enter a valid user ID and password in the query string, for example:
http://localhost:5000/login?user_id=1&password=password123
If you entered the correct username and password, you should see the "Login success!" message. Now, access the "/profile" route again and it should display a welcome message containing the ID of the currently logged in user.
如果你在浏览器中访问以下URL,则可以注销当前会话:
http://localhost:5000/logout
这样就完成了用户登录系统的所有实现。
总结
在本文中,我们介绍了如何使用Flask-Login扩展在Python服务器中实现用户登录功能。使用Flask-Login可以方便地验证和保护Web应用程序中的用户数据。此外,Flask-Login提供了许多有用的功能和方法,如会话管理和用户保护。希望这篇文章能够帮助你更好地了解如何使用Flask-Login编写Python服务器应用程序。
The above is the detailed content of Python server programming: using Flask-Login to implement user login. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
