|
| 1 | +#---------------------------------------------------------------------- |
| 2 | +# Copyright (c) 2009-2011 Benito Jorge Bastida |
| 3 | +# All rights reserved. |
| 4 | +# Redistribution and use in source and binary forms, with or without |
| 5 | +# modification, are permitted provided that the following conditions are |
| 6 | +# met: |
| 7 | +# |
| 8 | +# o Redistributions of source code must retain the above copyright |
| 9 | +# notice, this list of conditions, and the disclaimer that follows. |
| 10 | +# |
| 11 | +# o Redistributions in binary form must reproduce the above copyright |
| 12 | +# notice, this list of conditions, and the following disclaimer in |
| 13 | +# the documentation and/or other materials provided with the |
| 14 | +# distribution. |
| 15 | +# |
| 16 | +# o Neither the name of Digital Creations nor the names of its |
| 17 | +# contributors may be used to endorse or promote products derived |
| 18 | +# from this software without specific prior written permission. |
| 19 | +# |
| 20 | +# THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS AND CONTRIBUTORS *AS |
| 21 | +# IS* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED |
| 22 | +# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A |
| 23 | +# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL DIGITAL |
| 24 | +# CREATIONS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
| 25 | +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
| 26 | +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS |
| 27 | +# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND |
| 28 | +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR |
| 29 | +# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE |
| 30 | +# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH |
| 31 | +# DAMAGE. |
| 32 | +#---------------------------------------------------------------------- |
| 33 | + |
| 34 | +import os |
| 35 | +import sys |
| 36 | +import logging |
| 37 | +import traceback |
| 38 | + |
| 39 | +from django.conf import settings |
| 40 | +from django.utils import simplejson |
| 41 | +from django.http import HttpResponse |
| 42 | + |
| 43 | +from dajaxice.core import dajaxice_functions |
| 44 | +from dajaxice.exceptions import FunctionNotCallableError, DajaxiceImportError |
| 45 | + |
| 46 | +log = logging.getLogger('dajaxice.DajaxiceRequest') |
| 47 | + |
| 48 | +# Python 2.7 has an importlib with import_module. |
| 49 | +# For older Pythons, Django's bundled copy provides it. |
| 50 | +# For older Django's dajaxice reduced_import_module. |
| 51 | +try: |
| 52 | + from importlib import import_module |
| 53 | +except: |
| 54 | + try: |
| 55 | + from django.utils.importlib import import_module |
| 56 | + except: |
| 57 | + from dajaxice.utils import simple_import_module as import_module |
| 58 | + |
| 59 | + |
| 60 | +def safe_dict(d): |
| 61 | + """ |
| 62 | + Recursively clone json structure with UTF-8 dictionary keys |
| 63 | + http://www.gossamer-threads.com/lists/python/bugs/684379 |
| 64 | + """ |
| 65 | + if isinstance(d, dict): |
| 66 | + return dict([(k.encode('utf-8'), safe_dict(v)) for k, v in d.iteritems()]) |
| 67 | + elif isinstance(d, list): |
| 68 | + return [safe_dict(x) for x in d] |
| 69 | + else: |
| 70 | + return d |
| 71 | + |
| 72 | + |
| 73 | +class DajaxiceRequest(object): |
| 74 | + |
| 75 | + def __init__(self, request, call): |
| 76 | + call = call.rsplit('.', 1) |
| 77 | + self.app_name = call[0] |
| 78 | + self.method = call[1] |
| 79 | + self.request = request |
| 80 | + |
| 81 | + self.project_name = os.environ['DJANGO_SETTINGS_MODULE'].split('.')[0] |
| 82 | + self.module = "%s.ajax" % self.app_name |
| 83 | + self.full_name = "%s.%s" % (self.module, self.method) |
| 84 | + |
| 85 | + @staticmethod |
| 86 | + def get_js_functions(): |
| 87 | + return dajaxice_functions.get_functions() |
| 88 | + |
| 89 | + @staticmethod |
| 90 | + def get_media_prefix(): |
| 91 | + return getattr(settings, 'DAJAXICE_MEDIA_PREFIX', "dajaxice") |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def get_functions(): |
| 95 | + return getattr(settings, 'DAJAXICE_FUNCTIONS', ()) |
| 96 | + |
| 97 | + @staticmethod |
| 98 | + def get_debug(): |
| 99 | + return getattr(settings, 'DAJAXICE_DEBUG', True) |
| 100 | + |
| 101 | + @staticmethod |
| 102 | + def get_notify_exceptions(): |
| 103 | + return getattr(settings, 'DAJAXICE_NOTIFY_EXCEPTIONS', False) |
| 104 | + |
| 105 | + @staticmethod |
| 106 | + def get_cache_control(): |
| 107 | + if settings.DEBUG: |
| 108 | + return 0 |
| 109 | + return getattr(settings, 'DAJAXICE_CACHE_CONTROL', 5 * 24 * 60 * 60) |
| 110 | + |
| 111 | + @staticmethod |
| 112 | + def get_xmlhttprequest_js_import(): |
| 113 | + return getattr(settings, 'DAJAXICE_XMLHTTPREQUEST_JS_IMPORT', True) |
| 114 | + |
| 115 | + @staticmethod |
| 116 | + def get_json2_js_import(): |
| 117 | + return getattr(settings, 'DAJAXICE_JSON2_JS_IMPORT', True) |
| 118 | + |
| 119 | + @staticmethod |
| 120 | + def get_exception_message(): |
| 121 | + return getattr(settings, 'DAJAXICE_EXCEPTION', u'DAJAXICE_EXCEPTION') |
| 122 | + |
| 123 | + @staticmethod |
| 124 | + def get_js_docstrings(): |
| 125 | + return getattr(settings, 'DAJAXICE_JS_DOCSTRINGS', False) |
| 126 | + |
| 127 | + def _is_callable(self): |
| 128 | + """ |
| 129 | + Return if the request function was registered. |
| 130 | + """ |
| 131 | + return dajaxice_functions.is_callable(self.full_name) |
| 132 | + |
| 133 | + def _get_ajax_function(self): |
| 134 | + """ |
| 135 | + Return a callable ajax function. |
| 136 | + This function should be imported according the Django version. |
| 137 | + """ |
| 138 | + return self._modern_get_ajax_function() |
| 139 | + |
| 140 | + def _modern_get_ajax_function(self): |
| 141 | + """ |
| 142 | + Return a callable ajax function. |
| 143 | + This function uses django.utils.importlib |
| 144 | + """ |
| 145 | + self.module_import_name = "%s.%s" % (self.project_name, self.module) |
| 146 | + try: |
| 147 | + return self._modern_import() |
| 148 | + except: |
| 149 | + self.module_import_name = self.module |
| 150 | + return self._modern_import() |
| 151 | + |
| 152 | + def _modern_import(self): |
| 153 | + try: |
| 154 | + mod = import_module(self.module_import_name) |
| 155 | + return mod.__getattribute__(self.method) |
| 156 | + except: |
| 157 | + raise DajaxiceImportError() |
| 158 | + |
| 159 | + def process(self): |
| 160 | + """ |
| 161 | + Process the dajax request calling the apropiate method. |
| 162 | + """ |
| 163 | + if self._is_callable(): |
| 164 | + log.debug('Function %s is callable' % self.full_name) |
| 165 | + |
| 166 | + argv = self.request.POST.get('argv') |
| 167 | + if argv != 'undefined': |
| 168 | + try: |
| 169 | + argv = simplejson.loads(self.request.POST.get('argv')) |
| 170 | + argv = safe_dict(argv) |
| 171 | + except Exception, e: |
| 172 | + log.error('argv exception %s' % e) |
| 173 | + argv = {} |
| 174 | + else: |
| 175 | + argv = {} |
| 176 | + |
| 177 | + log.debug('argv %s' % argv) |
| 178 | + |
| 179 | + try: |
| 180 | + thefunction = self._get_ajax_function() |
| 181 | + response = '%s' % thefunction(self.request, **argv) |
| 182 | + |
| 183 | + except Exception, e: |
| 184 | + trace = '\n'.join(traceback.format_exception(*sys.exc_info())) |
| 185 | + log.error(trace) |
| 186 | + response = '%s' % DajaxiceRequest.get_exception_message() |
| 187 | + |
| 188 | + if DajaxiceRequest.get_notify_exceptions(): |
| 189 | + self.notify_exception(self.request, sys.exc_info()) |
| 190 | + |
| 191 | + log.info('response: %s' % response) |
| 192 | + return HttpResponse(response, mimetype="application/x-json") |
| 193 | + |
| 194 | + else: |
| 195 | + log.debug('Function %s is not callable' % self.full_name) |
| 196 | + raise FunctionNotCallableError(name=self.full_name) |
| 197 | + |
| 198 | + def notify_exception(self, request, exc_info): |
| 199 | + """ |
| 200 | + Send Exception traceback to ADMINS |
| 201 | + Similar to BaseHandler.handle_uncaught_exception |
| 202 | + """ |
| 203 | + from django.conf import settings |
| 204 | + from django.core.mail import mail_admins |
| 205 | + |
| 206 | + subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path) |
| 207 | + try: |
| 208 | + request_repr = repr(request) |
| 209 | + except: |
| 210 | + request_repr = "Request repr() unavailable" |
| 211 | + |
| 212 | + trace = '\n'.join(traceback.format_exception(*(exc_info or sys.exc_info()))) |
| 213 | + message = "%s\n\n%s" % (trace, request_repr) |
| 214 | + mail_admins(subject, message, fail_silently=True) |
0 commit comments