如何使用python执行curl命令

2024-04-25 05:22:36 发布

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

我想用python执行curl命令。

通常,我只需要在终端输入命令并按回车键。但是,我不知道它在python中是如何工作的。

命令如下:

curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere

有一个request.json文件要发送以获取响应。

我找了很多东西,都弄糊涂了。我试图写一段代码,虽然我不能完全理解。它不起作用。

import pycurl
import StringIO

response = StringIO.StringIO()
c = pycurl.Curl()
c.setopt(c.URL, 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere')
c.setopt(c.WRITEFUNCTION, response.write)
c.setopt(c.HTTPHEADER, ['Content-Type: application/json','Accept-Charset: UTF-8'])
c.setopt(c.POSTFIELDS, '@request.json')
c.perform()
c.close()
print response.getvalue()
response.close()

错误消息是“Parse error”。有人能告诉我如何修复它吗?或者如何从服务器获得正确的响应?


Tags: https命令comjsonapplicationresponserequestwww
3条回答
import requests
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
data = requests.get(url).json

也许吧?

如果你想发送一个文件

files = {'request_file': open('request.json', 'rb')}
r = requests.post(url, files=files)
print r.text, print r.json

啊,谢谢@LukasGraf,现在我更好地理解了他的原始代码在做什么

import requests,json
url = "https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere"
my_json_data = json.load(open("request.json"))
req = requests.post(url,data=my_json_data)
print req.text
print 
print req.json # maybe? 

只要用this website。它将把任何curl命令转换成Python、Node.js、PHP、R或Go。

示例:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

在Python中变成这样

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

为了简单起见,也许您应该考虑使用Requests库。

json响应内容的示例如下:

import requests
r = requests.get('https://github.com/timeline.json')
r.json()

如果您在Quickstart部分中寻找进一步的信息,它们有很多工作示例。

编辑:

对于特定的卷曲翻译:

import requests
url = 'https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere'
payload = open("request.json")
headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8'}
r = requests.post(url, data=payload, headers=headers)

相关问题 更多 >