Last active
November 22, 2016 03:13
-
-
Save torufurukawa/5429542 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""requests wrapper | |
>>> import curledrequests as requests | |
you can use this as requests module, but... | |
>>> requests.debug = True | |
>>> requests.get('http://example.com/') | |
curl http://example.com/ | |
Hello | |
200 | |
""" | |
from urllib import unquote | |
from base64 import b64decode | |
from requests import * | |
debug = False | |
def wrap(func, *args, **kw): | |
def wrapper(*args, **kw): | |
if debug: | |
kw['hooks'] = {'response': print_curl} | |
return func(*args, **kw) | |
return wrapper | |
def print_curl(res): | |
params = [res.url] | |
# method | |
method = res.request.method | |
if method != 'GET': | |
params = ['-X', method] + params | |
# data | |
body = res.request.body | |
if body: | |
params += ['--data', "'%s'" % unquote(body)] | |
# auth | |
auth = res.request.headers.get('Authorization') | |
if auth: | |
_, credential = auth.split(' ') | |
params += ['-u', "'%s'" % b64decode(credential)] | |
# status code | |
params += ['-w', r"'\n%{http_code}\n'"] | |
# render | |
print '$ curl ' + ' '.join(params) | |
print res.content | |
print res.status_code | |
get = wrap(get) | |
post = wrap(post) | |
delete = wrap(delete) | |
put = wrap(put) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment