我有以下 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)
任何帮助表示赞赏
回答1
我注意到在您的 curl 网址中,您在“/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 字符串更简洁:
url = f"https://{ip_address}**/eds/**api/table/{table_name}/changes/addBulk?hasHeader=false"
其他一切对我来说都是正确的。将来,在响应上设置断点以查看 400 http 响应是否有任何其他信息可能会有所帮助。
编辑:
好的,您可以尝试将标题修改为:
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)