エッセイ:Python+requestsがpostリクエストを行うよくある3種類の入参

10309 ワード

エッセイ:Python+requestsがpostリクエストを行うよくある3種類の入参
1、json形式の入参、ここで入参は漢字です
#coding=utf-8
import requests
from urllib.parse import quote
url = '    '
header = {'content-type':'application/json'}
t = "     ,   ,       ,   ,          ,  ,     。"
data = {"text":t}

#      data json   
response = requests.post(url=url,headers=header,json=data)
#           ,     
request = response.text.encode('utf-8').decode('unicode_escape')
#        
print(response.text)
#        
print(request)

結果を返します.
D:\test\Python37\python.exe D:/test/PycharmProjects/untitled/testrequest/testbody.py
{'text': '     ,   ,       ,   ,          ,  ,     。'}
{"value":{"\u60c5\u611f\u503e\u5411":"\u6b63\u5411","\u6d88\u6781\u6982\u7387":9.72836e-06,"\u79ef\u6781\u6982\u7387":0.99999,"\u8f93\u5165\u6587\u672c":"\u5fc3\u7075\u5b89\u987f\u4e86\uff0c\u5e73\u8861\u4e86\uff0c\u751f\u547d\u4e5f\u5c31\u5feb\u4e50\u4e86\uff0c\u65e0\u61be\u4e86\uff0c\u5982\u773c\u524d\u4e00\u5e45\u9759\u7f8e\u7684\u753b\u5377\uff0c\u6e05\u5e7d\uff0c\u6e29\u99a8\u4e0e\u5b81\u9759\u3002"}}

{"value":{"    ":"  ","    ":9.72836e-06,"    ":0.99999,"    ":"     ,   ,       ,   ,          ,  ,     。"}}


Process finished with exit code 0

2、csv、txtなどのファイルフォーマットの入力
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder

filename = r'D:\test\cloudAI\mxfile\OLT_DEMO.csv'
file = open(filename,'rb')
url = '    '
data = MultipartEncoder(
    fields={
        'OLT_INFO':
            ('OLT_DEMO.csv',
             file,
             'application/octet-stream')
    }
)
header={}
header['content-type'] = data.content_type
response = requests.post(url=url,headers=header,data=data)
print(response.text)

3、画像フォーマットによるbase 64符号化暗号化入力
import requests
import base64


photo = r'D:\test\cloudAI\phototest\wjj.jpg'
#fp = open(photo,'rb')


with open(photo,'rb') as f:
    base64_data = base64.b64encode(f.read())
    s = base64_data.decode()


url = '  url'
data = '{"imageBase64":"'+s+'"}'
header = {'Content-Type': 'application/json'}
response = requests.post(url=url,headers=header,data=data)

print(response.text)

番外:あとよくあるgetリクエストも大同小異