Created
January 20, 2015 22:01
-
-
Save defrex/c8bfb6cca199177bf428 to your computer and use it in GitHub Desktop.
A couple utility functions for pretty printing Django request and response objects
This file contains 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
from __future__ import unicode_literals, print_function | |
import re | |
import colorama | |
header_regex = re.compile('^HTTP_') | |
def print_header(key, value): | |
if not value: | |
return | |
header = header_regex.sub('', key).replace('_', ' ').title().replace(' ', '-') | |
print(colorama.Fore.CYAN, header, sep='', end='') | |
print(colorama.Style.RESET_ALL, ': ', sep='', end='') | |
print(colorama.Fore.YELLOW, value, sep='') | |
def print_request(request): | |
print('\n', end='') | |
print( | |
colorama.Fore.GREEN, | |
request.method, ' ', | |
colorama.Style.RESET_ALL, | |
request.path, | |
sep='', | |
) | |
print_header('CONTENT_TYPE', request.META.get('CONTENT_TYPE')) | |
print_header('CONTENT_LENGTH', request.META.get('CONTENT_LENGTH')) | |
for key, value in request.META.items(): | |
if key.startswith('HTTP_'): | |
print_header(key, request.META.get(key)) | |
print('\n', end='') | |
print(colorama.Style.RESET_ALL, request.body, sep='') | |
def print_response(response): | |
print('\n', end='') | |
print('\n', end='') | |
print( | |
colorama.Fore.GREEN, | |
response.status_code, ' ', | |
colorama.Style.RESET_ALL, | |
response.reason_phrase, | |
sep='', | |
) | |
for key, value in response.items(): | |
print_header(key, value) | |
print('\n', end='') | |
print(colorama.Style.RESET_ALL, response.content, sep='') | |
print('\n', end='') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, this was helpful. Note that it doesn't include the
Set-Cookie
response headers. Django does it like this: