def process_response(self, request, response): if random() >= 0.5 and DRF_CHAOS_ENABLED: time.sleep(randint(0, 3)) response = HttpResponse() status_code = choice(REASON_PHRASES.keys()) response.status_code = status_code response.reason_phrase = REASON_PHRASES.get( status_code, 'UNKNOWN STATUS CODE') response.content = "drf-chaos: {}".format(response.reason_phrase) return response
def process_response(self, request, response): if random() >= 0.5 and DRF_CHAOS_ENABLED: time.sleep(randint(0, 3)) response = HttpResponse() status_code = choice(REASON_PHRASES.keys()) response.status_code = status_code response.reason_phrase = REASON_PHRASES.get( status_code, 'UNKNOWN STATUS CODE' ) response.content = "drf-chaos: {}".format( response.reason_phrase ) return response
def render_to_json(response): """ Determine the appropriate content and create the JSON response """ # determine the status code if hasattr(response, 'status_code'): status_code = response.status_code elif issubclass(type(response), Http404): status_code = 404 elif issubclass(type(response), Exception): status_code = 500 else: status_code = 200 data = {} # TODO: add optional process for fragments if isinstance(response, dict): for key in ['fragments', 'inner-fragments', 'append-fragments', 'prepend-fragments']: if key in response: data.update({ key: response.pop(key) }) data.update({ 'status': status_code, 'statusText': REASON_PHRASES.get(status_code, 'UNKNOWN STATUS CODE'), 'content': response }) return JSONResponse(data)
def httpreason(value, arg=False): """ Uses django's REASON_PHRASES to change a status_code into a textual reason. Optional True/False argument allows you to return a string with code number *and* phrase. Defaults to False""" try: value_int = int(value) except Exception: return '' phrase = REASON_PHRASES.get(value_int, 'UNKNOWN STATUS CODE') if arg: phrase = '{0}: {1}'.format(value, phrase) return phrase
def custom_rest_exception_handler(exc, context): response = exception_handler(exc, context) if isinstance(exc, exceptions.NotAuthenticated): response.status_code = 401 response.reason_phrase = REASON_PHRASES.get(response.status_code) return response
from django.utils.encoding import iri_to_uri try: from urlparse import urlparse except ImportError: from urllib.parse import urlparse try: from collections import OrderedDict except ImportError: from ordereddict import OrderedDict import json import re REASON_PHRASES.update({ 308: 'PERMANENT REDIRECT', # Not in 1.6 427: 'BAD GEOLOCATION', }) STATUS_CODES = tuple(sorted(REASON_PHRASES.items())) STATUS = OrderedDict(STATUS_CODES) # Set constant-like properties for reverse lookup for code, label in STATUS_CODES: setattr(STATUS, re.sub(r'\W', '_', label.upper()), code) class BaseHttpResponse(HttpResponse, Exception): ''' A sub-class of HttpResponse that is also an Exception, allowing us to raise/catch it.