需要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, requestapp = 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("123456")print(age, pwd)return "成功"
完整代码
from flask import Flask, requestapp = 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("123456")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的对比
参考资料
[1] 【最快速度搞定Flask-框架教程】01~04