视觉学习(七)---Flask 框架下接口调用及python requests 实现json字符串传输

在项目实施过程中需要与其他系统进行接口联调,将图像检测的结果传递给其他系统接口,进行逻辑调用。这中间的过程可以通过requests库进行实现。

1.安装requests库
pip install requests
2.postman 接口测试

我们先通过postman 了解下接口调用,通过postman新增一个接口:
新增Collection --> 选中Collection,右键Add request --> 选择请求方式 POST/GET…, 填写URL --> raw --> 选择 JSON 格式 -->填写请求数据内容 --> Send, 得到请求结果
视觉学习(七)---Flask 框架下接口调用及python requests 实现json字符串传输_第1张图片

通过以上操作,我们可以总结出:request请求需要 url,data, 明确请求方式。

3. 通过requests库进行json 数据传输
import requests
import json

def  send_data():
    #url
    url = 'http://www.example.com/api/users'
    
    #上传data数据,json 串
    data = {
        'username': 'user1', 
        'password': 'password1'
    }
    
    #post请求
    response = requests.post(url, json=data)
    
    #以json格式,打印返回数据
    print(json.loads(response.content))
4.实例应用
import json
import requests
import datetime

def send_data(url,data):
    #一般接口调用需要加上请求头文件,告诉接口数据传输为json格式
    headers = {
        "Content-Type":"application/json"
    }

    try:
        #post请求
        response = requests.post(url,data,headers=headers)
        #判断是否异常,响应码是否是200,判断网络连接的状态
        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 response.status_code == 200:
    #     processed_data = json.loads(response.content)
    #     print("processed_data", processed_data)
    # else:
    #     print("error", response.status_code)


def test():
    url = "http://xxx.xx.xx.xx:xxxx/api/v1/xxx/xxxxx"   #写自己实际的接口路径
    now_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #获取时间
    wms_data={
        "time": now_time,
        "vehicleid": "192.168.9.201",
        "type": "A",
        "code": "5001",
    }
    send_data(url, wms_data)

你可能感兴趣的:(python,计算机视觉,python,flask)