Created
October 28, 2012 03:53
-
-
Save jkz/3967420 to your computer and use it in GitHub Desktop.
restlibpatch.py
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 .http import statuses | |
def Foo(Resource): | |
def get(request): | |
try: | |
something = api.do_something() | |
except api.Timeout: | |
request.response['So'] = 'many' # with the response attached to the request | |
request.response_headers['options'] = 'available' # or just the headers | |
raise statuses.request_timeout | |
except api.Unauthorized: | |
raise statuses.unauthorized({'Do': 'Whatever'}, Tickles='your', **{'Fancy': '!'}) | |
else: | |
return something |
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
class RestException(Exception): | |
headers = {} | |
def __init__(self, headers={}, **_headers): | |
# Some redundancy here for convenience, though that might | |
# be a matter of flavor. | |
self.headers.update(headers) | |
self.headers.update(_headers) | |
statuses = AttrDict((v.lower().replace(' ', '_'), | |
type(v.upper().replace(' ', '_'), (RestException,), {'code': k})) | |
for k, v in STATUS_CODE_TEXT.items()) |
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 django.http import HttpResponse | |
from .http import RestException | |
class RestMiddleware: | |
def process_view(self, request, resource, args, kwargs): | |
# The list of check calls could move here, or this could just call process_request | |
# on the resource | |
self.resource = resource # Or is this a Bad Idea™? | |
return resource.process_request(request, *args, **kwargs) | |
def process_response(self, request, response): | |
# The response could be the resource here, or the resource could have been bound to either | |
# either the middleware or the request. | |
self.resource.process_response(request, response) | |
def process_exception(self, request, exception): | |
if isinstance(exception, RestException): | |
# Another solution would be to attach the response object to the request | |
# object in stead of defining it at the top of 'Resource.process_request' | |
# that would also be one less parameter to a lot of the functions, but a bit | |
# more deep access. | |
response = HttpResponse(status=exception.code) | |
for k, v in exception.headers.iteritems(): | |
response[k] = v | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment