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

Python calls the chat robot interface based on the request library. Several methods of request are summarized

編輯:Python

Reference website cases :
https://www.begtut.com/python/ref-requests-post.html
https://blog.csdn.net/junli_chen/article/details/53670887
Refer to the official :https://requests.readthedocs.io/en/latest/api/?highlight=post#requests.post

1、post Request mode

One http The request consists of three parts , For not for request line , Ask the head of the newspaper , Message body , Like this :

Request line
Ask the head of the newspaper
Message body

HTTP Provisions of the agreement post The submitted data must be placed in the body of the message , But the protocol doesn't specify what encoding method must be used . The server passes according to the... In the request header Content-Type Field to know how the message body in the request is encoded , Then the message body is parsed . Specific encoding methods include :

application/x-www-form-urlencoded
Most common post How to submit data , With form Submit data in form form .
application/json
With json String submit data .
multipart/form-data
Usually used to upload files .

1.1 With form Send as post request

Reqeusts Support with form Send it as a form post request , Just construct the requested parameters into a dictionary , Then pass it to requests.post() Of data Parameters can be .

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

Output :

{

“args”: {
},
“data”: “”,
“files”: {
},
“form”: {

“key1”: “value1”,
“key2”: “value2”
},
“headers”: {

……
“Content-Type”: “application/x-www-form-urlencoded”,
……
},
“json”: null,
……
}

You can see , In the request header Content-Type Field is set to application/x-www-form-urlencoded, And d = {‘key1’: ‘value1’, ‘key2’: ‘value2’} With form Submit the form to the server , Returned by the server form The field is the submitted data .

1.2 With json Send as post request

You can make one json Serial transmission to requests.post() Of data Parameters ,

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

Output :

{

“args”: {
},
“data”: “{
\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,
“files”: {
},
“form”: {
},
“headers”: {

……
“Content-Type”: “application/json”,
……
},
“json”: {

“key1”: “value1”,
“key2”: “value2”
},
……
}

You can see , The request header Content-Type Set to application/json, And will s This json The string is submitted to the server .

1.3 With multipart Send as post request

Requests I also support multipart Send as post request , Just pass a file to requests.post() Of files Parameters can be .

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

Output :

{

“args”: {
},
“data”: “”,
“files”: {

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

2、 Case study

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)

call

 data_ = {
'description': ' Epidemic prevention policy ', 'id': '3'}
request_post(data_)

return , The default returned string type ,eval Then it becomes a dictionary type

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

subscriptable, Subscribable

3、 Chat robot case

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