[Python] flask framework to learn the basic use of flask framework

What is the flask framework?

Flask is a lightweight web framework for building web applications. Based on the Python programming language and the Werkzeug toolkit, it provides an easy-to-use API that makes it easy to create RESTful APIs and web applications.

Features of flask

  • Lightweight: The Flask framework is very lightweight, the code base is small, and it is easy to learn and use.
  • Flexible: Flask provides many plugins and extensions to flexibly build web applications as needed.
  • Easy to extend: The Flask framework is easily extensible and many custom features can be added.
  • Template engine: Flask provides Jinja2 template engine, which can easily build dynamic pages.
  • ORM: Flask provides the SQLAlchemy ORM to easily interact with databases.
  • RESTful API: The Flask framework provides the Flask-RESTful extension to easily build RESTful APIs.
  • Plug-in mechanism: Flask provides a rich plug-in mechanism, which can add custom functions as needed.

Advantages of the flask framework

  • Ease of use: The Flask framework is easy to use and has low learning costs, making it suitable for quickly building web applications.
  • Strong flexibility: Flask provides many extensions and plug-ins, which can flexibly build web applications according to needs.
  • Ease of Extensibility: The Flask framework is easily extensible and many custom features can be added.
  • Powerful template engine: Flask provides Jinja2 template engine, which can easily build dynamic pages.
  • Powerful ORM: Flask provides the SQLAlchemy ORM to easily interact with databases.
  • Support for RESTful API: The Flask framework provides the Flask-RESTful extension to easily build RESTful APIs.
  • Rich plug-ins: Flask provides a rich plug-in mechanism, which can add custom functions as needed.

In short, the Flask framework is a web framework that is lightweight, flexible, easy to expand, powerful template engine, ORM, supports RESTful API and rich plug-in mechanism, and can help developers quickly build high-quality web applications.

Basic use of the flask framework

The flask framework can easily build the most basic server program, just run the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return "hello world"

if __name__ == '__main__':
    app.run(debug=True)

This piece of code first imports the Flask class in the flask library. The instance of this class will become our WSGI application. app is the instantiated application, and then use the decoration class to make the web application process the request whose request information is "/". .

Running result:
insert image description here
Open the given link:
insert image description here
You will find that the page returns the string of hello world under the url, indicating that the web application of the simplest flask framework has been built.

Note: 127.0.0.1 and 0.0.0.0 are local addresses, and 5000 is the port number

Routing, variables, and url rules

routing

A route is a page or URL to jump to in a web application. In Flask, routes are defined using the route() function.

For example, the following code:

from flask import Flask
app = Flask(__name__)
# 路由

@app.route('/')
def index():
    return "hello world!"

@app.route('/hello/<name>')
def home(name):
    return "hello " + name

@app.route('/blg/<int:postID>')
def postid(postID):
    return postID

if __name__ == '__main__':
    app.run()

If you access the root directory on port 5000:
insert image description here

If you visit hello/xiaoming:
insert image description here

variable

Variables are a special kind of data used in routing. They can be passed to view functions in route parameters. There are several variable types in the Flask framework, including:

  • request: The object used to handle client requests.
  • session: An object used to store session data.
  • route: A variable used to identify a specific route.

To use variables in Flask routes, simply put them in variable strings and refer to them in view functions. For example, to define a variable called /users/ in the URL, you could use the following code:

from flask import Flask, render_template  
  
app = Flask(__name__)  
  
@app.route('/users/<name>')  
def users(name):  
    return render_template('users.html', users=[name])

The code above first imports the Flask library, creates an application instance, and defines a variable named /users/ in the app.route() function. This variable has a variable named name. In the users.html template, you can use { { name }} to refer to this variable.

URL rules

URL rules refer to some special characters used in URLs. They can be used to specify how requests are handled, for example:

  • /users: handles all requests whose URL starts with /users.
  • /users/: Handles all requests whose URL starts with /users/.
  • /users//: Handle all requests whose URL starts with /users//.

To use URL rules in a Flask route, simply use the corresponding prefix and suffix in the route's parameters. For example, to define a variable called /users// in the URL, you could use the following code:

from flask import Flask, render_template  
  
app = Flask(__name__)  
  
@app.route('/users/<name>/<sub-path>')  
def users(name, sub_path):  
    return render_template('users.html', users=[name], sub_path=sub_path)

The code above first imports the Flask library, creates an application instance, and defines a variable called /users/<name>/<sub-path> in the app.route() function. This variable has a variable called name and a variable called sub_path. In the users.html template, you can use { { sub_path }} to refer to this variable. Note that different variable types and routing parameters are used to distinguish different requests.

template for flask

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True,threaded=True)

After running this code, the server will look for the index.html file from the templates directory of the file and display it on the page.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>Nihao</h1>
</body>
</html>

This is index.html

operation result:
insert image description here

Flask.render_template is the core function in Flask for rendering templates. This function takes a template string as an argument and renders it as HTML.

The following is the basic usage of Flask.render_template:

from flask import Flask, render_template  
  
app = Flask(__name__)  
  
@app.route('/')  
def index():  
    return render_template('index.html', name='World')  
  
@app.route('/hello')  
def hello():  
    name = 'John'  
    return render_template('hello.html', name=name)

We define two routing functions index and hello, which both receive a template string as a parameter. In the index function, we set the name variable to 'World' and pass it as an argument to the render_template function to render the template. In the hello function, we set the name variable to 'John' and pass it as an argument to the render_template function to render the template.

When we run the Flask application, it will load the index.html and hello.html templates and render them to the corresponding HTML.

When rendering a template, Flask will interpolate the variable into the template string and pass it as an argument to the render_template function. When the template is rendered, Flask will insert these variables as parameters into the HTML and return the resulting HTML string.

Static files, redirects and errors

In Flask, static files, redirects, and error handling are very important concepts that play a vital role in the proper functioning of an application. Their implementation and application scenarios in Flask will be discussed in detail below.

  • Static files
    Static files are files stored on the server, usually used to store data and resources. In Flask, static files are typically used to store application configuration information, logs, stylesheets, etc.

To use static files, you need to create a folder in your Flask application to store the static files. Then, in the application's main file, use the url_for() function to refer to the static file. For example:

from flask import Flask, render_template  
  
app = Flask(__name__)  
  
@app.route('/')  
def index():  
    return render_template('index.html', name='World')  
  
if __name__ == '__main__':  
    # 创建静态文件夹  
    app.config['UPLOAD_FOLDER'] = 'static'  
  
    # 引用静态文件  
    static_folder = '../static'  
    app.url_for('static', filename=static_folder)

In this code, we create a folder named static in the application's main folder, and then use the url_for() function in the application's index function to reference the static file. This way, when the application is running, the static files are automatically loaded and displayed in the browser.

  • Redirection
    Redirection is the process of redirecting a user to another location. In Flask, redirection is mainly divided into two types: ① static redirection (URL redir): redirect the user to another static folder; ② dynamic redirection (URL redirect): redirect the user to another page .

For static redirects, just create the corresponding files in the static folder. For dynamic redirection, you need to use the Flask router to achieve it. Here is an example of a dynamic redirection:

from flask import Flask, render_template, redirect, url_for, request, send_from_directory  
  
app = Flask(__name__)  
app.config['UPLOAD_FOLDER'] = 'static'  
  
@app.route('/users', methods=['GET', 'POST'])  
def users():  
    if request.method == 'POST':  
        # 获取新用户信息并进行处理  
        new_user = request.form['new_user']  
        # 进行重定向操作  
        url = url_for('user', username=new_user)  
        return redirect(url)  
    else:  
        # 显示列表页面  
        return render_template('users.html')

cookies and sessions

In the Flask framework, cookies and sessions are used to store and manage user data.

Cookies are a common way of storing user data, and are usually used to store some simple data in user sessions, such as user preferences, login status, etc. Flask uses SessionCookieJar by default to manage cookies.

When a user visits a Flask application in a browser, the browser stores cookies on the local computer. When the user closes the browser and reopens it, the browser reloads the cookies on the user's computer so that the user can access previously saved data.

To use cookies in Flask, you need to add the secret_key parameter to the route handler, which specifies the cookie's security key.

from flask import Flask, render_template, request, redirect,session

app = Flask(__name__)
app.secret_key = 'my_secret_key'


@app.route('/')
def index():
    return render_template('index.html')


@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        # 获取用户输入的用户名和密码  
        username = request.form['username']
        password = request.form['password']

        # 在数据库中添加登录记录  
        if username == 'my_username' and password == 'my_password':
            session['username'] = username
            return redirect('/')
        else:
            return render_template('login.html', error='Invalid username or password')

    return render_template('index.html')

if __name__ == '__main__':
    app.run()

We used the secret_key parameter in the /login route handler to specify the cookie's security key. Thus, when the user revisits the application, the browser reloads the cookie on the user's computer so that the user can access previously saved data.

In addition, Flask also provides the concept of session (session), which is used to store more complex data in user sessions, such as user preferences, login status, etc. Sessions are usually implemented by storing data on the server side rather than on the client side.

conversation

In Flask, sessions are implemented using the Flask-Session module. To use sessions in Flask, you need to add a secret_key parameter to your route handler, which specifies the session's secret key.

from flask import Flask, render_template, request, redirect, url_for  
from flask_session import Session  
  
app = Flask(__name__)  
app.secret_key = 'my_secret_key'  
  
@app.route('/')  
def index():  
    return render_template('index.html')  
  
@app.route('/login', methods=['GET', 'POST'])  
def login():  
    if request.method == 'POST':  
        # 获取用户输入的用户名和密码  
        username = request.form['username']  
        password = request.form['password']  
  
        # 在数据库中添加登录记录  
        if username == 'my_username' and password

news flash

Flash in the Flask framework is a technique for displaying short reminders in web applications. Flash can be used when there is some very important information that needs to be communicated to the user immediately when the user is interacting with the application.

To use Flask Flash, you need to use the flash parameter in the view function to store the prompt information to be displayed. Then, use the flash.get() method to check if the prompt has already been displayed before the prompt is displayed. If the hint already exists, replace it with the new hint; otherwise, add the hint to the Flash object.

from flask import Flask, flash  
  
app = Flask(__name__)  
  
@app.route('/')  
def index():  
    flash('This is a flash message!')  
    return 'Hello, World!'

This is the code for a message flash. When the user interacts with the application, the prompt information stored in the flash object will be displayed. In this case, the prompt message is "This is a flash message!". After the user interacts with the application, the hint information in the flash object will be automatically deleted.

File Upload

Handling file uploads in Flask is very simple. It takes an HTML form with the enctype attribute set to "multipart/form-data" and posts the file to a URL.

The URL handler extracts the files from the request.files[] object and saves them to the desired location. Each uploaded file is first saved in a temporary location on the server before actually saving it to its final location. The name of the target file can be hard-coded or obtained from the filename property of the request.files[file] object.

from flask import Flask, request, jsonify  
  
app = Flask(__name__)  
  
@app.route('/upload', methods=['POST'])  
def upload_file():  
    # 检查是否有文件被上传  
    if 'file' not in request.files:  
        return jsonify({
    
    'error': 'No file uploaded.'}), 400  
  
    file = request.files['file']  
  
    # 安全保存文件到磁盘  
    file.save(os.path.join(app.config['UPLOAD_FOLDER'], file.filename))  
  
    return jsonify({
    
    'success': True}), 200

When a user uploads a file, a request.files['file'] object will be created and saved to the specified file path. The file will then be saved securely to the specified location on the server. Finally, the response will contain a success message with a key value of "success" indicating that the upload was successful.

Guess you like

Origin blog.csdn.net/fuhao6363/article/details/130464956