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']
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()
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 is not complete and possibly is not ideal, but shows a basic representation and concept to use. Additional things could be added or changed by taste.