Created
May 21, 2014 02:44
-
-
Save victorono/157facbe71bc19f3a006 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
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| import json | |
| from django.conf import settings | |
| from django.http import HttpResponse, HttpResponseBadRequest | |
| from django.contrib import messages | |
| class AjaxError(Exception): | |
| pass | |
| def ajax_view(f): | |
| """ | |
| Return a valid ajax response | |
| """ | |
| def view(request, *args, **kwargs): | |
| if not settings.DEBUG and not request.is_ajax(): | |
| return HttpResponseBadRequest() | |
| try: | |
| res = f(request, *args, **kwargs) | |
| error = None | |
| except AjaxError, e: | |
| res = None | |
| error = str(e) | |
| except Exception, e: | |
| res = None | |
| if settings.DEBUG: | |
| error = 'Internal Error' | |
| else: | |
| error = str(e) | |
| django_messages = [] | |
| for message in messages.get_messages(request): | |
| django_messages.append({ | |
| "level": message.level, | |
| "message": unicode(message.message), | |
| "extra_tags": message.tags, | |
| }) | |
| context = { | |
| 'error': error, | |
| 'response': res, | |
| 'messages': django_messages | |
| } | |
| return HttpResponse(json.dumps(context), content_type = 'application/json', | |
| return view |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment