Python中的CURL替代方法

我有一个在PHP中使用的curl调用:

curl -i -H'Accept:application / xml'-u login:key“ https://app.streamsend.com/emails ”

我需要一种方法来在Python中做同样的事情。 Python中是否有cURL的替代方法? 我知道urllib,但我是一个Python noob,不知道如何使用它。

 import urllib2 manager = urllib2.HTTPPasswordMgrWithDefaultRealm() manager.add_password(None, 'https://app.streamsend.com/emails', 'login', 'key') handler = urllib2.HTTPBasicAuthHandler(manager) director = urllib2.OpenerDirector() director.add_handler(handler) req = urllib2.Request('https://app.streamsend.com/emails', headers = {'Accept' : 'application/xml'}) result = director.open(req) # result.read() will contain the data # result.info() will contain the HTTP headers # To get say the content-length header length = result.info()['Content-Length'] 

改为使用urllib2的cURL调用。 完全未经testing。

您可以使用请求:HTTP for Humans用户指南中描述的HTTP请求。

这里有一个简单的例子,使用urllib2对GitHub的API进行基本的身份validation。

 import urllib2 u='username' p='userpass' url='https://api.github.com/users/username' # simple wrapper function to encode the username & pass def encodeUserData(user, password): return "Basic " + (user + ":" + password).encode("base64").rstrip() # create the request object and set some headers req = urllib2.Request(url) req.add_header('Accept', 'application/json') req.add_header("Content-type", "application/x-www-form-urlencoded") req.add_header('Authorization', encodeUserData(u, p)) # make the request and print the results res = urllib2.urlopen(req) print res.read() 

此外,如果您将其封装在脚本中并从terminal运行,则可以将响应string传递给“mjson.tool”以启用漂亮的打印。

 >> basicAuth.py | python -mjson.tool 

最后要注意的是,urllib2只支持GET和POST请求。
如果你需要使用其他的HTTP动词,如DELETE,PUT等,你可能会想看看PYCURL

如果你正在使用一个叫做curl的命令,你可以在subprocess中用Python做同样的事情。 例:

 subprocess.call(['curl', '-i', '-H', '"Accept: application/xml"', '-u', 'login:key', '"https://app.streamsend.com/emails"']) 

或者你可以尝试PycURL,如果你想把它作为一个像PHP那样更结构化的API。

一些例子,如何使用urllib的东西,用一些糖的语法。 我知道请求和其他库,但urllib是python的标准库,并不需要单独安装任何东西。

Python 2/3兼容。

 import sys if sys.version_info.major == 3: from urllib.request import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener from urllib.parse import urlencode else: from urllib2 import HTTPPasswordMgrWithDefaultRealm, HTTPBasicAuthHandler, Request, build_opener from urllib import urlencode def curl(url, params=None, auth=None, req_type="GET", data=None, headers=None): post_req = ["POST", "PUT"] get_req = ["GET", "DELETE"] if params is not None: url += "?" + urlencode(params) if req_type not in post_req + get_req: raise IOError("Wrong request type \"%s\" passed" % req_type) _headers = {} handler_chain = [] if auth is not None: manager = HTTPPasswordMgrWithDefaultRealm() manager.add_password(None, url, auth["user"], auth["pass"]) handler_chain.append(HTTPBasicAuthHandler(manager)) if req_type in post_req and data is not None: _headers["Content-Length"] = len(data) if headers is not None: _headers.update(headers) director = build_opener(*handler_chain) if req_type in post_req: if sys.version_info.major == 3: _data = bytes(data, encoding='utf8') else: _data = bytes(data) req = Request(url, headers=_headers, data=_data) else: req = Request(url, headers=_headers) req.get_method = lambda: req_type result = director.open(req) return { "httpcode": result.code, "headers": result.info(), "content": result.read() } """ Usage example: """ Post data: curl("http://127.0.0.1/", req_type="POST", data='cascac') Pass arguments (http://127.0.0.1/?q=show): curl("http://127.0.0.1/", params={'q': 'show'}, req_type="POST", data='cascac') HTTP Authorization: curl("http://127.0.0.1/secure_data.txt", auth={"user": "username", "pass": "password"}) 

function不完整,可能不够理想,但显示出使用的基本表述和概念。 额外的东西可以添加或改变口味。

12/08更新

这是一个GitHub链接,以实时更新的来源。 目前支持:

  • 授权

  • CRUD兼容

  • 自动字符集检测

  • 自动编码(压缩)检测

 import requests url = 'https://example.tld/' auth = ('username', 'password') r = requests.get(url, auth=auth) print r.content 

这是最简单的,我已经能够得到它。

如果它正在运行你正在寻找的命令行的所有上述,那么我build议HTTPie 。 这是一个梦幻般的cURL替代品,使用(和定制) 超级简单 方便

这里是GitHub的简洁描述。

HTTPie(发音为aych-tee-tee-pie)是一个命令行HTTP客户端。 其目标是使CLI与Web服务的交互尽可能人性化。

它提供了一个简单的http命令,允许使用简单自然的语法发送任意的HTTP请求,并显示彩色输出。 HTTPie可用于testing,debugging,并且通常与HTTP服务器进行交互。


关于authentication的文档应该给你足够的指针来解决你的问题。 当然,上面的所有答案都是准确的,并提供完成同一任务的不同方式。


只是所以你不必从Stack Overflow移开,简而言之就是它所提供的。

 Basic auth: $ http -a username:password example.org Digest auth: $ http --auth-type=digest -a username:password example.org With password prompt: $ http -a username example.org