【Flask】Flask中HTTP请求与接收

发布于:2024-04-24 ⋅ 阅读:(24) ⋅ 点赞:(0)

一、接收http请求与返回响应

在Flask中,可以通过@app.route装饰器来定义路由函数。

@app.route('/BringGoods',methods = ['POST', 'GET'])

GET请求:使用request.args.get('key')或者request.values.get('key')来获取URL中的参数。

POST请求:

  • 使用request.form.get('key')或者request.form['key']来获取表单数据;
  • 使用request.json.get('key')或者request.get_json()['key']来获取JSON数据
  • 使用request.files来访问上传的文件。

实例代码:

@app.route('/BringGoods',methods = ['POST', 'GET'])
def bringgoods():
    if request.method == 'POST':
        ord = request.json.get("ord")
        print(ord)
        data = {
            "msg":"ok"
        }
        return json.dumps(data)
    if request.method == 'GET':
        ord = request.values.get("name")
        print(ord)
        data = {
            "msg":"ok"
        }
        return json.dumps(data)

另附:postman接口测试图

POST方式:

GET方式:

 

二、 发送http请求

import requests
import datetime
import json
#接口调用post传参
def send_data(url,data):
    headers = 
    {
        "Content-Type":"application/json"
    }
    try:
        response = requests.post(url=url,json=data,headers=headers)
        response.raise_for_status()
        processed_data = json.loads(response.content)
        print("processed_data",processed_data)
    except requests.exceptions.RequestException as e:
        print("error",e)

 
if __name__ == "__main__":
    wms_url = "http://*.*.*.*:7000/BringGoods"
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    nopark_data ={
        "time":now_time,
        "ord": "44"
    }
    print(nopark_data)
    send_data(wms_url,nopark_data)