【Flask 3.1.2】2 获取请求数据与返回json数据
需要request包
获取请求数据
GET 方式请求(默认)
关键代码
# http://127.0.0.1:5000/index 执行index() GET
# http://127.0.0.1:5000/index?age=18&pwd=123456 执行index() GET 默认
@app.route("/index")
def index():
age = request.args.get("age") # 获取用户url传递过来的参数
pwd = request.args.get("pwd")
print(age, pwd)
return "成功"
完整代码
from flask import Flask, request
app = Flask(__name__)
# http://127.0.0.1:5000/index 执行index() GET
# http://127.0.0.1:5000/index?age=18&pwd=123456 执行index() GET 默认
@app.route("/index")
def index():
age = request.args.get("age") # 获取用户url传递过来的参数
pwd = request.args.get("pwd")
print(age, pwd)
return "成功"
@app.route("/home")
def home():
return "失败"
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
POST 方式请求
可以在请求体中包含一些数据
关键代码
# http://127.0.0.1:5000/index 执行index() POST
@app.route("/index", methods=["POST", "GET"])
def index():
age = request.form.get("age") # 获取用户请求体传递过来的参数
pwd = request.form.get("pwd")
print(age, pwd)
return "成功"
完整代码
from flask import Flask, request
app = Flask(__name__)
# http://127.0.0.1:5000/index 执行index() GET
# http://127.0.0.1:5000/index?age=18&pwd=123456 执行index() GET 默认
# http://127.0.0.1:5000/index 执行index() POST
@app.route("/index", methods=["POST", "GET"])
def index():
age = request.form.get("age") # 获取用户请求体传递过来的参数
pwd = request.form.get("pwd")
print(age, pwd)
return "成功"
@app.route("/home")
def home():
return "失败"
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
写一个小脚本post.py来模拟发送POST请求
import requests
# 目标URL
url = "http://127.0.0.1:5000/index"
# 要发送的请求体数据(字典形式)
data = {
"age": "18",
"pwd": "123456"
}
# 发送POST请求
response = requests.post(url, data=data)
# 处理响应
print("状态码:", response.status_code) # 200表示成功
print("响应内容:", response.text) # 响应的文本内容
# 如果响应是JSON格式,可以直接解析
if response.status_code == 200:
try:
json_data = response.json()
print("JSON响应:", json_data)
except ValueError:
print("响应不是JSON格式")
可以看到返回
Flask后台返回
GET与 POST的对比
返回json结果
关键代码
return jsonify({'status': True, 'data': "hello, flask"})
完整代码
from flask import Flask, request, jsonify
app = Flask(__name__)
# http://127.0.0.1:5000/index 执行index() GET
# http://127.0.0.1:5000/index?age=18&pwd=123456 执行index() GET 默认
# http://127.0.0.1:5000/index 执行index() POST
@app.route("/index", methods=["POST", "GET"])
def index():
age = request.form.get("age") # 获取用户请求体传递过来的参数
pwd = request.form.get("pwd")
print(age, pwd)
return jsonify({'status': True, 'data': "hello, flask"})
@app.route("/home")
def home():
return "失败"
if __name__ == '__main__':
app.run(host="127.0.0.1", port=5000)
请求端可以看到返回的结果
服务器端可以正确接收
网页可以正常显示