Python请求不上传文件

2024-04-05

我正在尝试使用 Python 请求重现此curl 命令:

curl -X POST -H 'Content-Type: application/gpx+xml' -H 'Accept: application/json' --data-binary @test.gpx "http://test.roadmatching.com/rest/mapmatch/?app_id=my_id&app_key=my_key" -o output.json

使用curl 的请求效果很好。现在我用Python尝试一下:

import requests

file =  {'test.gpx': open('test.gpx', 'rb')}

payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}


r = requests.post("https://test.roadmatching.com/rest/mapmatch/", files=file, headers=headers, params=payload)

我收到错误:

<Response [400]>
{u'messages': [], u'error': u'Invalid GPX format'}

我究竟做错了什么?我必须指定吗data-binary某处?

该 API 记录如下:https://mapmatching.3scale.net/mmswag https://mapmatching.3scale.net/mmswag


Curl 将文件作为 POST 正文本身上传,但您要问requests将其编码为多部分/表单数据主体。不要使用files在这里,传入文件对象作为data争论:

import requests

file = open('test.gpx', 'rb')

payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}

r = requests.post(
    "https://test.roadmatching.com/rest/mapmatch/",
    data=file, headers=headers, params=payload)

如果您在with声明上传后它将为您关闭:

payload = {'app_id': 'my_id', 'app_key': 'my_key'}
headers = {'Content-Type':'application/gpx+xml', 'Accept':'application/json'}

with open('test.gpx', 'rb') as file:
    r = requests.post(
        "https://test.roadmatching.com/rest/mapmatch/",
        data=file, headers=headers, params=payload)

来自curl的文档--data-binary http://curl.haxx.se/docs/manpage.html#--data-binary:

(HTTP) 这完全按照指定发布数据,无需任何额外处理。

如果数据以字母开头@,其余的应该是文件名。数据发布方式类似于--data-ascii确实如此,除了保留换行符和回车符并且从不进行转换。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python请求不上传文件 的相关文章

随机推荐