例如,如何使用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"})
功能不完整,可能不理想,但显示了基本的表示形式和要使用的概念。可以根据口味添加或更改其他内容。
12/08更新
这是GitHub实时更新源的链接。目前支持:
授权
兼容CRUD
自动字符集检测
自动编码(压缩)检测