Created
August 13, 2010 16:45
-
-
Save fredpalmer/523177 to your computer and use it in GitHub Desktop.
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
class rc_factory(object): | |
""" | |
Status codes. | |
""" | |
CODES = dict(ALL_OK = ('OK', 200), | |
CREATED = ('Created', 201), | |
DELETED = ('', 204), # 204 says "Don't send a body!" | |
BAD_REQUEST = ('Bad Request', 400), | |
FORBIDDEN = ('Forbidden', 401), | |
NOT_FOUND = ('Not Found', 404), | |
DUPLICATE_ENTRY = ('Conflict/Duplicate', 409), | |
NOT_HERE = ('Gone', 410), | |
INTERNAL_ERROR = ('Internal Error', 500), | |
NOT_IMPLEMENTED = ('Not Implemented', 501), | |
THROTTLED = ('Throttled', 503)) | |
def __getattr__(self, attr): | |
""" | |
Returns a fresh `HttpResponse` when getting | |
an "attribute". This is backwards compatible | |
with 0.2, which is important. | |
""" | |
try: | |
(r, c) = self.CODES.get(attr) | |
except TypeError: | |
raise AttributeError(attr) | |
class HttpResponseWrapper(HttpResponse): | |
""" | |
Wrap HttpResponse and make sure that the internal _is_string | |
flag is updated when the _set_content method (via the content | |
property) is called | |
""" | |
def _set_content(self, content): | |
""" | |
Set the _container and _is_string properties based on the | |
type of the value parameter. This logic is in the construtor | |
for HttpResponse, but doesn't get repeated when setting | |
HttpResponse.content although this bug report (feature request) | |
suggests that it should: http://code.djangoproject.com/ticket/9403 | |
""" | |
if not isinstance(content, basestring) and hasattr(content, '__iter__'): | |
self._container = content | |
self._is_string = False | |
else: | |
self._container = [content] | |
self._is_string = True | |
content = property(HttpResponse._get_content, _set_content) | |
return HttpResponseWrapper(r, content_type='text/plain', status=c) | |
rc = rc_factory() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment