Python 请求没有上传文件

Python requests doesn't upload file

我正在尝试使用 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

Curl 将文件上传为 POST 正文本身,但您要求 requests 将其编码为 multipart/form-data 正文。这里不要使用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 documentation for --data-binary:

(HTTP) This posts data exactly as specified with no extra processing whatsoever.

If you start the data with the letter @, the rest should be a filename. Data is posted in a similar manner as --data-ascii does, except that newlines and carriage returns are preserved and conversions are never done.