Last active
November 10, 2016 17:37
-
-
Save ojas/9ea182757c2fab63ecc61bcd3d5ada6c to your computer and use it in GitHub Desktop.
Python Helpers
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
| """ | |
| Log your requests activity in curl format and with pretty colors. | |
| import requests | |
| from requests_curl_logger import curl_log | |
| r = requests.get('http://example.com', hooks=dict(response=curl_log)) | |
| """ | |
| from json import dumps as json_dumps | |
| def shellquote(s): | |
| return "'" + s.replace("'", "'\\''") + "'" | |
| class bcolors: | |
| WHITE = '\033[97m' | |
| CYAN = '\033[96m' | |
| MAGENTA = '\033[95m' | |
| ENDC = '\033[0m' | |
| BOLD = '\033[1m' | |
| UNDERLINE = '\033[4m' | |
| BLUE = '\033[94m' | |
| GREEN = '\033[92m' | |
| WARNING = '\033[93m' | |
| FAIL = '\033[91m' | |
| def curl_log(r, *args, **kwargs): | |
| cl = 'curl \\\n' | |
| if r.request.method != 'GET' or 1: | |
| cl += " -X%s \\\n" % r.request.method.upper() | |
| IGNORE_HEADERS = ['User-Agent', 'Connection', 'Accept-Encoding', 'Content-Length', ] | |
| for k, v in r.request.headers.items(): | |
| if k not in IGNORE_HEADERS: | |
| cl += ' -H ' + shellquote("%s: %s" % (k, v)) + ' \\\n' | |
| if r.request.body is not None: | |
| cl += ' -d ' + shellquote(r.request.body.decode('utf-8')) + ' \\\n' | |
| cl += ' ' + shellquote(r.request.url) | |
| resp = bcolors.CYAN + cl + bcolors.ENDC + '\n\n' | |
| resp += bcolors.MAGENTA | |
| resp += bcolors.BOLD + '%s %s\n' % (r.status_code, r.reason) + bcolors.ENDC | |
| resp += bcolors.MAGENTA | |
| for k, v in r.headers.items(): | |
| resp += '%s: %s\n' % (k, v) | |
| formatted_text = r.text | |
| resp += bcolors.ENDC | |
| try: | |
| formatted_text = json_dumps(r.json(), indent=2) | |
| except Exception as e: | |
| pass | |
| resp += bcolors.WHITE | |
| resp += formatted_text + '\n\n' | |
| resp += bcolors.ENDC | |
| print(resp) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment