在请求库中传递curl -d参数时出错 [英] Error passing curl -d parameter in requests library
问题描述
我有一个 curl
POST请求,该请求在终端机(macOS)中运行良好,并按预期返回了csv.RJMetrcis 文档中提供了以下格式(请参见导出"数字数据").这是bash中的curl请求:
I have a curl
POST request that works perfectly in the terminal (macOS), returning a csv as expected. The following format is provided in the RJMetrcis documentation (see "Export figure data"). Here is the curl request in bash:
curl -d "format=csv&includeColumnHeaders=1" -H "X-RJM-API-Key: myAPIkey" https://api.rjmetrics.com/0.1/figure/0000/export
我的目标是使用 requests
在Python中实现 exact 相同的curl请求.当我输入与POST请求相同的参数时,代码不起作用并返回错误:
My objective is to implement the exact same curl request in Python using requests
. When I input the same parameters as a POST request, the code does not work returning an error:
import requests
headers = {'X-RJM-API-Key: myAPIkey'}
data= {'format=csv&includeColumnHeaders=1'}
url = "https://api.rjmetrics.com/0.1/figure/0000/export"
response = requests.post(url, data, headers)
这将返回错误:
TypeError: memoryview: a bytes-like object is required, not 'str'
第二次尝试:
response = requests.post(url, data=data, headers=headers)
返回
AttributeError: 'set' object has no attribute 'items'
在python中构造POST请求的正确格式是什么,以使其符合 data = {'key':'value'}
约定并返回csv?将bash curl POST转换为python POST请求
What is the correct format in python for constructing a POST request so that it matches the data = {'key':'value'}
convention, and returns a csv?Any help would be appreciated translating the bash curl POST into a python POST request
推荐答案
在这里您传递了一个集合,并且希望传递dict或str对象
Here you are passing a set and you are expected to pass a dict or str object
data= {'format=csv&includeColumnHeaders=1'}
替换为
data= {'format':'csv&includeColumnHeaders=1'}
应该修复它.
另一方面,看到您的卷曲请求.
On the other hand by seeing your curl request..
这完全取决于您要如何传递数据,以下代码(将数据有效载荷作为字符串传递)将直接发布数据,这等效于curl中的--data-raw
It all depends how you want to pass the data, following code (passing the data payload as a string) will post the data directly, that will be the equivalent to --data-raw in curl
import requests
url = "https://api.rjmetrics.com/0.1/figure/0000/export"
payload = "'{\"format\":\"csv&includeColumnHeaders=1\"}'"
headers = {
'X-RJM-API-Key': 'myAPIkey'
}
response = requests.request("POST", url, headers=headers, data = payload)
print(response.text.encode('utf8'))
这篇关于在请求库中传递curl -d参数时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!