zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python基于request库,调用聊天机器人接口,request的几种方式汇总

Python机器人接口 基于 方式 调用 汇总 几种
2023-09-11 14:14:26 时间

参考网站案例:
https://www.begtut.com/python/ref-requests-post.html
https://blog.csdn.net/junli_chen/article/details/53670887
参考官方:https://requests.readthedocs.io/en/latest/api/?highlight=post#requests.post

在这里插入图片描述

1、post请求方式

一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样:

请求行
请求报头
消息主体

HTTP协议规定post提交的数据必须放在消息主体中,但是协议并没有规定必须使用什么编码方式。服务端通过是根据请求头中的Content-Type字段来获知请求中的消息主体是用何种方式进行编码,再对消息主体进行解析。具体的编码方式包括:

application/x-www-form-urlencoded
最常见post提交数据的方式,以form表单形式提交数据。
application/json
以json串提交数据。
multipart/form-data
一般使用来上传文件。

1.1 以form形式发送post请求

Reqeusts支持以form表单形式发送post请求,只需要将请求的参数构造成一个字典,然后传给requests.post()的data参数即可。

url = 'http://httpbin.org/post'
d = {'key1': 'value1', 'key2': 'value2'}
r = requests.post(url, data=d)
print r.text

输出:

{ 
“args”: {}, 
“data”: “”, 
“files”: {}, 
“form”: { 
“key1”: “value1”, 
“key2”: “value2” 
}, 
“headers”: { 
…… 
“Content-Type”: “application/x-www-form-urlencoded”, 
…… 
}, 
“json”: null, 
…… 
}

可以看到,请求头中的Content-Type字段已设置为application/x-www-form-urlencoded,且d = {‘key1’: ‘value1’, ‘key2’: ‘value2’}以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据。

1.2 以json形式发送post请求

可以将一json串传给requests.post()的data参数,

url = 'http://httpbin.org/post'
s = json.dumps({'key1': 'value1', 'key2': 'value2'})
r = requests.post(url, data=s)
print r.text

输出:

{ 
“args”: {}, 
“data”:{\”key2\”: \”value2\”, \”key1\”: \”value1\”}, 
“files”: {}, 
“form”: {}, 
“headers”: { 
…… 
“Content-Type”: “application/json”, 
…… 
}, 
“json”: { 
“key1”: “value1”, 
“key2”: “value2” 
}, 
…… 
}

可以看到,请求头的Content-Type设置为application/json,并将s这个json串提交到服务端中。

1.3 以multipart形式发送post请求

Requests也支持以multipart形式发送post请求,只需将一文件传给requests.post()的files参数即可。

url = 'http://httpbin.org/post'
files = {'file': open('report.txt', 'rb')}
r = requests.post(url, files=files)
print r.text

输出:

{ 
“args”: {}, 
“data”: “”, 
“files”: { 
“file”: “Hello world!}, 
“form”: {}, 
“headers”: {…… 
“Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”, 
…… 
}, 
“json”: null, 
…… 
}

2、案例

def request_post(data):
    r = requests.post("xx", data=data)
    print(r.text)
    print(type(r.text))
    print(eval(r.text))
    print(type(eval(r.text)))
    return eval(r.text)

调用

    data_ = {'description': '防疫政策', 'id': '3'}
    request_post(data_)

返回,默认返回的字符串类型,eval后变成字典类型

<class 'str'>
{'current_id': '3', 'similar_id_list': [{'166': 0.9442330598831177}, {'901': 0.9388024806976318}, {'140': 0.9371911287307739}]}
<class 'dict'>

subscriptable,可下标的

3、聊天机器人案例

import os
import pandas as pd
import requests
from database.connect_database_mysql import ConnectDatabaseMysql
from config_env.config_envi import common, select_env

connect_database = ConnectDatabaseMysql(select_env)


def request_post(data):
    r = requests.post("xx", data=data)
    result = eval(r.text)
    print(result)
    id_list = [key for res in result['similar_id_list'] for key in res.keys()]
    sql_read_field = 'id,question,answer'
    sql = "select %s from %s where id in (%s, %s, %s, %s, %s)" % (sql_read_field, common['mysql_table'],
                                                                  id_list[0], id_list[1], id_list[2],
                                                                  id_list[3], id_list[4])
    result_pd = pd.read_sql_query(sql, connect_database.con_target)
    index2ans = dict(zip(result_pd['id'], zip(result_pd['question'], result_pd['answer'])))
    answer_list = [index2ans[int(id_)] for id_ in id_list]
    return answer_list


if __name__ == '__main__':
    while True:
        human_utterance = input("Please enter your question:").strip()
        data_ = {'description': human_utterance, 'id': '3', 'top_k': '5'}
        robot_utterance = request_post(data_)
        print("[Bot answer]: %s" % robot_utterance)