我想在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'。任何人都可以告诉我如何修复它?或者如何正确地从服务器获得响应?
答案 0 :(得分:126)
为简单起见,您可以考虑使用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)
答案 1 :(得分:43)
只需使用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)
答案 2 :(得分:15)
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?
答案 3 :(得分:14)
curl -d @request.json --header "Content-Type: application/json" https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere
它的python实现就像
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', 'mykeyhere'),
)
data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
检查 this link ,它有助于将cURl命令转换为python,php和nodejs
答案 4 :(得分:8)
有一个不错的网站https://curl.trillworks.com/为您完成转化。它确实从cURL转换为Python,Node.js,R,PHP,Go。
答案 5 :(得分:4)
我使用 os
库。
import os
os.system("sh script.sh")
script.sh
字面上只包含卷曲。
答案 6 :(得分:3)
我的回答是WRT python 2.6.2。
import commands
status, output = commands.getstatusoutput("curl -H \"Content-Type:application/json\" -k -u (few other parameters required) -X GET https://example.org -s")
print output
我为没有提供必要的参数而道歉,因为它是保密的。
答案 7 :(得分:3)
import requests
headers = {
'Content-Type': 'application/json',
}
params = (
('key', 'mykeyhere'),
)
data = open('request.json')
response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search', headers=headers, params=params, data=data)
#NB. Original query string below. It seems impossible to parse and
#reproduce query strings 100% accurately so the one below is given
#in case the reproduced version is not "correct".
# response = requests.post('https://www.googleapis.com/qpxExpress/v1/trips/search?key=mykeyhere', headers=headers, data=data)
答案 8 :(得分:0)
一些背景:我一直在寻找这个问题,因为我不得不做一些事情来检索内容,但是我所能得到的只是一个旧版的python,它没有足够的SSL支持。如果您使用的是较旧的MacBook,那么您知道我在说什么。在任何情况下,curl
都可以从Shell正常运行(我怀疑它已链接了现代SSL支持),因此有时您想要在不使用requests
或urllib2
的情况下执行此操作。
您可以使用subprocess
模块执行curl
并获取检索到的内容:
import subprocess
// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])
Python 3的subprocess
模块还包含带有许多有用选项的.run()
。我将其留给实际上正在运行python 3的人来提供该答案。
答案 9 :(得分:0)
Python 3
仅适用于 UNIX (Linux / Mac) (!)
使用 Python 3 执行 cURL 并解析其 JSON 数据。
import shlex
import json
import subprocess
# Make sure that cURL has Silent mode (--silent) activated
# otherwise we receive progress data inside err message later
cURL = r"""curl -X --silent POST http://www.test.testtestest/ -d 'username=test'"""
lCmd = shlex.split(cURL) # Splits cURL into an array
p = subprocess.Popen(lCmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate() # Get the output and the err message
json_data = json.loads(out.decode("utf-8"))
print(json_data) # Display now the data
如果遇到奇怪的错误,有时您还需要在 UNIX 上安装这些依赖项:
# Dependencies
sudo apt install libcurl4-openssl-dev libssl-dev
sudo apt install curl
答案 10 :(得分:-3)
这可以通过下面提到的伪代码方法来实现
导入操作系统 导入请求 Data = os.execute(curl URL) R = Data.json()