Skip to content

Instantly share code, notes, and snippets.

@torufurukawa
Last active November 22, 2016 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torufurukawa/5429542 to your computer and use it in GitHub Desktop.
Save torufurukawa/5429542 to your computer and use it in GitHub Desktop.
"""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
print
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