【Flask】Flask中HTTP请求与接收

一、接收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)
相关推荐
TE-茶叶蛋2 分钟前
TF-IDF 与 BM25 深度解析:从理论到项目实战
python·django·tf-idf
xcbrand5 分钟前
湖南VI设计公司排名
大数据·人工智能·python
IT_陈寒14 分钟前
Vite热更新失效?可能你在用Windows
前端·人工智能·后端
lllsure33 分钟前
【开源项目】Learn Claude Code
python·ai
椰椰椰耶1 小时前
[SpringCloud][14]OpenFeign参数传递方法
后端·spring·spring cloud
onething3651 小时前
Spring Boot + Spring AI 从入门到实战:7天转型计划 Day 3 —— 消息表设计 + 级联删除 + 事务管理
人工智能·后端
荣江2 小时前
Hermes Agent 代码仓库打包工具使用指南(repomix-rs 高性能版)
后端
王某某人2 小时前
LangChain4j 入门:Java 程序员的第一个 AI 对话程序
人工智能·后端
码农刚子2 小时前
从零开始:在 Windows 服务器上部署 Node.js 项目(小白实战教程)
后端·node.js
Cache技术分享2 小时前
435. Java 日期时间 API - Clock 灵活获取当前时间
前端·后端