Table of contents
2 commonly used web frameworks in python
3.1 Flask framework installation
3.3.4 Multiple routes bound to a view function
3.3.5 Routing to access URL parameters
3.3.6 Dynamic routing with default values
3.3.7 Dynamic routing with different data types
1 Web framework
A Web Framework is a set of software tools designed to simplify and speed up the development of Web applications. It provides a set of pre-designed modules, functions, classes, and tools to help developers build and maintain feature-rich Web applications more easily. By using a web framework, developers can avoid writing large amounts of repetitive code from scratch and focus on the business logic and core functionality of the application.
The functionality of the web framework is as follows:
Routing and URL processing: Web frameworks usually provide routing functions, allowing developers to map different URLs to corresponding processing functions or views. This makes the URL structure clearer and can easily handle different requests.
Template engine: Template engine allows developers to combine HTML and dynamic data to generate dynamic Web pages. They usually provide functions such as conditional statements, loops, and variable substitution to help developers efficiently generate page content.
Database interaction: Web frameworks often provide a database abstraction layer that simplifies interaction with the database. This enables developers to more easily perform database queries, inserts, updates, and deletes.
Form processing: Web applications often need to process form data submitted by users. Web frameworks typically provide mechanisms to validate form data, handle submissions, and generate responses.
Session Management: Many web applications need to track the user's session state. Web frameworks usually provide session management functions so that developers can easily manage user sessions and states.
Promote code reuse
2 commonly used web frameworks in python
In Python, there are many commonly used web frameworks to choose from. Here are some common Python web frameworks:
1. Flask: Flask is a micro, flexible web framework with concise syntax and powerful expansion capabilities. It's great for building small, lightweight applications.
2. Django: Django is a full-featured web framework that provides many out-of-the-box features, such as database ORM, user authentication, caching, etc. Django's design concept is "loosely coupled" components, making the development process more efficient.
3. Pyramid: Pyramid is a lightweight web framework that focuses on flexibility and scalability. It uses a plugin-like mechanism that allows developers to selectively add or remove functionality from the framework.
4. Bottle: Bottle is a small and easy-to-use web framework with minimal dependencies and a single source file. Bottle is great for building small, fast applications.
5. Tornado: Tornado is a high-performance web framework that uses non-blocking I/O and event-driven methods to handle requests. Tornado is suitable for handling high-concurrency situations, such as chat applications and real-time data push.
3 Use of Flask framework
3.1 Flask framework installation
Flask depends on two external libraries: Werkzeug and Jinja2. Werkzeug is a WSGI toolset and Jinja2 is responsible for rendering templates. This article is installed in the virtual environment created by annconda, as follows:
pip install flask
as follows
(venv) PS D:\python365> pip install flask
Collecting flask
Downloading flask-2.3.3-py3-none-any.whl (96 kB)
---------------------------------------- 96.1/96.1 kB 365.4 kB/s eta 0:00:00
Collecting importlib-metadata>=3.6.0
Downloading importlib_metadata-6.8.0-py3-none-any.whl (22 kB)
Requirement already satisfied: Jinja2>=3.1.2 in d:\python365\venv\lib\site-packages (from flask) (3.1.2)
Collecting colorama
Downloading colorama-0.4.6-py2.py3-none-any.whl (25 kB)
Requirement already satisfied: zipp>=0.5 in d:\python365\venv\lib\site-packages (from importlib-metadata>=3.6.0->flask) (3.16.2)
Requirement already satisfied: MarkupSafe>=2.0 in d:\python365\venv\lib\site-packages (from Jinja2>=3.1.2->flask) (2.1.3)
Installing collected packages: Werkzeug, itsdangerous, importlib-metadata, colorama, blinker, click, flask
Successfully installed Werkzeug-2.3.7 blinker-1.6.2 click-8.1.7 colorama-0.4.6 flask-2.3.3 importlib-metadata-6.8.0 itsdangerous-2.1.2
[notice] A new release of pip available: 22.3.1 -> 23.2.1
[notice] To update, run: python.exe -m pip install --upgrade pip
(venv) PS D:\python365>
3.2 The first Flask program
After the installation is complete, write your first Flask program. Here's an example of a simple Flask program that creates a basic web application and returns a "Hello, Flask!" message when a specific URL is visited:
from flask import Flask
# 创建 Flask 应用实例
app = Flask(__name__)
# 定义路由和视图函数
@app.route('/')
def hello():
return "Hello, Flask!"
# 如果这个文件是作为主程序运行,则执行下面的代码
if __name__ == '__main__':
app.run(debug=True)
The output is as follows:
Enter the URL in the browser: http://127.0.0.1:5000 , as follows:
The above code uses Python's Flask framework to create a simple web application.
First, you need to import the Flask library. Then, create a Flask application instance with the name of the current module as a parameter, i.e.
__name__
.Next, use a decorator
@app.route('/')
to define the route, which specifies the URL path. In this example, the root path '/' represents the application's default page.Then, define a view function
hello()
that will be called when the user accesses the root path. This function returns a string "Hello, Flask!" as a response to the user.Finally,
app.run()
run the application through the method, start a local server, listen for HTTP requests and return corresponding results. Settingsdebug=True
can enable debug mode.If you run this file as the main program,
app.run()
the statements will be executed, the application will be started, and debugging information will be output to the terminal.
3.3 Routing
In Flask, routing is used to associate a specific URL path with a corresponding view function. Routing determines which view function should be executed to handle the request when the user visits a different URL. Routes can be defined using decorators @app.route()
.
Here are some examples of route definitions for different situations:
3.3.1 Basic routing
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "Welcome to the homepage!"
In this example, when the user visits the root path
/
, the view function named is calledindex()
and returns the message "Welcome to the homepage!".
3.3.2 Dynamic routing
You can use variable parts in routes to capture different values in the URL. These variables will be passed as parameters to the view function.
@app.route('/user/<username>')
def show_user_profile(username):
return f"User: {username}"
In this example, when the user accesses /user/johndoe
a path like , show_user_profile()
the view function will be called and the parameters username
will receive values "johndoe"
.
3.3.3 HTTP methods
You can handle different requests by specifying different HTTP methods, such as GET, POST, PUT, DELETE, etc.
@app.route('/submit', methods=['POST'])
def submit_form():
return "Form submitted successfully!"
In this example, the view function
/submit
is called only when the user accesses the path using the POST methodsubmit_form()
.
Common HTTP methods and descriptions:
3.3.4 Multiple routes bound to a view function
You can bind multiple different paths to the same view function to provide more access options.
@app.route('/')
@app.route('/home')
@app.route('/index')
def homepage():
return "Welcome to the homepage!"
Here, whether the user accesses the root path
/
or the view function will be called ./home
/index
homepage()
3.3.5 Routing to access URL parameters
You can access URL parameters in the view function, and these parameters will be automatically parsed by Flask and passed to the view function.
from flask import request
@app.route('/profile')
def user_profile():
username = request.args.get('username')
return f"User profile: {username}"
The sample code defines a route
/profile
that calls a view function named when a user accesses the pathuser_profile()
. In this view function,request
an object is used to obtainusername
the value of the URL parameter and then returns a message containing the user name.
3.3.6 Dynamic routing with default values
@app.route('/user/<username>/<int:age>')
def user_profile(username, age=18):
return f"User: {username}, Age: {age}"
In this example,
age
the parameter has a default value of 18. This means you can/user/johndoe
access it via , not just/user/johndoe/25
.
3.3.7 Dynamic routing with different data types
@app.route('/item/<int:item_id>')
def get_item(item_id):
return f"Item ID: {item_id}"
Here,
item_id
only values of integer type will be matched, and if accessed/item/123
,item_id
will be passed as the integer 123.
These are some examples of route definitions for common situations. By properly defining routes, you can build web applications that are logically clear and easy to access. Note that the route definition should be placed @app.route()
immediately below the decorator followed by the corresponding view function definition.
3.4 Static files
In Flask, static files refer to resources that do not need to be dynamically generated, such as style sheets, JavaScript files, images, etc. These files are not generated by the server on every request, but are returned directly to the client browser. Flask provides specialized routing and configuration for handling static files.
static
By default, Flask creates a folder named in the application root directory to store static files. You can create subfolders in it to organize different types of static resources, such as static/css
stylesheets and static/js
JavaScript files.
Here are the basic steps of how to handle static files in Flask:
static
Create a folder in the project root directory to store static files. Subfolders can be created in it to organize different types of static resources, for examplestatic/css
.static/js
Use
url_for()
the function to generate URLs for static files. This function will generate the correct URL according to the configuration to ensure that the static files are accessed correctly.
Here is a simple example showing how to handle static files in Flask:
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run()
In this example, render_template('index.html')
the function is used to render the template, which may need to load static files. For example, to load a stylesheet in a template:
<!DOCTYPE html>
<html>
<head>
<title>Flask Static Files</title>
<link rel="stylesheet" href="{
{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<h1>Hello, Flask!</h1>
</body>
</html>
In this example,
url_for('static', filename='css/style.css')
the correct static file URL is generated.'static'
It is the default static file directory in Flask and'css/style.css'
is the path relative to this directory.Make sure to use in the template
url_for()
to generate URLs for static files so that they can be accessed correctly in different environments. This way, you can efficiently serve static files in your Flask application.
3.5 Template
In Flask, templates are used to render dynamic data into HTML pages to achieve dynamic generation of page content. Flask integrates the Jinja2 template engine, which allows you to embed Python code in HTML to render data. This approach separates the business logic from the interface and improves the maintainability of the code.
Here are the basic steps for using templates in Flask:
templates
Create a folder named under the project root directory to store template files. These template files can use Jinja2 syntax.Use functions in view functions
render_template()
to render templates and pass data.Use Jinja2 syntax to embed dynamic content and control structures in templates.
Here is a simple example showing how to use templates in Flask:
- Create a
templates
folder named and aindex.html
template file named inside it.
templates/index.html
document content:
<!DOCTYPE html>
<html>
<head>
<title>Flask Template Example</title>
</head>
<body>
<h1>Hello, {
{ name }}!</h1>
<p>Today is {
{ date }}</p>
</body>
</html>
Create a Flask application that uses render_template()
the function to render templates and pass data.
from flask import Flask, render_template
import datetime
app = Flask(__name__)
@app.route('/')
def index():
current_date = datetime.datetime.now()
return render_template('index.html', name='Flask User', date=current_date)
if __name__ == '__main__':
app.run()
In this example, the template
render_template('index.html', name='Flask User', date=current_date)
is renderedindex.html
, passingname
the anddate
variables. In templates, you can use{ { variable_name }}
to insert dynamic content. Go to the root of your application in your browser and you should see "Hello, Flask User!" and the current date.This is just a simple Flask template example. You can use more Jinja2 features in the template, such as conditional statements, loops, filters, etc., to build more complex dynamic pages.