Home > Article > Backend Development > Small application development guide for the Flask framework
Flask Framework Small Application Development Guide
Introduction:
With the popularity of the Internet, the demand for Web applications is getting higher and higher, and Flask, as a light The massive Python web framework is becoming more and more popular among developers because of its simplicity, flexibility, ease of learning and expansion. This article will guide readers through specific code examples to quickly master the basic steps of developing small applications using the Flask framework.
1. Preparation
Before we start, we need to make sure that Python and the Flask framework have been installed. It can be installed through the following command:
pip install flask
2. Create a Flask application
First, we need to create a new Python file, such as app.py, and then import the Flask library in the file and create a Flask Application object:
from flask import Flask app = Flask(__name__)
3. Routing and view functions
Flask uses routing and view functions to implement the mapping relationship between URL and view. In Flask, we can use decorators to define routes and view functions, for example:
@app.route('/') def index(): return 'Hello, Flask!'
The above code defines a root route '/' and a view function named index. When the user accesses the root URL , Flask will execute the index function and return 'Hello, Flask!'.
4. Run the application
In Flask, you can run the application directly in the application script. We just need to add the following code at the end of the script:
if __name__ == '__main__': app.run()
In this way, when we run the script in the terminal, the Flask application will run on the local server.
5. Rendering template
In actual applications, it is often necessary to combine dynamically generated data with HTML templates and present them to users. Flask provides Jinja2 template engine to implement template rendering. First, we need to prepare an HTML template, such as index.html:
<!DOCTYPE html> <html> <head> <title>Flask应用</title> </head> <body> <h1>{{ message }}</h1> </body> </html>
Then, use the render_template function in the view function to render the template:
from flask import render_template @app.route('/') def index(): message = 'Hello, Flask!' return render_template('index.html', message=message)
Finally, Flask will use the variables in the template Make the replacement and return the rendered HTML to the client.
6. Processing forms
Web applications often need to process form data submitted by users. Flask provides methods to obtain form data through the request object. For example, we can use request.form in the view function to obtain the form data of the POST request:
from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': username = request.form['username'] password = request.form['password'] # 处理表单数据 return render_template('login.html')
In the above code, we define a /login route and specify that it supports GET and POST requests. In the POST request, we obtain the username and password submitted in the form through request.form.
7. Database operation
In actual applications, it is usually necessary to interact with the database. Flask provides support for database operations through extension packages such as SQLAlchemy. First, we need to install the corresponding extension package:
pip install sqlalchemy
Then, introduce and configure the database in the application:
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = '数据库连接' db = SQLAlchemy(app) class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), unique=True) password = db.Column(db.String(100))
In the above code, we define a User model class and specify its The corresponding database field.
8. Multi-page application
In actual applications, there may be multiple views and multiple templates. To reduce code redundancy, we can use blueprints to organize views and templates. First, we need to create a Blueprint object:
from flask import Blueprint main_bp = Blueprint('main', __name__)
Then, associate the view functions and templates with the Blueprint:
@main_bp.route('/') def index(): return render_template('index.html')
Finally, register the Blueprint in the application:
from app import main_bp app.register_blueprint(main_bp)
Conclusion:
Through the guidance of this article, readers can understand the basic usage of the Flask framework, and learn skills such as creating Flask applications, defining routing and view functions, rendering templates, processing forms, database operations, and using blueprints to organize code. I hope this article can help readers quickly get started with the Flask framework and develop their own small web applications.
The above is the detailed content of Small application development guide for the Flask framework. For more information, please follow other related articles on the PHP Chinese website!