将 curl 命令转换为 python

convert curl command to python

我有以下 curl 命令

file_location='some/path/to/test.csv'

auth_token='my_api_token'

curl --insecure --request POST 'https://<ip_address>/eds/api/table/table_name/changes/addBulk?hasHeader=false' -H 'Csrf-Token: nocheck' -H 'AuthToken:'$auth_token'' -H 'Content-Type: multipart/form-data' --form 'data=@'$file_location'

csv 中的数据只是多行 1 列,例如:

row_1
row_2
row_3

curl 命令工作得很好,我正在尝试使用 python 替代它,我在下面尝试过:


files = {'file': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')}

auth_token="<api token here>"

url="https://" + ip_address +"/eds/api/table/" + table_name + "/changes/addBulk?hasHeader=false"

headers = {
    'Csrf-Token': 'nocheck',
    'AuthToken': auth_token
}

response = requests.post(url, headers=headers, files=files, verify=False)

感谢任何帮助

我注意到在你的 curl url 中你在 "/api/..." 之前有 "eds" 但在你的 python 版本中你没有.

curl_url = "https://<ip_address>/eds/api/table/table_name/changes/addBulk?hasHeader=false"

python_url = "https://" + ip_address +"/api/table/" + table_name + "/changes/addBulk?hasHeader=false"

此外,在 python 3 中使用这样的 f-string 更干净:

url = f"https://{ip_address}**/eds/**api/table/{table_name}/changes/addBulk?hasHeader=false"

我觉得其他一切都合适。将来可能有助于在响应上设置断点以查看 400 http 响应是否有任何其他信息。

编辑:

那好吧,你能试着把你的 header 修改成:

headers = {
    'Csrf-Token': 'nocheck',
    'AuthToken': auth_token,
    'Content-Type': 'multipart/form-data'
}

同时将您的文件编辑为:

files = {
    'data': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')
}

最终代码应该是:

auth_token = "<api token here>"
files = {
    'data': ('test.csv', open("some/path/to/test.csv", 'rb'), 'multipart/form-data')
}
url = f"https://{ip_address}/eds/api/table/{table_name}/changes/addBulk?hasHeader=false"

headers = {
    'Csrf-Token': 'nocheck',
    'AuthToken': auth_token
}

response = requests.post(url, headers=headers, files=files, verify=False)