如何在python中使用POST?

时间:2019-11-20 10:04:15

标签: python json api

我想使用python发送此curl数据

curl -X POST "http://192.168.12.80:8080/1.0/kb/accounts/a6c08c2c-f3eb-456a-a681-6e5262262e94/payments?paymentMethodId=810d4eae-4668-4c6a-897c-178c041eb67f" -H "accept: application/json" -H "X-Killbill-CreatedBy: demo" -H "authorization: Basic YWRtaW46cGFzc3dvcmQ=" -H "X-Killbill-ApiKey: abcd" -H "X-Killbill-ApiSecret: dcba" -H "Content-Type: application/json" -d "{\"transactionType\":\"AUTHORIZE\",\"amount\":\"$user\",\"currency\":\"INR\",\"transactionExternalKey\":\"$id\"}"

2 个答案:

答案 0 :(得分:0)

第一步:安装请求包 安装后,您应该在执行时看到类似这样的内容 命令行中的点列表

$ pip list
Package      Version
------------ -------------------
certifi      2019.9.11
chardet      3.0.4
Click        7.0
idna         2.8
itsdangerous 1.1.0
MarkupSafe   1.1.1
pip          19.3.1
**requests     2.22.0**
setuptools   41.6.0.post20191030
urllib3      1.25.7
Werkzeug     0.16.0
wheel        0.33.6
wincertstore 0.2

第2步:运行以下代码,检查发布请求是否正常

请在下面找到python POST请求的示例,

import requests

url = 'https://www.w3schools.com/python/demopage.php'
myobj = {'somekey': 'somevalue'}

x = requests.post(url, data = myobj)

print(x.text)

Step3:您的代码使用如下所示的请求

import requests

url = 'http://192.168.12.80:8080/1.0/kb/accounts/a6c08c2c-f3eb-456a-a681-6e5262262e94/payments?paymentMethodId=810d4eae-4668-4c6a-897c-178c041eb67f"'
myobj = {'transactionType': 'AUTHORIZE','amount':'$user','currency':'INR','transactionExternalKey':'$id'}
headers = {'accept': 'application/json','X-Killbill-CreatedBy': 'demo','authorization':'Basic YWRtaW46cGFzc3dvcmQ=','X-Killbill-ApiKey': 'abcd','X-Killbill-ApiSecret': 'dcba', 'Content-Type': 'application/json'}
x = requests.post(url, data = myobj, headers=headers)

print(x.text)

答案 1 :(得分:0)

requests package可以在这里为您提供帮助。主要调用将是requests.post(),它将使用您需要的所有参数。例如

import requests
import json

myHeaders = { 'accept': 'application/json', 'content-type': 'application/json', 'X-Killbill-CreatedBy': demo", 'X-pect': 'The Spanish Inquisition'}

myData = {'transactionType': 'AUTHORIZE', 'amount': user, 'currency': 'INR', 'transactionExternalKey': id }

myParams = {'paymentMethodId': '810d4eae-4668-4c6a-897c-178c041eb67f'}

requests.post(
    'http://192.168.12.80:8080/1.0/kb/accounts/a6c08c2c-f3eb-456a-a681-6e5262262e94',
    params = myParams,
    headers = myHeaders,
    data = json.dumps(myData),
)