使用Python中的文件上载作为请求重写curl post调用

2024-05-12 17:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我对本地graphhopper服务器进行了以下curl调用:

curl -XPOST -H "Content-Type: application/gpx+xml" -d @home/jd/test1.gpx "localhost:8989/match?vehicle=car&type=json"

现在,我想在python中自动执行此调用,并获得了以下内容:

import requests

url = 'http://localhost:8989/match'

headers = {'Content-Type': "application/gpx+xml"}
files = {'upload_file': open('home/jd/test1.gpx','rb')}
values = {'vehicle': 'car', 'type': 'json'}

r = requests.post(url, files=files, data=values, headers=headers)

print (r.status_code)
print (r.raise_for_status())

我收到一个错误的URL请求http://localhost:8989/match

我错过了什么


Tags: localhosthomeapplicationtypematchfilesxmlgpx
1条回答
网友
1楼 · 发布于 2024-05-12 17:40:23

好的,我找到了解决方案:

因为Curl的Post请求上载了一个文件,所以我必须直接将文件objekt传递到数据中。我确实把其他参数放回了URL

import requests

url = 'http://localhost:8989/match?vehicle=car&type=json'

headers = {'Content-Type': 'application/gpx+xml'}

r = requests.post(url, data=open('/home/jd/test1.gpx','rb'), headers= headers)

print (r.status_code)
print (r.raise_for_status())
print (r.text)

工作起来很有魅力

相关问题 更多 >