Python Flask practical tips: interface implementation | manipulate database, etc.

Article Directory

1. Introduction to Flask

Flask is a lightweight web development framework based on the Python language, which can be quickly installed through the pip command

pip install flask

Recommended bibliography: "Flask Web Development: Python-based Web Application Development Actual Combat"

Two, start the server

You can quickly build Web services by writing simple code

from flask import Flask

app = Flask(__name__)

# 主页
def index():
    return "Hi Flask!"

if __name__ == '__main__':
    app.debug=True  # 默认开启debug模式
    # host= port=5000'', 5000)

Running the above .pyfile will open the Flask server on the local 5000 port

Concept Supplement-Decorator syntax and routing

Python decorator syntax
Encapsulate a function with a function
Use @anotherFunctionName before function A, which means that function A is passed into anotherFunctionName as a parameter, and it is modified to run by anotherFunctionName

route is routing, used in flask in the form of decorator syntax. Take 👇 code as an example: @app.route('/')used to decorate the index()function, indicating that the content of the root directory page will be index()determined by the return value of the function

# 主页
def index():
    return "Hi Flask!"
Implement dynamic routing

Dynamic routing can also be easily implemented in Flask (responding to different page content as the routing changes)

@app.route('/user/<name>')	# <name> 就是可变部分
def user(name):	# name作为函数的参数被获得
    return '<h1>Hello,{}!</h1>'.format(name)

Using dynamic routing, you can easily "customize" personalized pages for any user

Three, configure cross-domain access

When using a front-end and back-end separation architecture, resources are often requested across domains. If you see this error in the browser console:CORS policy

Access to XMLHttpRequest at ‘xxx’ from origin ‘xxx’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

It indicates that the server needs to be configured to allow cross-domain access. In Flask, there are mature third-party libraries that can solve this problem. You need to modify your .pycode like this 👇

from flask_cors import *	# pip install flask_cors

app = Flask(__name__)
CORS(app, resources=r'/*')	# 允许任意主机请求资源

Four, static file path

The server always uses static files when rendering the page. When preparing static files for Flask, there are strict directory format regulations:

    | - (flask APP - 你的flask服务器.py文件)
    | - templates (模板文件夹 - 模板 会在 五、模板渲染 中提到)
    |           | - a.html (网页模板a)
    |           | - b.html (网页模板b)
    |           | - c.html (网页模板c)
    |			...
    | - static (静态文件文件夹)
            | - images (图片文件夹)
            | - srcipts (js文件夹)
            | - styles (css文件夹)

The templates and static directories are required, and they must be in the same directory as your server's .py file. As for their contents, they are variable. In order to use static files, make a little modification to your code

# app = Flask(__name__)
# 指定静态文件目录
app = Flask(__name__,static_url_path='/static/',template_folder='templates')

Five, template rendering

Using the same set of templates to render different pages, for traditional static web development, the advantages of template rendering are self-evident. Remember the templates folder, it is used to store web page templates.
Using render_template()method, you can quickly render the template in the folder into a page👇

from flask render_template
def user_page(user):
    return render_template("user.html",user = user)

How to write a website template

The user is passed to the template as a parameter. To use parameters in the template, your template page (the template page is in html+css+js format) needs to follow the following syntax, that is, use double curly braces { {}} to wrap your variables


In addition, simple control statements can also be used in the template: branch and loop

ps: If the template { {}} syntax and other front-end library conflicts (such vue), can be used {% raw %}and {% endraw %}separate the different parts, tell jinja2 (Flask template engine) of its terms of reference:

{% raw %}
{% endraw %}

Six, realize the GET/POST interface

Here are two demo examples directly


from flask import request
import json

@app.route('/api/get_name', methods=['GET'])
def get_name():
    comment here
    # value=request.args.get('key') # 想用GET传参?你可以这样获取参数
	# 把结果格式化为json形式回传
    return json.dumps({'result':result},ensure_ascii=False)


from flask import request
import json

@app.route('/api/post_sth', methods=['POST'])
def post_sth():
    comment here
    value=request.form['key']	# 获取表单传来的数据
    # 把结果格式化为json形式回传
    return json.dumps({'result':result},ensure_ascii=False)

Seven, use pymysql to manipulate MySQL database

The syntax of linking the database is fixed, but you should pay attention to the issue of MySQL version. 5.7 and 8.0 use different link syntax

import pymysql

db = pymysql.connect(host='主机ip', user='用户名', password='密码', database='数据库名') # MySQL 5.7

# db = pymysql.connect("主机ip","用户名","密码","数据库名" ) # MySQL 8.0
cursor = db.cursor()    # 创建一个游标对象


cursor.execute(sql) # 执行语句
data=cursor.fetchall()  # 获取元组形式查询结果 .fatchone()方法获取单条数据
db.close() # 关闭连接

Attachment: Flask commonly used code generator

Flask's common functional grammar frameworks are mostly fixed. To facilitate and quickly build flask applications, I wrote a Flask basic code generator : fixed templates like GET/POST interfaces, database operations, etc. are included; one-click copy of the selected demo, welcome to try it😋