Example #1
0
 def handle_404(self, request, exception):
     if settings.DEBUG:
         from django.views import debug
         return debug.technical_404_response(request, exception)
     else:
         callback, param_dict = resolver(request).resolve404()
         return callback(request, **param_dict)
Example #2
0
 def handle_404(self, request, exception):
     if settings.DEBUG:
         from django.views import debug
         return debug.technical_404_response(request, exception)
     else:
         callback, param_dict = resolver(request).resolve404()
         return callback(request, **param_dict)
Example #3
0
    def _handle_response_exception(self, request, response, e):

        if isinstance(e, http.Http404):
            logger.warning('Not Found: %s', request.path,
                        extra={
                            'status_code': 404,
                            'request': request
                        })
            if settings.DEBUG:
                response = debug.technical_404_response(request, e)
            else:
                try:
                    self.callback, param_dict = resolver.resolve404()
                    response = self.callback(request, **param_dict)
                except:
                    signals.got_request_exception.send(sender=self.__class__, request=request)
                    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        if isinstance(e, PermissionDenied):
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                })
            try:
                self.callback, param_dict = resolver.resolve403()
                response = self.callback(request, **param_dict)
            except:
                signals.got_request_exception.send(
                        sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request,
                        resolver, sys.exc_info())

        if isinstance(e, SuspiciousOperation):
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' %
                            e.__class__.__name__)
            security_logger.error(force_text(e))

            try:
                self.callback, param_dict = resolver.resolve400()
                response = self.callback(request, **param_dict)
            except:
                signals.got_request_exception.send(
                        sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request,
                        resolver, sys.exc_info())

        if isinstance(e, SystemExit):
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        else: # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, self.resolver, sys.exc_info())

        return response
Example #4
0
def server_error_404(request, template_name="404.html"):
    """
    Custom 404 handler method.

    The traceback is written to an html file and a plain text file
    which are placed in the log directory.
    """
    file_prefix = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S')
    ex_type, ex_value, ex_traceback = sys.exc_info() #@UnusedVariable
    try:
        # --- Log to file ---
        # Log straight to file with Django's normal 404 output
        traceback_404 = debug.technical_404_response(request, ex_value)
        destFilename = "%s_%s_404.html" %(file_prefix, settings.LOG_FILE)
        log_filepath = os.path.join(settings.LOG_DIR, destFilename)
        out_file = open(log_filepath, "w")
        out_file.write(traceback_404.content)
        out_file.close()

        # --- Render to page ---
        # Initialise Django's TECHNICAL_404_TEMPLATE to ours
        from main.httpd_errors import FLAT_404_TEMPLATE
        debug.TECHNICAL_404_TEMPLATE = FLAT_404_TEMPLATE
        traceback_404 = debug.technical_404_response(request, ex_value)
        destFilename = "%s_%s_404.log" %(file_prefix, settings.LOG_FILE)
        log_filepath = os.path.join(settings.LOG_DIR, destFilename)
        out_file = open(log_filepath, "w")
        out_file.write(traceback_404.content)
        out_file.close()

        # print request.path

        # --- Render to page ---
        # get our own custom technical 500 template to render for the browser
        # Initialise Django's TECHNICAL_500_TEMPLATE to ours
        from main.httpd_errors import TECHNICAL_404_TEMPLATE
        debug.TECHNICAL_404_TEMPLATE = TECHNICAL_404_TEMPLATE
        traceback_404 = debug.technical_404_response(request, ex_value)
        # now render the actual page
        template = loader.get_template(template_name) # You need to create a 404.html template!
        c = Context({
                     'traceback': traceback_404.content,
                     'log_filepath': log_filepath,
                     })
        response = HttpResponse(template.render(c))
    except Exception, e:
        response = HttpResponse('<html><body><p>%s</p>Click here to return <a href="/">home</a></body></html>' % unicode(e))
Example #5
0
	def process_response(self, request, response):
		if getattr(request, 'paginator_page_not_found', False):
			if settings.DEBUG:
				error = Http404('The requested page number is out of range.')
				return technical_404_response(request, error)
			else:
				callback, params = get_resolver(None).resolve404()
				return callback(request, **params)
		return response
Example #6
0
 def handle_404(self, request, exception):
     if settings.DEBUG:
         logger.debug('DEBUG=true')
         from django.views import debug
         return debug.technical_404_response(request, exception)
     else:
         logger.debug('DEBUG=false')
         callback, param_dict = self.resolver(request).resolve404()
         return callback(request, **param_dict)
Example #7
0
 def handle_404(self, request, exception):
     if settings.DEBUG:
         logger.debug('DEBUG=true')
         from django.views import debug
         return debug.technical_404_response(request, exception)
     else:
         logger.debug('DEBUG=false')
         callback, param_dict = self.resolver(request).resolve404()
         return callback(request, **param_dict)
Example #8
0
def handler_404(request):
    info = sys.exc_info()
    if request.settings.exists and not request.settings.DEBUG:
        try:
            template = loader.get_template(request.settings.TEMPLATE_404)
            return HttpResponseNotFound(template.render(RequestContext(request)))
        except:
            pass
    return debug.technical_404_response(request, info[1])
Example #9
0
    def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
    def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                return self.serve(request)
            except Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
Example #11
0
 def get_technical_error_response(self, request, is404=False, exception=None):
     """
     Returns an HttpResponse that displays a TECHNICAL error message for a
     fundamental database or coding error.
     """
     import sys
     from django.views import debug
     if is404:
         return debug.technical_404_response(request, exception)
     else:
         return debug.technical_500_response(request, *sys.exc_info())
Example #12
0
 def get_response(self, request):
     """
     Always tries to serve a static file as you don't even get into this
     handler subclass without the wrapper directing you here.
     """
     try:
         return self.serve(request)
     except Http404 as e:
         if settings.DEBUG:
             from django.views import debug
             return debug.technical_404_response(request, e)
Example #13
0
 def get_response(self, request):
     """
     Always tries to serve a static file as you don't even get into this
     handler subclass without the wrapper directing you here.
     """
     try:
         return self.serve(request)
     except Http404 as e:
         if settings.DEBUG:
             from django.views import debug
             return debug.technical_404_response(request, e)
Example #14
0
def response_for_exception(request, exc):
    if isinstance(exc, Http404):
        if settings.DEBUG:
            response = debug.technical_404_response(request, exc)
        else:
            response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc)

    elif isinstance(exc, PermissionDenied):
        logger.warning(
            'Forbidden (Permission denied): %s', request.path,
            extra={'status_code': 403, 'request': request},
        )
        response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc)

    elif isinstance(exc, MultiPartParserError):
        logger.warning(
            'Bad request (Unable to parse request body): %s', request.path,
            extra={'status_code': 400, 'request': request},
        )
        response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

    elif isinstance(exc, SuspiciousOperation):
        if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)):
            # POST data can't be accessed again, otherwise the original
            # exception would be raised.
            request._mark_post_parse_error()

        # The request logger receives events for any problematic request
        # The security logger receives events for all SuspiciousOperations
        security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__)
        security_logger.error(
            force_text(exc),
            extra={'status_code': 400, 'request': request},
        )
        if settings.DEBUG:
            response = debug.technical_500_response(request, *sys.exc_info(), status_code=400)
        else:
            response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

    elif isinstance(exc, SystemExit):
        # Allow sys.exit() to actually exit. See tickets #1023 and #4701
        raise

    else:
        signals.got_request_exception.send(sender=None, request=request)
        response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())

    # Force a TemplateResponse to be rendered.
    if not getattr(response, 'is_rendered', True) and callable(getattr(response, 'render', None)):
        response = response.render()

    return response
Example #15
0
 def handle_not_found(self, request, resolver, exception):
     """
     Logs a 404 warning and invokes either the debug handler or the
     resolver's 404 handler.
     
     """
     logger.warning(
         "Not Found: {path:s}".format(path=request.path),
         extra={"status_code": 404, "request": request})
     if settings.DEBUG:
         return debug.technical_404_response(request, exception)
     callback, kwargs = resolver.resolve404()
     return callback(request, **kwargs)
Example #16
0
 def __call__(self, request):
     # 当 debug 设置为 False 时,返回 404 时
     # 如果是管理员,则返回一个特殊的响应对象,也就是Debug页面
     # 如果是普通用户,则返回None,交给默认的流程处理
     response = self.get_response(request)
     if not settings.DEBUG:
         if response.status_code == 404:
             if request.session['issuperuser']:
                 try:
                     resolve(request.path)
                 except Resolver404 as e:
                     return technical_404_response(request, e)
     return response
Example #17
0
    def get_response(self, request):
        # logger.debug("StaticFileHandler::get_response %s", request.path)

        if self._should_handle(request.path):
            # logger.debug("StaticFileHandler::get_response should_handle")
            try:
                return self.serve(request)
            except Http404 as e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)

        # logger.debug("StaticFileHandler::get_response not should_handle")
        return super(StaticFilesHandler, self).get_response(request)
Example #18
0
    def get_response(self, request):
        from django.http import Http404

        if self._should_handle(request.path):
            try:
                response = self.serve(request)
                # Increase FileResponse block sizes so they're not super slow
                response.block_size = 1024 * 256
                return response
            except Http404 as e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
        return super(StaticFilesHandler, self).get_response(request)
Example #19
0
    def __call__(self, request):
        try:
            response = self.get_response(request)
        except Http404 as exc:
            if settings.DEBUG:
                response = debug.technical_404_response(request, exc)
            else:
                response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 404, exc)

        except PermissionDenied as exc:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={'status_code': 403, 'request': request},
            )
            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 403, exc)

        except MultiPartParserError as exc:
            logger.warning(
                'Bad request (Unable to parse request body): %s', request.path,
                extra={'status_code': 400, 'request': request},
            )
            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

        except SuspiciousOperation as exc:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__)
            security_logger.error(
                force_text(exc),
                extra={'status_code': 400, 'request': request},
            )
            if settings.DEBUG:
                return debug.technical_500_response(request, *sys.exc_info(), status_code=400)

            response = self.handler.get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except Exception:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.handler.__class__, request=request)
            response = self.handler.handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())

        return response
Example #20
0
def response_for_exception(request, exc):
    if isinstance(exc, Http404):
        if settings.DEBUG:
            response = debug.technical_404_response(request, exc)
        else:
            response = get_exception_response(request, get_resolver(get_urlconf()), 404, exc)

    elif isinstance(exc, PermissionDenied):
        logger.warning(
            'Forbidden (Permission denied): %s', request.path,
            extra={'status_code': 403, 'request': request},
        )
        response = get_exception_response(request, get_resolver(get_urlconf()), 403, exc)

    elif isinstance(exc, MultiPartParserError):
        logger.warning(
            'Bad request (Unable to parse request body): %s', request.path,
            extra={'status_code': 400, 'request': request},
        )
        response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

    elif isinstance(exc, SuspiciousOperation):
        # The request logger receives events for any problematic request
        # The security logger receives events for all SuspiciousOperations
        security_logger = logging.getLogger('django.security.%s' % exc.__class__.__name__)
        security_logger.error(
            force_text(exc),
            extra={'status_code': 400, 'request': request},
        )
        if settings.DEBUG:
            response = debug.technical_500_response(request, *sys.exc_info(), status_code=400)
        else:
            response = get_exception_response(request, get_resolver(get_urlconf()), 400, exc)

    elif isinstance(exc, SystemExit):
        # Allow sys.exit() to actually exit. See tickets #1023 and #4701
        raise

    else:
        signals.got_request_exception.send(sender=None, request=request)
        response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info())

    return response
Example #21
0
 def process_response(self, request, response):
     """If the response was a 404, attempt to serve up a page."""
     if response.status_code != 404:
         return response
     # Get the current page.
     page = request.pages.current
     if page is None:
         return response
     script_name = page.get_absolute_url()[:-1]
     path_info = request.path[len(script_name):]
     # Dispatch to the content.
     try:
         try:
             callback, callback_args, callback_kwargs = urlresolvers.resolve(
                 path_info, page.content.urlconf)
         except urlresolvers.Resolver404:
             # First of all see if adding a slash will help matters.
             if settings.APPEND_SLASH:
                 new_path_info = path_info + "/"
                 try:
                     urlresolvers.resolve(new_path_info,
                                          page.content.urlconf)
                 except urlresolvers.Resolver404:
                     pass
                 else:
                     return redirect(script_name + new_path_info)
             return response
         response = callback(request, *callback_args, **callback_kwargs)
         # Validate the response.
         if not response:
             raise ValueError, "The view {0!r} didn't return an HttpResponse object.".format(
                 callback.__name__)
         if isinstance(response, SimpleTemplateResponse):
             return response.render()
         return response
     except Http404, ex:
         if settings.DEBUG:
             return technical_404_response(request, ex)
         # Let the normal 404 mechanisms render an error page.
         return response
    def process_request(self, request):
        response = None
        method = request.method
        devopsgroup = None
        offset = 0
        limit = 0
        if method == "GET":
            devopsgroup = request.GET.get("devopsgroup", None)
            offset = int(request.GET.get('offset', 1))
            limit = int(request.GET.get('limit', PER_PAGE))
        if method == "POST":
            devopsgroup = request.POST.get("devopsgroup", None)
            offset = int(request.POST.get('offset', 1))
            limit = int(request.POST.get('limit', PER_PAGE))

        request.offset = offset
        request.limit = limit
        user = request.user
        if user.is_active:  #user.is_authenticated
            request.clienttype = 'PC'
            if devopsgroup:
                request.devopsgroup = devopsgroup
                request.devopsuser = user.username
            else:
                isSuperUser = user.is_superuser
                if isSuperUser:
                    devopsgroup = 'all'
                else:
                    user_group = Group.objects.get(user=user)
                    devopsgroup = user_group.name
                if devopsgroup:
                    request.devopsgroup = devopsgroup
                    request.devopsuser = user.username
                else:
                    response = debug.technical_404_response(request, Http404())

        return response
Example #23
0
 def process_response(self, request, response):
     """If the response was a 404, attempt to serve up a page."""
     if response.status_code != 404:
         return response
     # Get the current page.
     page = request.pages.current
     if page is None:
         return response
     script_name = page.get_absolute_url()[:-1]
     path_info = request.path[len(script_name):]
     # Dispatch to the content.
     try:
         try:
             callback, callback_args, callback_kwargs = urlresolvers.resolve(path_info, page.content.urlconf)
         except urlresolvers.Resolver404:
             # First of all see if adding a slash will help matters.
             if settings.APPEND_SLASH:
                 new_path_info = path_info + "/"
                 try:
                     urlresolvers.resolve(new_path_info, page.content.urlconf)
                 except urlresolvers.Resolver404:
                     pass
                 else:
                     return redirect(script_name + new_path_info)
             return response
         response = callback(request, *callback_args, **callback_kwargs)
         # Validate the response.
         if not response:
             raise ValueError, "The view {0!r} didn't return an HttpResponse object.".format(callback.__name__)
         if isinstance(response, SimpleTemplateResponse):
             return response.render()
         return response
     except Http404, ex:
         if settings.DEBUG:
             return technical_404_response(request, ex)
         # Let the normal 404 mechanisms render an error page.
         return response
Example #24
0
    def __call__(self, request, *args, **kwargs):
        try:
            return self.func(request, *args, **kwargs)

        except exceptions.DisallowedHost as ex:
            self.GetLogger(request).exception(GetEnvInfo(request))
            response = self._page400(request)
            return response

        except Http404 as e:

            if settings.DEBUG:
                self.GetLogger(request).exception(GetEnvInfo(request))
                from django.views import debug
                response = debug.technical_404_response(request, e)
            else:
                response = self._page404(request)

            response.source_exc = e
            return response

        except TooLongRequestException as ex:
            traceback = FormatTraceback()
            log_res.exception(
                "TooLongRequestException: ('{}';  '{}'; '{}')".format(
                    request.META['REMOTE_ADDR'],
                    request.full_url,
                    request.META.get('HTTP_USER_AGENT', 'NONE'),
                ))

            if settings.DEBUG:
                from django.views import debug
                return debug.technical_500_response(request, *sys.exc_info())

            response = self._page500(request, status=503)
            response._exc_details = (ex, traceback)
            return response

        except (OperationalError, DjangoOperationalError) as ex:

            traceback = FormatTraceback()
            log_res.exception("OperationalError: ('{}';  '{}'; '{}')".format(
                request.META['REMOTE_ADDR'],
                request.full_url,
                request.META.get('HTTP_USER_AGENT', 'NONE'),
            ))

            if settings.DEBUG:
                from django.views import debug
                return debug.technical_500_response(request, *sys.exc_info())

            response = self._page500(request, status=503)
            response._exc_details = (ex, traceback)
            response.skip_bug_report = True
            return response

        except exceptions.PermissionDenied as pd:
            if settings.DEBUG:
                self.GetLogger(request).exception(GetEnvInfo(request))
            response = self._page403(request)
            response.source_exc = pd
            return response

        except BadRequestException as pd:
            self.GetLogger(request).exception(GetEnvInfo(request))
            response = self._page400(request)
            response.skip_bug_report = True
            return response

        except BotRequestException as ex:
            self.GetLogger(request).exception(GetEnvInfo(request))
            response = self._page503(request, status=503)
            response.skip_bug_report = True
            return response

        except NotImplementedError as ex:
            self.GetLogger(request).exception(GetEnvInfo(request))
            return self._page500(request, status=503)

        except SystemExit:
            pass  # See http://code.djangoproject.com/ticket/1023

        except Exception as ex:  # Handle everything else

            traceback = FormatTraceback()
            self.GetLogger(request).exception(GetEnvInfo(request))

            # if settings.DEBUG:
            # 	from django.views import debug
            # 	return debug.technical_500_response(request, *sys.exc_info())

            response = self._page502(request)
            response._exc_details = (ex, traceback)

            return response
Example #25
0
 def handle_404(self, request, e):
     if self.debug:
         from django.views import debug
         return debug.technical_404_response(request, e)
     else:
         return http.HttpResponseNotFound('<h1>404</h1>')
Example #26
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        return response

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        return response

                try:
                    response = callback(request, *callback_args, **callback_kwargs)
                except Exception, e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            return response
                    raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__' # If it's a class
                    raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))

                return response
            except http.Http404, e:
                logger.warning('Not Found: %s' % request.path,
                            extra={
                                'status_code': 404,
                                'request': request
                            })
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        return callback(request, **param_dict)
                    except:
                        try:
                            return self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
Example #27
0
    def get_response(self, request):
        # type: (HttpRequest) -> HttpResponse
        "Returns an HttpResponse object for the given HttpRequest"
        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                response = None

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                ### ADDED BY ZULIP
                request._resolver = resolver
                ### END ADDED BY ZULIP

                callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)

                # Apply view middleware
                if response is None:
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback,
                                                     callback_args,
                                                     callback_kwargs)
                        if response:
                            break

                ### THIS BLOCK MODIFIED BY ZULIP
                if response is None:
                    from ...decorator import RespondAsynchronously

                    try:
                        response = callback(request, *callback_args,
                                            **callback_kwargs)
                        if response is RespondAsynchronously:
                            async_request_stop(request)
                            return None
                        clear_handler_by_id(self.handler_id)
                    except Exception as e:
                        clear_handler_by_id(self.handler_id)
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                if response is None:
                    try:
                        view_name = callback.__name__
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s returned None." %
                                     (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(
                                request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(
                                sender=self.__class__, request=request)
            except exceptions.PermissionDenied:
                logging.warning('Forbidden (Permission denied): %s',
                                request.path,
                                extra={
                                    'status_code': 403,
                                    'request': request
                                })
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except:
                    try:
                        response = self.handle_uncaught_exception(
                            request, resolver, sys.exc_info())
                    finally:
                        signals.got_request_exception.send(
                            sender=self.__class__, request=request)
            except SystemExit:
                # See https://code.djangoproject.com/ticket/4701
                raise
            except Exception as e:
                exc_info = sys.exc_info()
                signals.got_request_exception.send(sender=self.__class__,
                                                   request=request)
                return self.handle_uncaught_exception(request, resolver,
                                                      exc_info)
        finally:
            # Reset urlconf on the way out for isolation
            urlresolvers.set_urlconf(None)

        ### ZULIP CHANGE: The remainder of this function was moved
        ### into its own function, just below, so we can call it from
        ### finish().
        response = self.apply_response_middleware(request, response, resolver)

        return response
Example #28
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            # Setup default url resolver for this thread, this code is outside
            # the try/except so we don't get a spurious "unbound local
            # variable" exception in the event an exception is raised before
            # resolver is set
            urlconf = settings.ROOT_URLCONF
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
            try:
                response = None
                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if response is None:
                    if hasattr(request, "urlconf"):
                        # Reset url resolver with a custom urlconf.
                        urlconf = request.urlconf
                        urlresolvers.set_urlconf(urlconf)
                        resolver = urlresolvers.RegexURLResolver(
                            r'^/', urlconf)

                    callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                    # Apply view middleware
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback,
                                                     callback_args,
                                                     callback_kwargs)
                        if response:
                            break

                if response is None:
                    try:
                        response = callback(request, *callback_args,
                                            **callback_kwargs)
                    except Exception, e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name  # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'  # If it's a class
                    raise ValueError(
                        "The view %s.%s didn't return an HttpResponse object."
                        % (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404, e:
                logger.warning('Not Found: %s',
                               request.path,
                               extra={
                                   'status_code': 404,
                                   'request': request
                               })
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(
                                request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(
                                sender=self.__class__, request=request)
Example #29
0
                raise

            # Complain if the view returned None (a common error).
            if response is None:
                try:
                    view_name = callback.func_name  # If it's a function
                except AttributeError:
                    view_name = callback.__class__.__name__ + '.__call__'  # If it's a class
                raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (
                    callback.__module__, view_name)

            return response
        except http.Http404, e:
            if settings.DEBUG:
                from django.views import debug
                return debug.technical_404_response(request, e)
            else:
                callback, param_dict = resolver.resolve404()
                return callback(request, **param_dict)
        except exceptions.PermissionDenied:
            return http.HttpResponseForbidden('<h1>Permission denied</h1>')
        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise
        except:  # Handle everything else, including SuspiciousOperation, etc.
            # Get the exception info now, in case another exception is thrown later.
            exc_info = sys.exc_info()
            receivers = dispatcher.send(signal=signals.got_request_exception,
                                        request=request)

            if settings.DEBUG_PROPAGATE_EXCEPTIONS:
Example #30
0
    def __call__(self, request):
        try:
            response = self.get_response(request)
        except Http404 as exc:
            if settings.DEBUG:
                response = debug.technical_404_response(request, exc)
            else:
                response = self.handler.get_exception_response(
                    request, get_resolver(get_urlconf()), 404, exc)

        except PermissionDenied as exc:
            logger.warning(
                'Forbidden (Permission denied): %s',
                request.path,
                extra={
                    'status_code': 403,
                    'request': request
                },
            )
            response = self.handler.get_exception_response(
                request, get_resolver(get_urlconf()), 403, exc)

        except MultiPartParserError as exc:
            logger.warning(
                'Bad request (Unable to parse request body): %s',
                request.path,
                extra={
                    'status_code': 400,
                    'request': request
                },
            )
            response = self.handler.get_exception_response(
                request, get_resolver(get_urlconf()), 400, exc)

        except SuspiciousOperation as exc:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' %
                                                exc.__class__.__name__)
            security_logger.error(
                force_text(exc),
                extra={
                    'status_code': 400,
                    'request': request
                },
            )
            if settings.DEBUG:
                return debug.technical_500_response(request,
                                                    *sys.exc_info(),
                                                    status_code=400)

            response = self.handler.get_exception_response(
                request, get_resolver(get_urlconf()), 400, exc)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except Exception:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.handler.__class__,
                                               request=request)
            response = self.handler.handle_uncaught_exception(
                request, get_resolver(get_urlconf()), sys.exc_info())

        return response
Example #31
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"

        # Setup default url resolver for this thread, this code is outside
        # the try/except so we don't get a spurious "unbound local
        # variable" exception in the event an exception is raised before
        # resolver is set
        urlconf = settings.ROOT_URLCONF
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.get_resolver(urlconf)
        # Use a flag to check if the response was rendered to prevent
        # multiple renderings or to force rendering if necessary.
        response_is_rendered = False
        try:
            response = None
            # Apply request middleware
            for middleware_method in self._request_middleware:
                response = middleware_method(request)
                if response:
                    break

            if response is None:
                if hasattr(request, 'urlconf'):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.get_resolver(urlconf)

                resolver_match = resolver.resolve(request.path_info)
                callback, callback_args, callback_kwargs = resolver_match
                request.resolver_match = resolver_match

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        break

            if response is None:
                wrapped_callback = self.make_view_atomic(callback)
                try:
                    response = wrapped_callback(request, *callback_args, **callback_kwargs)
                except Exception as e:
                    response = self.process_exception_by_middleware(e, request)

            # Complain if the view returned None (a common error).
            if response is None:
                if isinstance(callback, types.FunctionType):    # FBV
                    view_name = callback.__name__
                else:                                           # CBV
                    view_name = callback.__class__.__name__ + '.__call__'
                raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
                                 % (callback.__module__, view_name))

            # If the response supports deferred rendering, apply template
            # response middleware and then render the response
            if hasattr(response, 'render') and callable(response.render):
                for middleware_method in self._template_response_middleware:
                    response = middleware_method(request, response)
                    # Complain if the template response middleware returned None (a common error).
                    if response is None:
                        raise ValueError(
                            "%s.process_template_response didn't return an "
                            "HttpResponse object. It returned None instead."
                            % (middleware_method.__self__.__class__.__name__))
                try:
                    response = response.render()
                except Exception as e:
                    response = self.process_exception_by_middleware(e, request)

                response_is_rendered = True

        except http.Http404 as exc:
            logger.warning('Not Found: %s', request.path,
                        extra={
                            'status_code': 404,
                            'request': request
                        })
            if settings.DEBUG:
                response = debug.technical_404_response(request, exc)
            else:
                response = self.get_exception_response(request, resolver, 404, exc)

        except PermissionDenied as exc:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 403, exc)

        except MultiPartParserError as exc:
            logger.warning(
                'Bad request (Unable to parse request body): %s', request.path,
                extra={
                    'status_code': 400,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 400, exc)

        except SuspiciousOperation as exc:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' %
                            exc.__class__.__name__)
            security_logger.error(
                force_text(exc),
                extra={
                    'status_code': 400,
                    'request': request
                })
            if settings.DEBUG:
                return debug.technical_500_response(request, *sys.exc_info(), status_code=400)

            response = self.get_exception_response(request, resolver, 400, exc)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
                # Complain if the response middleware returned None (a common error).
                if response is None:
                    raise ValueError(
                        "%s.process_response didn't return an "
                        "HttpResponse object. It returned None instead."
                        % (middleware_method.__self__.__class__.__name__))
            response = self.apply_response_fixes(request, response)
        except:  # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        response._closable_objects.append(request)

        # If the exception handler returns a TemplateResponse that has not
        # been rendered, force it to be rendered.
        if not response_is_rendered and callable(getattr(response, 'render', None)):
            response = response.render()

        return response
Example #32
0
def try_process_exception(request):
    json_output = json_requested(request)

    logger.exception("Error in {} {}".format(
        request.method,
        request.POST.get(conf.submission_action_post_name) or request.path))

    try:
        try:
            raise

        except InvalidForm as e:
            if json_output:
                return json_response(
                    {
                        "success": False,
                        "reason": "invalid_form",
                        "errors": e.form.errors,
                    },
                    status=403,
                    request=request)

            request._failed_form = e.form
            return None

        except InvalidSubmission as e:
            if json_output:
                return json_response(
                    {
                        "success": False,
                        "reason": "invalid_submission",
                        "error": e.error_key,
                    },
                    status=403,
                    request=request)

            request._submission_error_key = e.error_key
            return None

        except AuthenticationRequired as e:
            return response_authentication_required(request, e)

        except ApiError as e:
            if json_output:
                return json_response(combine_dicts(
                    {
                        "success": False,
                        "reason": e.reason,
                    }, e.data),
                                     status=403,
                                     request=request)
            else:
                raise

        # Working around Django bug #6094. TODO: FIXME all the rest of the function is a dirty hack.
        except Http404 as e:
            if settings.DEBUG:
                from django.views import debug
                return debug.technical_404_response(request, e)
            return HttpResponseNotFound()

    except Exception as e:
        if json_output:
            response = {
                "success": False,
                "reason": "exception",
            }
            if settings.DEBUG:
                response.update({
                    "error": repr(e),
                    "traceback": traceback.format_exc(),
                })
            return json_response(response, status=500, request=request)

        if not settings.DEBUG or settings.DEBUG_PROPAGATE_EXCEPTIONS:
            raise

        return django.views.debug.technical_500_response(
            request, *sys.exc_info())
Example #33
0
 def process_exception(self, request, exception):
     if request.user.is_superuser or request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
         return technical_404_response(request, *sys.exc_info())
Example #34
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"

        # Setup default url resolver for this thread, this code is outside
        # the try/except so we don't get a spurious "unbound local
        # variable" exception in the event an exception is raised before
        # resolver is set
        # 这个resolver本来就要放在外面啊=.=
        urlconf = settings.ROOT_URLCONF
        #  根URLconfig设置在当前线程默认为/,但是请求中一般有urlconf,会重写
        urlresolvers.set_urlconf(urlconf)
        # 拿到了全局的解析器,TODO:为什么不将该resolver直接放在线程中,而是在这里创建,需要reverse的时候又创建
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            response = None
            # Apply request middleware,一旦有请求中间件返回response就停止
            for middleware_method in self._request_middleware:
                response = middleware_method(request)
                if response:
                    break
            # 如果返回的是空,说明所有中间件执行了,但是没有返回response,就继续处理
            if response is None:
                # 如果请求有urlconf属性,则重新配置resolver
                if hasattr(request, 'urlconf'):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    #  路径以/开头
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
                # 这里可能抛出resolve404,是HTTP404的子类,会被正确处理
                resolver_match = resolver.resolve(request.path_info)
                callback, callback_args, callback_kwargs = resolver_match
                # 在request上设置匹配到的ResolverMatch
                request.resolver_match = resolver_match

                # Apply view middleware
                # 应用视图方法的中间件
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        break

            # 调用视图方法,如果调用过程中抛出异常,则使用异常中间件
            if response is None:
                wrapped_callback = self.make_view_atomic(callback)
                try:
                    response = wrapped_callback(request, *callback_args, **callback_kwargs)
                except Exception as e:
                    # 使用异常中间件处理视图抛出的异常
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            break
                    if response is None:
                        raise

            # Complain if the view returned None (a common error).
            # 视图函数不应该返回None
            if response is None:
                if isinstance(callback, types.FunctionType):  # FBV
                    view_name = callback.__name__
                else:  # CBV
                    view_name = callback.__class__.__name__ + '.__call__'
                raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
                                 % (callback.__module__, view_name))

            # If the response supports deferred rendering, apply template
            # response middleware and then render the response
            # 如果响应支持延迟的渲染,那么就使用模板响应中间件然后渲染响应.
            if hasattr(response, 'render') and callable(response.render):
                for middleware_method in self._template_response_middleware:
                    response = middleware_method(request, response)
                    # Complain if the template response middleware returned None (a common error).
                    if response is None:
                        raise ValueError(
                            "%s.process_template_response didn't return an "
                            "HttpResponse object. It returned None instead."
                            % (middleware_method.__self__.__class__.__name__))
                response = response.render()

        # 可能在resolve的过程中抛出的
        except http.Http404 as e:
            logger.warning('Not Found: %s', request.path,
                           extra={
                               'status_code': 404,
                               'request': request
                           })
            if settings.DEBUG:
                response = debug.technical_404_response(request, e)
            else:
                response = self.get_exception_response(request, resolver, 404)
        # 权限中间件可以使用
        except PermissionDenied:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 403)

        # TODO
        except MultiPartParserError:
            logger.warning(
                'Bad request (Unable to parse request body): %s', request.path,
                extra={
                    'status_code': 400,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 400)
        # 可疑的操作
        except SuspiciousOperation as e:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            # request logger就是本模块的全局logger
            security_logger = logging.getLogger('django.security.%s' %
                                                e.__class__.__name__)
            security_logger.error(
                force_text(e),
                extra={
                    'status_code': 400,
                    'request': request
                })
            if settings.DEBUG:
                return debug.technical_500_response(request, *sys.exc_info(), status_code=400)

            response = self.get_exception_response(request, resolver, 400)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            # 把信号发送给出去
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        try:
            # Apply response middleware, regardless of the response
            # 依次执行响应中间件,如果此时发生异常,则会视为500异常
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
                # Complain if the response middleware returned None (a common error).
                if response is None:
                    raise ValueError(
                        "%s.process_response didn't return an "
                        "HttpResponse object. It returned None instead."
                        % (middleware_method.__self__.__class__.__name__))
            # 执行完之后执行response_fixes
            response = self.apply_response_fixes(request, response)
        except:  # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        # 这个是什么,是添加可关闭的对象,然后wsgi会关闭这些对象吗,request方法的close好像是关闭使用的文件
        response._closable_objects.append(request)

        return response
Example #35
0
 def handle_404(self, request, e):
     if self.debug:
         from django.views import debug
         return debug.technical_404_response(request, e)
     else:
         return http.HttpResponseNotFound('<h1>404</h1>')
Example #36
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django import http
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                response = None

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                ### ADDED BY ZULIP
                request._resolver = resolver
                ### END ADDED BY ZULIP

                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                # Apply view middleware
                if response is None:
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback, callback_args, callback_kwargs)
                        if response:
                            break

                ### THIS BLOCK MODIFIED BY ZULIP
                if response is None:
                    from ...decorator import RespondAsynchronously

                    try:
                        response = callback(request, *callback_args, **callback_kwargs)
                        if response is RespondAsynchronously:
                            async_request_stop(request)
                            return
                    except Exception, e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                if response is None:
                    try:
                        view_name = callback.func_name
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s returned None." %
                                     (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()


            except http.Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(sender=self.__class__, request=request)
Example #37
0
    def process_response(self, request, response):
        """If the response was a 404, attempt to serve up a page."""
        if response.status_code != 404:
            return response
        # Get the current page.
        page = request.pages.current
        if page is None:
            return response
        script_name = page.get_absolute_url()[:-1]
        path_info = request.path[len(script_name):]

        # Continue for media
        if request.path.startswith('/media/'):
            return response

        if hasattr(request, 'country') and request.country is not None:
            script_name = '/{}{}'.format(
                request.country.code.lower(),
                script_name
            )

        # Dispatch to the content.
        try:
            try:
                callback, callback_args, callback_kwargs = urlresolvers.resolve(path_info, page.content.urlconf)
            except urlresolvers.Resolver404:
                # First of all see if adding a slash will help matters.
                if settings.APPEND_SLASH:
                    new_path_info = path_info + "/"

                    try:
                        urlresolvers.resolve(new_path_info, page.content.urlconf)
                    except urlresolvers.Resolver404:
                        pass
                    else:
                        return redirect(script_name + new_path_info, permanent=True)
                return response
            response = callback(request, *callback_args, **callback_kwargs)
            # Validate the response.
            if not response:
                raise ValueError("The view {0!r} didn't return an HttpResponse object.".format(
                    callback.__name__
                ))

            if request:
                if page.auth_required() and not request.user.is_authenticated():
                    return redirect("{}?next={}".format(
                        settings.LOGIN_URL,
                        request.path
                    ))

            if isinstance(response, SimpleTemplateResponse):
                return response.render()

            return response
        except Http404 as ex:
            if settings.DEBUG:
                return technical_404_response(request, ex)
            # Let the normal 404 mechanisms render an error page.
            return response
        except:
            return BaseHandler().handle_uncaught_exception(request, urlresolvers.get_resolver(None), sys.exc_info())
Example #38
0
def view404(request, exception):
    exc_type, exc_value, tb = sys.exc_info()
    return technical_404_response(request, exc_value)
Example #39
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            # Setup default url resolver for this thread, this code is outside
            # the try/except so we don't get a spurious "unbound local
            # variable" exception in the event an exception is raised before
            # resolver is set
            urlconf = settings.ROOT_URLCONF
            urlresolvers.set_urlconf(urlconf)
            resolver = urlresolvers.RegexURLResolver(r"^/", urlconf)
            try:
                response = None
                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if response is None:
                    if hasattr(request, "urlconf"):
                        # Reset url resolver with a custom urlconf.
                        urlconf = request.urlconf
                        urlresolvers.set_urlconf(urlconf)
                        resolver = urlresolvers.RegexURLResolver(r"^/", urlconf)

                    callback, callback_args, callback_kwargs = resolver.resolve(request.path_info)

                    # Apply view middleware
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback, callback_args, callback_kwargs)
                        if response:
                            break

                if response is None:
                    try:
                        response = callback(request, *callback_args, **callback_kwargs)
                    except Exception as e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name  # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + ".__call__"  # If it's a class
                    raise ValueError(
                        "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)
                    )

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, "render") and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                logger.warning("Not Found: %s", request.path, extra={"status_code": 404, "request": request})
                if settings.DEBUG:
                    from django.views import debug

                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(sender=self.__class__, request=request)
            except exceptions.PermissionDenied:
                logger.warning(
                    "Forbidden (Permission denied): %s", request.path, extra={"status_code": 403, "request": request}
                )
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except:
                    try:
                        response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
                    finally:
                        signals.got_request_exception.send(sender=self.__class__, request=request)
            except SystemExit:
                # Allow sys.exit() to actually exit. See tickets #1023 and #4701
                raise
            except:  # Handle everything else, including SuspiciousOperation, etc.
                # Get the exception info now, in case another exception is thrown later.
                signals.got_request_exception.send(sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
        finally:
            # Reset URLconf for this thread on the way out for complete
            # isolation of request.urlconf
            urlresolvers.set_urlconf(None)

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except:  # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        return response
Example #40
0
 def process_exception(self, request, exception):
     if request.user.is_superuser:
         if isinstance(exception, Http404):
             return technical_404_response(request, exception)
         return technical_500_response(request, *sys.exc_info())
Example #41
0
 def f(request, *args, **kwargs):
     if not test():
         return technical_404_response(request, Http404(message))
     return func(request, *args, **kwargs)
Example #42
0
File: base.py Project: un33k/django
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"

        # Setup default url resolver for this thread, this code is outside
        # the try/except so we don't get a spurious "unbound local
        # variable" exception in the event an exception is raised before
        # resolver is set
        urlconf = settings.ROOT_URLCONF
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            response = None
            # Apply request middleware
            for middleware_method in self._request_middleware:
                response = middleware_method(request)
                if response:
                    break

            if response is None:
                if hasattr(request, 'urlconf'):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                resolver_match = resolver.resolve(request.path_info)
                callback, callback_args, callback_kwargs = resolver_match
                request.resolver_match = resolver_match

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback,
                                                 callback_args,
                                                 callback_kwargs)
                    if response:
                        break

            if response is None:
                wrapped_callback = self.make_view_atomic(callback)
                try:
                    response = wrapped_callback(request, *callback_args,
                                                **callback_kwargs)
                except Exception as e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            break
                    if response is None:
                        raise

            # Complain if the view returned None (a common error).
            if response is None:
                if isinstance(callback, types.FunctionType):  # FBV
                    view_name = callback.__name__
                else:  # CBV
                    view_name = callback.__class__.__name__ + '.__call__'
                raise ValueError(
                    "The view %s.%s didn't return an HttpResponse object." %
                    (callback.__module__, view_name))

            # If the response supports deferred rendering, apply template
            # response middleware and then render the response
            if hasattr(response, 'render') and callable(response.render):
                for middleware_method in self._template_response_middleware:
                    response = middleware_method(request, response)
                response = response.render()

        except http.Http404 as e:
            logger.warning('Not Found: %s',
                           request.path,
                           extra={
                               'status_code': 404,
                               'request': request
                           })
            if settings.DEBUG:
                response = debug.technical_404_response(request, e)
            else:
                try:
                    callback, param_dict = resolver.resolve404()
                    response = callback(request, **param_dict)
                except:
                    signals.got_request_exception.send(sender=self.__class__,
                                                       request=request)
                    response = self.handle_uncaught_exception(
                        request, resolver, sys.exc_info())

        except PermissionDenied:
            logger.warning('Forbidden (Permission denied): %s',
                           request.path,
                           extra={
                               'status_code': 403,
                               'request': request
                           })
            try:
                callback, param_dict = resolver.resolve403()
                response = callback(request, **param_dict)
            except:
                signals.got_request_exception.send(sender=self.__class__,
                                                   request=request)
                response = self.handle_uncaught_exception(
                    request, resolver, sys.exc_info())

        except SuspiciousOperation as e:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' %
                                                e.__class__.__name__)
            security_logger.error(force_text(e),
                                  extra={
                                      'status_code': 400,
                                      'request': request
                                  })

            try:
                callback, param_dict = resolver.resolve400()
                response = callback(request, **param_dict)
            except:
                signals.got_request_exception.send(sender=self.__class__,
                                                   request=request)
                response = self.handle_uncaught_exception(
                    request, resolver, sys.exc_info())

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.__class__,
                                               request=request)
            response = self.handle_uncaught_exception(request, resolver,
                                                      sys.exc_info())

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except:  # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__,
                                               request=request)
            response = self.handle_uncaught_exception(request, resolver,
                                                      sys.exc_info())

        return response
Example #43
0
    def process_response(self, request, response):
        """If the response was a 404, attempt to serve up a page."""
        if response.status_code != 404:
            return response
        # Get the current page.
        page = request.pages.current
        if page is None:
            return response
        script_name = page.get_absolute_url()[:-1]
        path_info = request.path[len(script_name):]

        # Continue for media
        if request.path.startswith('/media/'):
            return response

        if hasattr(request, 'country') and request.country is not None:
            script_name = '/{}{}'.format(request.country.code.lower(),
                                         script_name)

        # Dispatch to the content.
        try:
            try:
                callback, callback_args, callback_kwargs = urlresolvers.resolve(
                    path_info, page.content.urlconf)
            except urlresolvers.Resolver404:
                # First of all see if adding a slash will help matters.
                if settings.APPEND_SLASH:
                    new_path_info = path_info + "/"

                    try:
                        urlresolvers.resolve(new_path_info,
                                             page.content.urlconf)
                    except urlresolvers.Resolver404:
                        pass
                    else:
                        return redirect(script_name + new_path_info,
                                        permanent=True)
                return response
            response = callback(request, *callback_args, **callback_kwargs)
            # Validate the response.
            if not response:
                raise ValueError(
                    "The view {0!r} didn't return an HttpResponse object.".
                    format(callback.__name__))

            if request:
                if page.auth_required(
                ) and not request.user.is_authenticated():
                    return redirect("{}?next={}".format(
                        settings.LOGIN_URL, request.path))

            if isinstance(response, SimpleTemplateResponse):
                return response.render()

            return response
        except Http404 as ex:
            if settings.DEBUG:
                return technical_404_response(request, ex)
            # Let the normal 404 mechanisms render an error page.
            return response
        except:
            return BaseHandler().handle_uncaught_exception(
                request, urlresolvers.get_resolver(None), sys.exc_info())
Example #44
0
    def get_response(self, request):
        # type: (HttpRequest) -> HttpResponse
        "Returns an HttpResponse object for the given HttpRequest"
        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                response = None

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                ### ADDED BY ZULIP
                request._resolver = resolver
                ### END ADDED BY ZULIP

                callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)

                # Apply view middleware
                if response is None:
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback, callback_args,
                                                     callback_kwargs)
                        if response:
                            break

                ### THIS BLOCK MODIFIED BY ZULIP
                if response is None:
                    try:
                        response = callback(request, *callback_args, **callback_kwargs)
                        if response is RespondAsynchronously:
                            async_request_stop(request)
                            return None
                        clear_handler_by_id(self.handler_id)
                    except Exception as e:
                        clear_handler_by_id(self.handler_id)
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                if response is None:
                    try:
                        view_name = callback.__name__
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s returned None." %
                                     (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except Exception:
                        try:
                            response = self.handle_uncaught_exception(request, resolver,
                                                                      sys.exc_info())
                        finally:
                            signals.got_request_exception.send(sender=self.__class__,
                                                               request=request)
            except exceptions.PermissionDenied:
                logging.warning(
                    'Forbidden (Permission denied): %s', request.path,
                    extra={
                        'status_code': 403,
                        'request': request
                    })
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except Exception:
                    try:
                        response = self.handle_uncaught_exception(request,
                                                                  resolver, sys.exc_info())
                    finally:
                        signals.got_request_exception.send(
                            sender=self.__class__, request=request)
            except SystemExit:
                # See https://code.djangoproject.com/ticket/4701
                raise
            except Exception as e:
                exc_info = sys.exc_info()
                signals.got_request_exception.send(sender=self.__class__, request=request)
                return self.handle_uncaught_exception(request, resolver, exc_info)
        finally:
            # Reset urlconf on the way out for isolation
            urlresolvers.set_urlconf(None)

        ### ZULIP CHANGE: The remainder of this function was moved
        ### into its own function, just below, so we can call it from
        ### finish().
        response = self.apply_response_middleware(request, response, resolver)

        return response
Example #45
0
            if response is None:
                try:
                    view_name = callback.func_name  # If it's a function
                except AttributeError:
                    view_name = callback.__class__.__name__ + ".__call__"  # If it's a class
                raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (
                    callback.__module__,
                    view_name,
                )

            return response
        except http.Http404, e:
            if settings.DEBUG:
                from django.views import debug

                return debug.technical_404_response(request, e)
            else:
                try:
                    callback, param_dict = resolver.resolve404()
                    return callback(request, **param_dict)
                except:
                    try:
                        return self.handle_uncaught_exception(request, resolver, sys.exc_info())
                    finally:
                        receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
        except exceptions.PermissionDenied:
            return http.HttpResponseForbidden("<h1>Permission denied</h1>")
        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise
        except:  # Handle everything else, including SuspiciousOperation, etc.
Example #46
0
from django.conf import settings
Example #47
0
class DjangoHandler(tornado.web.RequestHandler, base.BaseHandler) :
    initLock = Lock()

    def __init__(self, *args, **kwargs) :
        super(DjangoHandler, self).__init__(*args, **kwargs)

        # Set up middleware if needed. We couldn't do this earlier, because
        # settings weren't available.
        self._request_middleware = None
        self.initLock.acquire()
        # Check that middleware is still uninitialised.
        if self._request_middleware is None:
            self.load_middleware()
        self.initLock.release()
        self._auto_finish = False

    def head(self) :
        self.get()

    def get(self) :
        from tornado.wsgi import HTTPRequest, WSGIContainer
        from django.core.handlers.wsgi import WSGIRequest, STATUS_CODE_TEXT
        import urllib

        environ  = WSGIContainer.environ(self.request)
        environ['PATH_INFO'] = urllib.unquote(environ['PATH_INFO'])
        request  = WSGIRequest(environ)

        request._tornado_handler     = self

        set_script_prefix(base.get_script_name(environ))
        signals.request_started.send(sender=self.__class__)
        try:
            response = self.get_response(request)

            if not response :
                return 

            # Apply response middleware
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        finally:
            signals.request_finished.send(sender=self.__class__)

        try:
            status_text = STATUS_CODE_TEXT[response.status_code]
        except KeyError:
            status_text = 'UNKNOWN STATUS CODE'
        status = '%s %s' % (response.status_code, status_text)

        self.set_status(response.status_code)
        for h in response.items() :
            self.set_header(h[0], h[1])

        if not hasattr(self, "_new_cookies"):
            self._new_cookies = []
        self._new_cookies.append(response.cookies)

        self.write(response.content)
        self.finish()

    def post(self) :
        self.get()
    #
    #
    #
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django import http
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        return response

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        return response

                from ...decorator import TornadoAsyncException

                try:
                    response = callback(request, *callback_args, **callback_kwargs)
                except TornadoAsyncException, e:
                    #
                    #  Running under Tornado, so a null return is ok... means that the 
                    #   data is not finished
                    #
                    return
                except Exception, e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            return response
                    raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__' # If it's a class
                    raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))

                return response
            except http.Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        return callback(request, **param_dict)
                    except:
                        try:
                            return self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
Example #48
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        # Reset the urlconf for this thread.
        urlresolvers.set_urlconf(None)

        # Apply request middleware
        for middleware_method in self._request_middleware:
            response = middleware_method(request)
            if response:
                return response

        # Get urlconf from request object, if available.  Otherwise use default.
        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)

        # Set the urlconf for this thread to the one specified above.
        urlresolvers.set_urlconf(urlconf)

        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            try:
                callback, callback_args, callback_kwargs = resolver.resolve(
                        request.path_info)

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        return response

                try:
                    response = callback(request, *callback_args, **callback_kwargs)
                except Exception, e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            return response
                    raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__' # If it's a class
                    raise ValueError, "The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name)

                return response
            except http.Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        return callback(request, **param_dict)
                    except:
                        try:
                            return self.handle_uncaught_exception(request, resolver, sys.exc_info())
                        finally:
                            receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
Example #49
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"

        # Setup default url resolver for this thread, this code is outside
        # the try/except so we don't get a spurious "unbound local
        # variable" exception in the event an exception is raised before
        # resolver is set
        urlconf = settings.ROOT_URLCONF
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
        try:
            response = None
            # Apply request middleware
            for middleware_method in self._request_middleware:
                response = middleware_method(request)
                if response:
                    break

            if response is None:
                if hasattr(request, 'urlconf'):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                resolver_match = resolver.resolve(request.path_info)
                callback, callback_args, callback_kwargs = resolver_match
                request.resolver_match = resolver_match

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        break

            if response is None:
                wrapped_callback = self.make_view_atomic(callback)
                try:
                    response = wrapped_callback(request, *callback_args, **callback_kwargs)
                except Exception as e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            break
                    if response is None:
                        raise

            # Complain if the view returned None (a common error).
            if response is None:
                if isinstance(callback, types.FunctionType):    # FBV
                    view_name = callback.__name__
                else:                                           # CBV
                    view_name = callback.__class__.__name__ + '.__call__'
                raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))

            # If the response supports deferred rendering, apply template
            # response middleware and then render the response
            if hasattr(response, 'render') and callable(response.render):
                for middleware_method in self._template_response_middleware:
                    response = middleware_method(request, response)
                response = response.render()

        except http.Http404 as e:
            logger.warning('Not Found: %s', request.path,
                        extra={
                            'status_code': 404,
                            'request': request
                        })
            if settings.DEBUG:
                response = debug.technical_404_response(request, e)
            else:
                try:
                    callback, param_dict = resolver.resolve404()
                    response = callback(request, **param_dict)
                except:
                    signals.got_request_exception.send(sender=self.__class__, request=request)
                    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        except PermissionDenied:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                })
            try:
                callback, param_dict = resolver.resolve403()
                response = callback(request, **param_dict)
            except:
                signals.got_request_exception.send(
                        sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request,
                        resolver, sys.exc_info())

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except: # Handle everything else, including SuspiciousOperation, etc.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except: # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        return response
Example #50
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django import http
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                response = None

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                ### ADDED BY ZULIP
                request._resolver = resolver
                ### END ADDED BY ZULIP

                callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)

                # Apply view middleware
                if response is None:
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback,
                                                     callback_args,
                                                     callback_kwargs)
                        if response:
                            break

                ### THIS BLOCK MODIFIED BY ZULIP
                if response is None:
                    from ...decorator import RespondAsynchronously

                    try:
                        response = callback(request, *callback_args,
                                            **callback_kwargs)
                        if response is RespondAsynchronously:
                            async_request_stop(request)
                            return
                    except Exception, e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                if response is None:
                    try:
                        view_name = callback.func_name
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s returned None." %
                                     (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        try:
                            response = self.handle_uncaught_exception(
                                request, resolver, sys.exc_info())
                        finally:
                            signals.got_request_exception.send(
                                sender=self.__class__, request=request)
Example #51
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        根据请求, 得到响应

        try:
            为该线程提供默认的 url 处理器
            # Setup default url resolver for this thread, this code is outside
            # the try/except so we don't get a spurious "unbound local
            # variable" exception in the event an exception is raised before
            # resolver is set

            #ROOT_URLCONF = 'tomato.urls'
            urlconf = settings.ROOT_URLCONF

            urlresolvers.set_urlconf(urlconf) 出现了
            resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

            try:
                response = None
                # Apply request middleware 调用请求中间件
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        break

                # 如果没有结果, 尝试 request 中是否有 urlconf, 不懂
                if response is None:
                    if hasattr(request, 'urlconf'):
                        # Reset url resolver with a custom urlconf. 自定义的 urlconf
                        urlconf = request.urlconf
                        urlresolvers.set_urlconf(urlconf)
                        resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                    resolver_match = resolver.resolve(request.path_info) # 返回 ResolverMatch 实例
                    callback, callback_args, callback_kwargs = resolver_match
                    request.resolver_match = resolver_match

                    # Apply view middleware 调用视图中间件
                    for middleware_method in self._view_middleware:
                        response = middleware_method(request, callback, callback_args, callback_kwargs)
                        if response:
                            break

                if response is None:
                    try:
                        # 这里调用的是真正的处理函数, 我们一般在 view.py 中定义这些函数
                        response = callback(request, *callback_args, **callback_kwargs)
                    except Exception as e:
                        # If the view raised an exception, run it through exception
                        # middleware, and if the exception middleware returns a
                        # response, use that. Otherwise, reraise the exception.

                        # 调用异常中间件
                        for middleware_method in self._exception_middleware:
                            response = middleware_method(request, e)
                            if response:
                                break
                        if response is None:
                            raise

                如果还是返回空
                # Complain if the view returned None (a common error).
                if response is None:
                    if isinstance(callback, types.FunctionType):    # FBV
                        view_name = callback.__name__
                    else:                                           # CBV
                        view_name = callback.__class__.__name__ + '.__call__'
                    raise ValueError("The view %s.%s didn't return an HttpResponse object." % (callback.__module__, view_name))

                # If the response supports deferred rendering, apply template
                # response middleware and the render the response 如果 response 实现了 render, 那么渲染返回
                if hasattr(response, 'render') and callable(response.render):
                    for middleware_method in self._template_response_middleware:
                        response = middleware_method(request, response)
                    response = response.render()

            except http.Http404 as e:
                logger.warning('Not Found: %s', request.path,
                            extra={
                                'status_code': 404,
                                'request': request
                            })

                # 如果是调试下, 直接要返回 404 页面
                if settings.DEBUG:
                    response = debug.technical_404_response(request, e)
                else:
                    try:
                        # 非调试模式下, 获取 url 处理器的默认 404 处理
                        callback, param_dict = resolver.resolve404()
                        response = callback(request, **param_dict)
                    except:
                        signals.got_request_exception.send(sender=self.__class__, request=request)
                        response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

            # 访问拒绝
            except exceptions.PermissionDenied:
                logger.warning(
                    'Forbidden (Permission denied): %s', request.path,
                    extra={
                        'status_code': 403,
                        'request': request
                    })
                try:
                    callback, param_dict = resolver.resolve403()
                    response = callback(request, **param_dict)
                except:
                    signals.got_request_exception.send(
                            sender=self.__class__, request=request)
                    response = self.handle_uncaught_exception(request,
                            resolver, sys.exc_info())

            except SystemExit:
                # Allow sys.exit() to actually exit. See tickets #1023 and #4701
                raise

            except: # Handle everything else, including SuspiciousOperation, etc.
                # Get the exception info now, in case another exception is thrown later.
                signals.got_request_exception.send(sender=self.__class__, request=request)
                response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
        finally:
            # Reset URLconf for this thread on the way out for complete
            # isolation of request.urlconf 重置, 因为前面有两种 url resolver 的可能
            urlresolvers.set_urlconf(None)

        try:
            # Apply response middleware, regardless of the response 调用响应中间件
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
            response = self.apply_response_fixes(request, response)
        except: # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        return response
Example #52
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"
        from django.core import exceptions, urlresolvers
        from django.conf import settings

        try:
            try:
                # Setup default url resolver for this thread.
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                # Apply request middleware
                for middleware_method in self._request_middleware:
                    response = middleware_method(request)
                    if response:
                        return response

                if hasattr(request, "urlconf"):
                    # Reset url resolver with a custom urlconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)

                callback, callback_args, callback_kwargs = resolver.resolve(
                    request.path_info)

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback,
                                                 callback_args,
                                                 callback_kwargs)
                    if response:
                        return response

                try:
                    response = callback(request, *callback_args,
                                        **callback_kwargs)
                except Exception, e:
                    # If the view raised an exception, run it through exception
                    # middleware, and if the exception middleware returns a
                    # response, use that. Otherwise, reraise the exception.
                    for middleware_method in self._exception_middleware:
                        response = middleware_method(request, e)
                        if response:
                            return response
                    raise

                # Complain if the view returned None (a common error).
                if response is None:
                    try:
                        view_name = callback.func_name  # If it's a function
                    except AttributeError:
                        view_name = callback.__class__.__name__ + '.__call__'  # If it's a class
                    raise ValueError(
                        "The view %s.%s didn't return an HttpResponse object."
                        % (callback.__module__, view_name))

                return response
            except http.Http404, e:
                if settings.DEBUG:
                    from django.views import debug
                    return debug.technical_404_response(request, e)
                else:
                    try:
                        callback, param_dict = resolver.resolve404()
                        return callback(request, **param_dict)
                    except:
                        try:
                            return self.handle_uncaught_exception(
                                request, resolver, sys.exc_info())
                        finally:
                            receivers = signals.got_request_exception.send(
                                sender=self.__class__, request=request)
Example #53
0
        def get_response(self, request):
            try:
                urlconf = settings.ROOT_URLCONF
                urlresolvers.set_urlconf(urlconf)
                resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
                try:
                    response = None
                    for middleware_method in self._request_middleware:
                        response = middleware_method(request)
                        if response:
                            break

                    if response is None:
                        if hasattr(request, 'urlconf'):
                            urlconf = request.urlconf
                            urlresolvers.set_urlconf(urlconf)
                            resolver = urlresolvers.RegexURLResolver(
                                r'^/', urlconf)

                        resolver_match = resolver.resolve(request.path_info)
                        callback, callback_args, callback_kwargs = resolver_match
                        request.resolver_match = resolver_match

                        for middleware_method in self._view_middleware:
                            response = middleware_method(
                                request, callback, callback_args,
                                callback_kwargs)
                            if response:
                                break

                    if response is None:
                        try:
                            response = yield Chain([
                                lambda: callback(request, *callback_args, **
                                                 callback_kwargs)
                            ])
                        except Exception as e:
                            for middleware_method in self._exception_middleware:
                                response = middleware_method(request, e)
                                if response:
                                    break
                            if response is None:
                                raise

                    if response is None:
                        if isinstance(callback, types.FunctionType):  # FBV
                            view_name = callback.__name__
                        else:  # CBV
                            view_name = callback.__class__.__name__ + '.__call__'
                        raise ValueError(
                            "The view %s.%s didn't return an HttpResponse object."
                            % (callback.__module__, view_name))
                    if hasattr(response, 'render') and callable(
                            response.render):
                        for middleware_method in self._template_response_middleware:
                            response = middleware_method(request, response)
                        response = response.render()

                except http.Http404 as e:
                    log.warning('Not Found: %s',
                                request.path,
                                extra={
                                    'status_code': 404,
                                    'request': request
                                })
                    if settings.DEBUG:
                        response = debug.technical_404_response(request, e)
                    else:
                        try:
                            callback, param_dict = resolver.resolve404()
                            response = callback(request, **param_dict)
                        except:
                            signals.got_request_exception.send(
                                sender=self.__class__, request=request)
                            response = self.handle_uncaught_exception(
                                request, resolver, sys.exc_info())
                except exceptions.PermissionDenied:
                    log.warning('Forbidden (Permission denied): %s',
                                request.path,
                                extra={
                                    'status_code': 403,
                                    'request': request
                                })
                    try:
                        callback, param_dict = resolver.resolve403()
                        response = callback(request, **param_dict)
                    except:
                        signals.got_request_exception.send(
                            sender=self.__class__, request=request)
                        response = self.handle_uncaught_exception(
                            request, resolver, sys.exc_info())
                except SystemExit:
                    raise
                except:
                    signals.got_request_exception.send(sender=self.__class__,
                                                       request=request)
                    response = self.handle_uncaught_exception(
                        request, resolver, sys.exc_info())
            finally:
                urlresolvers.set_urlconf(None)

            try:
                for middleware_method in self._response_middleware:
                    response = middleware_method(request, response)
                response = self.apply_response_fixes(request, response)
            except:
                signals.got_request_exception.send(sender=self.__class__,
                                                   request=request)
                response = self.handle_uncaught_exception(
                    request, resolver, sys.exc_info())

            yield response
Example #54
0
    def get_response(self, request):
        "Returns an HttpResponse object for the given HttpRequest"

        # Setup default url resolver for this thread, this code is outside
        # the try/except so we don't get a spurious "unbound local
        # variable" exception in the event an exception is raised before
        # resolver is set
        urlconf = settings.ROOT_URLCONF
        urlresolvers.set_urlconf(urlconf)
        resolver = urlresolvers.get_resolver(urlconf)
        # Use a flag to check if the response was rendered to prevent
        # multiple renderings or to force rendering if necessary.
        response_is_rendered = False
        try:
            response = None
            # Apply request middleware
            for middleware_method in self._request_middleware:
                response = middleware_method(request)
                if response:
                    break

            if response is None:
                if hasattr(request, 'urlconf'):
                    # Reset url resolver with a custom URLconf.
                    urlconf = request.urlconf
                    urlresolvers.set_urlconf(urlconf)
                    resolver = urlresolvers.get_resolver(urlconf)

                resolver_match = resolver.resolve(request.path_info)
                callback, callback_args, callback_kwargs = resolver_match
                request.resolver_match = resolver_match

                # Apply view middleware
                for middleware_method in self._view_middleware:
                    response = middleware_method(request, callback, callback_args, callback_kwargs)
                    if response:
                        break

            if response is None:
                wrapped_callback = self.make_view_atomic(callback)
                try:
                    response = wrapped_callback(request, *callback_args, **callback_kwargs)
                except Exception as e:
                    response = self.process_exception_by_middleware(e, request)

            # Complain if the view returned None (a common error).
            if response is None:
                if isinstance(callback, types.FunctionType):    # FBV
                    view_name = callback.__name__
                else:                                           # CBV
                    view_name = callback.__class__.__name__ + '.__call__'
                raise ValueError("The view %s.%s didn't return an HttpResponse object. It returned None instead."
                                 % (callback.__module__, view_name))

            # If the response supports deferred rendering, apply template
            # response middleware and then render the response
            if hasattr(response, 'render') and callable(response.render):
                for middleware_method in self._template_response_middleware:
                    response = middleware_method(request, response)
                    # Complain if the template response middleware returned None (a common error).
                    if response is None:
                        raise ValueError(
                            "%s.process_template_response didn't return an "
                            "HttpResponse object. It returned None instead."
                            % (middleware_method.__self__.__class__.__name__))
                try:
                    response = response.render()
                except Exception as e:
                    response = self.process_exception_by_middleware(e, request)

                response_is_rendered = True

        except http.Http404 as exc:
            logger.warning('Not Found: %s', request.path,
                        extra={
                            'status_code': 404,
                            'request': request
                        })
            if settings.DEBUG:
                response = debug.technical_404_response(request, exc)
            else:
                response = self.get_exception_response(request, resolver, 404, exc)

        except PermissionDenied as exc:
            logger.warning(
                'Forbidden (Permission denied): %s', request.path,
                extra={
                    'status_code': 403,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 403, exc)

        except MultiPartParserError as exc:
            logger.warning(
                'Bad request (Unable to parse request body): %s', request.path,
                extra={
                    'status_code': 400,
                    'request': request
                })
            response = self.get_exception_response(request, resolver, 400, exc)

        except SuspiciousOperation as exc:
            # The request logger receives events for any problematic request
            # The security logger receives events for all SuspiciousOperations
            security_logger = logging.getLogger('django.security.%s' %
                            exc.__class__.__name__)
            security_logger.error(
                force_text(exc),
                extra={
                    'status_code': 400,
                    'request': request
                })
            if settings.DEBUG:
                return debug.technical_500_response(request, *sys.exc_info(), status_code=400)

            response = self.get_exception_response(request, resolver, 400, exc)

        except SystemExit:
            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
            raise

        except Exception:  # Handle everything else.
            # Get the exception info now, in case another exception is thrown later.
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        try:
            # Apply response middleware, regardless of the response
            for middleware_method in self._response_middleware:
                response = middleware_method(request, response)
                # Complain if the response middleware returned None (a common error).
                if response is None:
                    raise ValueError(
                        "%s.process_response didn't return an "
                        "HttpResponse object. It returned None instead."
                        % (middleware_method.__self__.__class__.__name__))
            response = self.apply_response_fixes(request, response)
        except Exception:  # Any exception should be gathered and handled
            signals.got_request_exception.send(sender=self.__class__, request=request)
            response = self.handle_uncaught_exception(request, resolver, sys.exc_info())

        response._closable_objects.append(request)

        # If the exception handler returns a TemplateResponse that has not
        # been rendered, force it to be rendered.
        if not response_is_rendered and callable(getattr(response, 'render', None)):
            response = response.render()

        return response
Example #55
0
 def f(request, *args, **kwargs):
     if not test():
         return technical_404_response(request, Http404(message))
     return func(request, *args, **kwargs)
Example #56
0
def response_for_exception(request, exc):
    if isinstance(exc, Http404):
        if settings.DEBUG:
            response = debug.technical_404_response(request, exc)
        else:
            response = get_exception_response(request,
                                              get_resolver(get_urlconf()), 404,
                                              exc)

    elif isinstance(exc, PermissionDenied):
        response = get_exception_response(request, get_resolver(get_urlconf()),
                                          403, exc)
        log_response(
            "Forbidden (Permission denied): %s",
            request.path,
            response=response,
            request=request,
            exception=exc,
        )

    elif isinstance(exc, MultiPartParserError):
        response = get_exception_response(request, get_resolver(get_urlconf()),
                                          400, exc)
        log_response(
            "Bad request (Unable to parse request body): %s",
            request.path,
            response=response,
            request=request,
            exception=exc,
        )

    elif isinstance(exc, BadRequest):
        if settings.DEBUG:
            response = debug.technical_500_response(request,
                                                    *sys.exc_info(),
                                                    status_code=400)
        else:
            response = get_exception_response(request,
                                              get_resolver(get_urlconf()), 400,
                                              exc)
        log_response(
            "%s: %s",
            str(exc),
            request.path,
            response=response,
            request=request,
            exception=exc,
        )
    elif isinstance(exc, SuspiciousOperation):
        if isinstance(exc, (RequestDataTooBig, TooManyFieldsSent)):
            # POST data can't be accessed again, otherwise the original
            # exception would be raised.
            request._mark_post_parse_error()

        # The request logger receives events for any problematic request
        # The security logger receives events for all SuspiciousOperations
        security_logger = logging.getLogger("django.security.%s" %
                                            exc.__class__.__name__)
        security_logger.error(
            str(exc),
            exc_info=exc,
            extra={
                "status_code": 400,
                "request": request
            },
        )
        if settings.DEBUG:
            response = debug.technical_500_response(request,
                                                    *sys.exc_info(),
                                                    status_code=400)
        else:
            response = get_exception_response(request,
                                              get_resolver(get_urlconf()), 400,
                                              exc)

    else:
        signals.got_request_exception.send(sender=None, request=request)
        response = handle_uncaught_exception(request,
                                             get_resolver(get_urlconf()),
                                             sys.exc_info())
        log_response(
            "%s: %s",
            response.reason_phrase,
            request.path,
            response=response,
            request=request,
            exception=exc,
        )

    # Force a TemplateResponse to be rendered.
    if not getattr(response, "is_rendered", True) and callable(
            getattr(response, "render", None)):
        response = response.render()

    return response