网上教程一大堆,这里就不写详细教程了,只记录一些我认为有用的知识点。

基础

返回值要是字符串或相关类型

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

Flask 要求返回的是 字符串、响应对象(Response) 或者可以被转换成响应的内容类型。

这里如果直接

return 666

会报错。

获取用户访问参数

# 访问http://127.0.0.1:5000/?id=1234&pwd=mima
@app.route('/')
def index():
    id = request.args.get('id')
    pwd = request.args.get('pwd')
    print(id,pwd)
    return '666'

设置请求方法(post,get)

## 访问http://127.0.0.1:5000/?id=1234&pwd=mima
@app.route('/',methods=['GET','POST'])
def index():
    id = request.args.get('id')
    pwd = request.args.get('pwd')
    print(id,pwd)
    return '666'

不填写methods就默认只接受get请求

POST请求

请求体

# 访问http://127.0.0.1:5000/?id=1234&pwd=mima
# 请求体
#     id=666&pwd=888
@app.route('/',methods=['GET','POST'])
def index():
    id1 = request.args.get('id')
    pwd1 = request.args.get('pwd')
    print(id1,pwd1)
    id2 = request.form.get('id')
    pwd2 = request.form.get('pwd')
    print(id2, pwd2)
    return '666'

请求体和参数

JSON

# 访问http://127.0.0.1:5000/?id=1234&pwd=mima
# 请求体(json数据)
# {
#   "id":666,
#   "pwd":"hhh"
# }
@app.route('/',methods=['GET','POST'])
def index():
    id1 = request.args.get('id')
    pwd1 = request.args.get('pwd')
    print(id1,pwd1)
    print(request.json)
    return '666'

JSON

返回值

返回json数据

# 访问http://127.0.0.1:5000
@app.route('/',methods=['GET','POST'])
def index():
    return jsonify({'code':'True','data':'hhhhhhhh'})
# 需要导入flask的jsonfiy

最后修改:2025 年 07 月 21 日