本文介绍了Flask框架的基础知识,包括正确的返回值类型、获取用户访问参数、设置请求方法、处理POST请求和返回JSON数据。强调了返回值应为字符串或可转换为响应的类型,展示了如何获取GET和POST请求中的参数,以及如何返回JSON格式的数据。
网上教程一大堆,这里就不写详细教程了,只记录一些我认为有用的知识点。
基础
返回值要是字符串或相关类型
@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数据
# 访问http://127.0.0.1:5000
@app.route('/',methods=['GET','POST'])
def index():
return jsonify({'code':'True','data':'hhhhhhhh'})
# 需要导入flask的jsonfiy
1 条评论
hello