1. Introduction
Flask is a lightweight and customizable framework, written in Python language, which is more flexible, lightweight, safe and easy to use than other similar frameworks. Flask is a micro-framework based on Python development and relies on jinja2 templates and Werkzeug WSGI services . Here we briefly introduce the use of flask to mock a server, which is convenient for testing and mock testing before the corresponding service function development is completed.
Install:
# 安装flask
pip install flask
# 验证flask
pip show flask
Two, Flask is simple to use
1. Configuration file
2. Routing system
1) Dynamic routing (url parameter passing), the sample code is as follows:
from flask import Flask
# 创建1个Flask实例
app = Flask(__name__)
# 设置一个动态参数name
@app.route('/<name>')
# 视图必须有对应的接收参数name
def first_flask(name):
print(name)
return "Hello World~"
if __name__ == '__main__':
app.run(debug=True)
After executing the code, access the service link, add the name "yoyo" to the path, and the effect is as follows:
2) Specify the allowed request method
@app.route('/login', methods=['GET', 'POST'])
3. Request request parameter acquisition
1) Post request parameter acquisition
request.get_data(), request.data, get unprocessed raw request data regardless of the content type, if the data format is json, then get a json string; request.get_json(), and request.json
, The request parameters are processed, and the result is in dictionary format, so the sorting will disrupt the sorting rules based on the dictionary.
Client request code:
Server code:
from flask import Flask, request
# 创建1个Flask实例
app = Flask(__name__)
# 设置一个动态参数name
@app.route('/', methods=['GET', 'POST'])
# 视图函数
def first_flask():
# 1. request.get_data()、request.data,获取未经处理过的原始请求数据而不管内容类型,如果数据格式是json的,则取得的是json字符串
a = request.get_data()
print(a)
print(type(a))
b = request.data
print(b)
print(type(b))
# 2.request.get_json(),和request.json,将请求参数做了处理,得到的是字典格式的,因此排序会打乱依据字典排序规则
c = request.get_json()
print(c)
print(type(c))
name = request.get_json()['name']
print(f"name的值是:{name}")
d = request.json
print(d)
print(type(d))
return "Hello World~"
if __name__ == '__main__':
app.run(debug=True)
2) get request parameter acquisition
Client code:
Server code:
from flask import Flask, request
# 创建1个Flask实例
app = Flask(__name__)
# 设置一个动态参数name
@app.route('/', methods=['GET', 'POST'])
# 视图函数
def first_flask():
# get请求参数
# 获取到单个的值
e = request.args.get('name')
print(f'获取name的值为:{e}')
# 可以获取get请求的所有参数返回值是ImmutableMultiDict(不可变的多字典)类型
f = request.args
print(f)
# 将获得的参数转换为字典
g = request.args.to_dict()
print(g)
print(type(g))
return "Hello World~"
if __name__ == '__main__':
app.run(debug=True)
The server prints the result:
There are also some common methods, such as:
request.headers : Get request headers
request.method: get method
request.url: Get the access url address, such as http://127.0.0.1:5000/?name=yoyo&age=17
request.cookies: get request cookies
3. Mock login and query user information scenarios
Server code:
from flask import Flask, request, jsonify
app = Flask(__name__)
# 解决接收报文中文乱码问题
app.config['JSON_AS_ASCII'] =False
@app.route('/api/login', methods=['POST'], strict_slashes=False)
def login():
'''登录接口'''
# 调试信息,打印请求方法
print(request.method)
# 获取请求数据,将数据变为字典
data = request.get_json()
print(data)
# 定义用户名和密码变量,从data中取值
username = data['username']
pwd = data['password']
'''
测试场景设计
1)参数为空
2)用户名密码正确
3)用户名或密码错误
'''
if username == '' or pwd == '':
return jsonify({"code": "001",
"msg": "用户名或密码不能为空"})
elif username == 'yoyo' and pwd == '123456':
return jsonify({"code": "002",
"msg": "登录成功",
"info": {
"age": 18,
"name": "yoyo"},
"token": "23657DGYUSGD126731638712GE18271H"
})
else:
return jsonify(
{
"code": "001",
"msg": "用户名或密码错误"
}
)
# 查询个人用户信息接口
@app.route('/api/userinfo', methods=['GET'], strict_slashes=False)
def api_userinfo():
# 获取请求头的token
token = request.headers.get('token')
if token == "23657DGYUSGD126731638712GE18271H":
return jsonify({
"httpstatus": 200,
"data": {
"userid": 321411,
"username": "yoyo",
"userbalance": 5678.90,
"userpoints": 4215
}
})
else:
return jsonify(
{"code": "1000",
"msg": "用户信息不正确"}
)
if __name__ == '__main__':
app.run(debug=True)
illustrate:
1) # In the routing configuration, strict_slashes=False is strictly required for the / symbol at the end of the URL
For example: @app.route('/index', strict_slashes=False) #Visit http://www.xx.com/index/ or http://www.xx.com/index is available
@app.route('/index',strict_slashes=True) #Only visit http://www.xx.com/index
2) In the Flask framework, jsonify can be used to return json data. When using jsonify, the Content-Type of the returned http response is application/json, which complies with the provisions of the HTTP protocol
Client code and request result: