程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python基於request庫,調用聊天機器人接口,request的幾種方式匯總

編輯:Python

參考網站案例:
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)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved