Esempio n. 1
0
 def process_exception(self, request, exception):
     if not settings.DEBUG or MONKEY_FORCE_ACTIVE:
         exc_info = sys.exc_info()
         if exc_info:
             response = technical_500_response(request, *exc_info)
         else:
             response = technical_500_response(request, type(exception), exception, None)
         self.patch_response(request, response)
         return response
Esempio n. 2
0
def django_error_page_response(request, error=None):
    ''' Return a response with Django's error page.

        If settings.DEBUG is True, Django automatically shows a useful
        error page for exceptions in views. But sometimes an exception
        isn't propogated out of the view, such as when the exception
        occurs in a separate thread. This shows the Django error page
        for any exception.

        If error is not present or is None, returns an error page for the
        last exception.

        Example:
            error = None
            ...
            # in separate thread
            error = sys.exc_info()
            ...
            # in parent thread
            show_django_error_page(error)
        '''

    from django.views.debug import technical_500_response
    # error should be sys.exc_info() from an earlier except block
    if not error:
        error = sys.exc_info()
    exc_type, exc_value, tb = error
    response = technical_500_response(request, exc_type, exc_value, tb)
Esempio n. 3
0
    def handle_uncaught_exception(self, request, resolver, exc_info):
        """
        处理未能捕捉的错误

        Processing for any otherwise uncaught exceptions (those that will
        generate HTTP 500 responses). Can be overridden by subclasses who want
        customised 500 handling. 子类中可以重写 500 状态的处理

        Be *very* careful when overriding this because the error could be
        caused by anything, so assuming something like the database is always
        available would be an error.
        """
        if settings.DEBUG_PROPAGATE_EXCEPTIONS:
            raise

        logger.error('Internal Server Error: %s', request.path,
            exc_info=exc_info,
            extra={
                'status_code': 500,
                'request': request
            }
        )

        调试模式特殊处理
        if settings.DEBUG:
            return debug.technical_500_response(request, *exc_info)

        # If Http500 handler is not installed, re-raise last exception 如果http500 处理器都没有安装, 可能会崩溃
        if resolver.urlconf_module is None:
            six.reraise(*exc_info)

        # Return an HttpResponse that displays a friendly error message.
        #这是自定义的 500 处理器
        callback, param_dict = resolver.resolve500()
        return callback(request, **param_dict)
Esempio n. 4
0
def server_error(request, *args, **kwargs):
    debugkey = request.REQUEST.get('debugkey')
    if debugkey and debugkey == getattr(settings, 'DEBUGKEY', None):
        import sys
        from django.views import debug
        return debug.technical_500_response(request, *sys.exc_info())
    return HttpResponseServerError(render_to_string(request, '500.html'))
def test_technical_500_response_empty(settings, mock_api_response_empty, mocker, rf, capsys):
    settings.DEBUG = True
    test_data_url = 'http://www.fixmydjango.com/test-server'
    submission_url = 'http://www.fixmydjango.com/test-server/draft/create/'

    try:
        raise ValueError("test")
    except:
        exc_info = sys.exc_info()

    def clean_traceback(tb):
        # remove \r
        tb = tb.replace('\r', '')
        # remove empty lines
        tb_lines = [line for line in tb.split('\n')
                    if line.strip()]
        return '\n'.join(tb_lines)
    mocker.patch('fixmydjango.is_django_exception', return_value=True)
    mocker.patch('fixmydjango.clean_traceback', side_effect=clean_traceback)
    mocker.patch('fixmydjango.sanitize_traceback', side_effect=lambda x: x)
    mocker.patch(
        'fixmydjango.ExceptionReporterPatch._get_fix_my_django_submission_url',
        return_value=submission_url)

    request = rf.get(reverse('test-error'))
    response = technical_500_response(request, *exc_info)

    assert response.status_code == 500

    out, err = capsys.readouterr()
    assert out == colored(FIX_MY_DJANGO_MESSAGE_TO_ADMIN_PLAIN.format(submission_url=submission_url), 'yellow') + '\n'
Esempio n. 6
0
    def server_error(self, request, exception = None, *args, **kwargs):
        """
        Graceful degradation, last resort.

        usage:
            server_error(request, [ exception = None])
        """
        try:
            import logging
            logging.exception('server error')
        except:
            pass

        try: # render default 500 response
            from django.conf import settings
            debugkey = request.REQUEST.get('debugkey')
            DEBUG = getattr(settings, 'DEBUG')

            if DEBUG or (debugkey and debugkey == getattr(settings, 'DEBUGKEY')):
                import sys
                from django.views import debug
                return debug.technical_500_response(request, *sys.exc_info())
        except:
            pass

        try: # try coustom response
            if exception:
                request.response = self._exception_str(exception)
            return self._fetch_page(request, 500)
        except:
            pass
Esempio n. 7
0
    def handle_uncaught_exception(self, request, resolver, exc_info):
        """
        Processing for any otherwise uncaught exceptions (those that will
        generate HTTP 500 responses). Can be overridden by subclasses who want
        customised 500 handling.

        Be *very* careful when overriding this because the error could be
        caused by anything, so assuming something like the database is always
        available would be an error.
        """
        from django.conf import settings

        if settings.DEBUG_PROPAGATE_EXCEPTIONS:
            raise

        print exc_info

        logger.error('Internal Server Error: %s', request.path,
            exc_info=exc_info,
            extra={
                'status_code': 500,
                'request': request
            }
        )

        
        from django.views import debug
        return debug.technical_500_response(request, *exc_info) 
Esempio n. 8
0
 def process_exception(self, request, exception):
     try:
         user = request.user
     except:
         user = None
     if user and user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 9
0
def sensitive_kwargs_function_caller(request):
    try:
        sensitive_kwargs_function(''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e']))
    except Exception:
        exc_info = sys.exc_info()
        send_log(request, exc_info)
        return technical_500_response(request, *exc_info)
Esempio n. 10
0
def raises_template_does_not_exist(request):
    # We need to inspect the HTML generated by the fancy 500 debug view but
    # the test client ignores it, so we send it explicitly.
    try:
        return render_to_response('i_dont_exist.html')
    except TemplateDoesNotExist:
        return technical_500_response(request, *sys.exc_info())
Esempio n. 11
0
def raises500(request):
    # We need to inspect the HTML generated by the fancy 500 debug view but
    # the test client ignores it, so we send it explicitly.
    try:
        raise Exception
    except Exception:
        return technical_500_response(request, *sys.exc_info())
Esempio n. 12
0
    def handle_uncaught_exception(self, request, resolver, exc_info):
        """
        Processing for any otherwise uncaught exceptions (those that will
        generate HTTP 500 responses). Can be overridden by subclasses who want
        customised 500 handling.

        Be *very* careful when overriding this because the error could be
        caused by anything, so assuming something like the database is always
        available would be an error.
        """
        from django.conf import settings

        if settings.DEBUG_PROPAGATE_EXCEPTIONS:
            raise

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

        logger.error('Internal Server Error: %s' % request.path,
            exc_info=exc_info,
            extra={
                'status_code': 500,
                'request':request
            }
        )

        # If Http500 handler is not installed, re-raise last exception
        if resolver.urlconf_module is None:
            raise exc_info[1], None, exc_info[2]
        # Return an HttpResponse that displays a friendly error message.
        callback, param_dict = resolver.resolve500()
        return callback(request, **param_dict)
Esempio n. 13
0
def email_admin_last_exception(request):
    """
    Email admin about the exception just caught. It's useful when we need to
    catch an exception nicely but still want to send admin an email about it.
    Email code were taken from django.core.handlers.base.BaseHandler.
    handle_uncaught_exception.

    Usage example (normally in a view):
                try:
                     raise ValueError
                except ValueError:
                     email_admin_last_exception(request)
                     return <some nicer response>
    """
    import sys
    from django.core.mail import mail_admins

    exc_info = sys.exc_info()

    if settings.DEBUG_PROPAGATE_EXCEPTIONS:
        raise

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

    # When DEBUG is False, send an error message to the admins.
    subject = 'Error (%s IP): %s' % ((request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS and 'internal' or 'EXTERNAL'), request.path)
    try:
        request_repr = repr(request)
    except:
        request_repr = "Request repr() unavailable"

    message = "%s\n\n%s" % (_get_traceback(exc_info), request_repr)
    mail_admins(subject, message, fail_silently=True)
Esempio n. 14
0
def server_error(request, *args, **kwargs):
    # Save exc info before next exception occurs
    exc_info = sys.exc_info()
    crash_reporting = logger.CrashReporting(transport='threaded')
    try:
        tb = Advanced.objects.all().latest('id').adv_traceback
    except:
        tb = True

    # Crash reporting
    extra_log_files = [
        ('/var/log/debug.log', 'debug_log'),
        ('/data/update.failed', 'update_failed'),
    ]
    # If the exception comes from middleware client lets append the log
    # since middlewared itself might be stuck
    if issubclass(exc_info[0], (ClientException, socket.timeout)):
        extra_log_files.insert(0, ('/var/log/middlewared.log', 'middlewared_log'))

    log.debug('UI crash exception', exc_info=exc_info)
    crash_reporting.report(exc_info, request2crashreporting(request), extra_log_files)

    try:
        if tb:
            reporter = ExceptionReporter(request, *exc_info)
            html = reporter.get_traceback_html()
            return HttpResponse(html, content_type='text/html')
        else:
            raise
    except Exception:
        return debug.technical_500_response(request, *exc_info)
Esempio n. 15
0
    def handle_uncaught_exception(self, request, exc_info):
        """
        Processing for any otherwise uncaught exceptions (those that will
        generate HTTP 500 responses). Can be overridden by subclasses who want
        customised 500 handling.

        Be *very* careful when overriding this because the error could be
        caused by anything, so assuming something like the database is always
        available would be an error.
        """
        from django.core.mail import mail_admins

        if self.propagate_exceptions:
            raise

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

        # When DEBUG is False, send an error message to the admins.
        subject = 'Error: %s' % request.path
        try:
            request_repr = repr(request)
        except:
            request_repr = "Request repr() unavailable"
        message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
        mail_admins(subject, message, fail_silently=True)
        # Return an HttpResponse that displays a friendly error message.
        return self.handle_500(request, exc_info)
Esempio n. 16
0
    def handle_uncaught_exception(self, request, resolver, exc_info):
        """
        Processing for any otherwise uncaught exceptions (those that will
        generate HTTP 500 responses). Can be overridden by subclasses who want
        customised 500 handling.

        Be *very* careful when overriding this because the error could be
        caused by anything, so assuming something like the database is always
        available would be an error.
        """
        from django.conf import settings
        from django.core.mail import mail_admins

        if settings.DEBUG_PROPAGATE_EXCEPTIONS:
            raise

        if settings.DEBUG:
            from django.views import debug

            return debug.technical_500_response(request, *exc_info)

        # When DEBUG is False, send an error message to the admins.
        subject = "Error (%s IP): %s" % (
            (request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS and "internal" or "EXTERNAL"),
            request.path,
        )
        try:
            request_repr = repr(request)
        except:
            request_repr = "Request repr() unavailable"
        message = "%s\n\n%s" % (self._get_traceback(exc_info), request_repr)
        mail_admins(subject, message, fail_silently=True)
        # Return an HttpResponse that displays a friendly error message.
        callback, param_dict = resolver.resolve500()
        return callback(request, **param_dict)
Esempio n. 17
0
def sensitive_kwargs_function_caller(request):
    try:
        sensitive_kwargs_function("".join(["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"]))
    except Exception:
        exc_info = sys.exc_info()
        send_log(request, exc_info)
        return technical_500_response(request, *exc_info)
Esempio n. 18
0
    def save_traceback_to_epoch_file(self, request, exc_info):
        try:
            resp = technical_500_response(request, *exc_info)

            if BETTER_500_LOG_DIR:
                epoch = int(time.mktime(datetime.datetime.now().timetuple()))
                epoch_file = "%s.html" % (epoch,)

                folder = os.path.join(BETTER_500_LOG_DIR, BETTER_500_UNCAUGHT_DIR)
                debug_log_file = os.path.join(folder, epoch_file)

                if not os.path.exists(folder):
                       os.makedirs(folder)

                try:
                    default_storage.save(debug_log_file, ContentFile(resp._container[0]))
                except:
                    f = open(debug_log_file,"a")
                    f.write(resp._container[0])
                    f.close()

                return epoch
        except:
            try:
                log = logging.getLogger("better500s")
                log.error(exception_string())
            except:
                pass
            pass
        return None
Esempio n. 19
0
def server_error_500(request, template_name='500.html'):
    """
    Custom 500 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')
    try:
        # --- Log to file ---
        # Log straight to file with Django's normal HTML formatted 500 output
        traceback_500 = debug.technical_500_response(request, *sys.exc_info())
        destFilename = "%s_%s_500.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_500.content)
        out_file.close()

        # --- Render to flat file ---
        # get our own custom technical 500 template to render a non-HTML
        # plain text version of the error output
        # Initialise Django's TECHNICAL_500_TEMPLATE to ours
        from main.httpd_errors import FLAT_500_TEMPLATE
        debug.TECHNICAL_500_TEMPLATE = FLAT_500_TEMPLATE
        traceback_500 = debug.technical_500_response(request, *sys.exc_info())
        destFilename = "%s_%s_500.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_500.content)
        out_file.close()

        # --- 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_500_TEMPLATE
        debug.TECHNICAL_500_TEMPLATE = TECHNICAL_500_TEMPLATE
        # Get the traceback formatted the way we want it for inclusion in the
        # web page we will render
        traceback_500 = debug.technical_500_response(request, *sys.exc_info())
        template = loader.get_template(template_name) # You need to create a 500.html template!
        c = Context({
                     'traceback': traceback_500.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))
Esempio n. 20
0
 def process_exception(self, request, exception):
     exc_info = sys.exc_info()
     user = request.user
     if not user.is_superuser:
         return None
     if user.groups.filter(name=EX_GROUP_NAME):
         return technical_500_response(request, *exc_info)
     return None
Esempio n. 21
0
def doc_reader(request, docname):
    try:
        doc = get_doc(docname)
    except Exception, e:
        # Always use the debug response, even if we aren't in DEBUG mode.
        import sys
        from django.views import debug
        return debug.technical_500_response(request, *sys.exc_info())
Esempio n. 22
0
File: views.py Progetto: ab/bcfg2
def server_error(request):
    """
    500 error handler.

    For now always return the debug response.  Mailing isn't appropriate here.

    """
    from django.views import debug
    return debug.technical_500_response(request, *sys.exc_info())
Esempio n. 23
0
def multivalue_dict_key_error(request):
    cooked_eggs = "".join(["s", "c", "r", "a", "m", "b", "l", "e", "d"])  # NOQA
    sauce = "".join(["w", "o", "r", "c", "e", "s", "t", "e", "r", "s", "h", "i", "r", "e"])  # NOQA
    try:
        request.POST["bar"]
    except Exception:
        exc_info = sys.exc_info()
        send_log(request, exc_info)
        return technical_500_response(request, *exc_info)
Esempio n. 24
0
 def handle_value_error(self, request, exception):
     exc_info = sys.exc_info()
     if settings.DEBUG:
         from django.views import debug
         return debug.technical_500_response(request, *exc_info)
     else:
         '''Return an HttpResponse that displays a friendly message.'''
         callback, param_dict = resolver(request).resolve500()
         return callback(request, **param_dict)
Esempio n. 25
0
def multivalue_dict_key_error(request):
    cooked_eggs = ''.join(['s', 'c', 'r', 'a', 'm', 'b', 'l', 'e', 'd'])  # NOQA
    sauce = ''.join(['w', 'o', 'r', 'c', 'e', 's', 't', 'e', 'r', 's', 'h', 'i', 'r', 'e'])  # NOQA
    try:
        request.POST['bar']
    except Exception:
        exc_info = sys.exc_info()
        send_log(request, exc_info)
        return technical_500_response(request, *exc_info)
Esempio n. 26
0
 def process_exception(self, request, exception):
     """Same as UserBasedExceptionMiddleware but works for all superusers but without
     need of creating groups, having cache etc.
     """
     if DEBUG:
         return None
     if request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
     return None
Esempio n. 27
0
def raises(request):
    # Make sure that a callable that raises an exception in the stack frame's
    # local vars won't hijack the technical 500 response (#15025).
    def callable():
        raise Exception
    try:
        raise Exception
    except Exception:
        return technical_500_response(request, *sys.exc_info())
Esempio n. 28
0
def handler_500(request):
    info = sys.exc_info()
    if request.settings.exists and request.settings.DEBUG:
        try:
            template = loader.get_template(request.settings.TEMPLATE_500)
            return HttpResponseServerError(template.render(RequestContext(request)))
        except:
            pass
    return debug.technical_500_response(request, *info)
Esempio n. 29
0
def server_error(request, template_name="errors/500.html"):
    """
    Mimics Django's error handler but adds ``STATIC_URL`` to the
    context.
    """
    if request.user.is_superuser or request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
        return technical_500_response(request, *sys.exc_info())
    context = RequestContext(request, {"STATIC_URL": settings.STATIC_URL})
    t = get_template(template_name)
    return HttpResponseServerError(t.render(context))
Esempio n. 30
0
def raises(request):
    # Make sure that a callable that raises an exception in the stack frame's
    # local vars won't hijack the technical 500 response. See:
    # http://code.djangoproject.com/ticket/15025
    def callable():
        raise Exception
    try:
        raise Exception
    except Exception:
        return technical_500_response(request, *sys.exc_info())
 def safe_process_response(self, request, response):
     try:
         return process_response(self, request, response)
     except Exception:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 32
0
    def process_exception(self, request, exception):
        sentry_exception_handler(request=request)

        if request.user.is_superuser:
            return technical_500_response(request, *sys.exc_info())
Esempio n. 33
0
    def _wrap_view_func(request, *args, **kwargs):
        is_ajax = True

        if hasattr(request, 'is_ajax'):
            if not request.is_ajax():
                is_ajax = False
        else:
            # for backward compatibility with Django pre 1.0
            if not (request.META.has_key('HTTP_ACCEPT') and
                    'application/javascript' in request.META['HTTP_ACCEPT']):
                is_ajax = False

        origin_resp = None

        #FIXME: require refactoring here
        if not is_ajax:
            # require direct call original function (out of try/except) to proper determine error exception
            # in orinical view
            origin_resp = view_func(request, *args, **kwargs)
            if isinstance(origin_resp, dict) or isinstance(origin_resp, list):
                return _json_dump(origin_resp)
            else:
                return origin_resp

        response_dict = {}
        response_dict['debug'] = False
        try:
            origin_resp = view_func(request, *args, **kwargs)

            if isinstance(origin_resp, dict) or isinstance(origin_resp, list):
                if isinstance(origin_resp, dict):
                    if 'status' not in origin_resp:
                        origin_resp['status'] = 200
                return _json_dump(origin_resp)

            if hasattr(
                    origin_resp, 'content_type'
            ) and origin_resp.content_type == 'application/javascript':
                return origin_resp

            response_dict['status'] = origin_resp.status_code
            response_dict['content'] = origin_resp.content

            # if isinstance(origin_resp, HttpResponseRedirect):
            #     response_dict['location'] = origin_resp['location']

        except Http404 as e:
            raise Http404(e)
        except Exception as e:
            response_dict['status'] = 500

            if settings.DEBUG:
                from django.views import debug
                rc = debug.technical_500_response(request, *sys.exc_info())
                response_dict['debug'] = True
                # rc.content #.replace('\n', '<br>\n')
                response_dict['debug_msg'] = ''
            else:
                from django.core.mail import mail_admins

                exc_info = sys.exc_info()

                subject = 'Error (%s IP): %s' % (
                    (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                     and 'internal' or 'EXTERNAL'), request.path)
                try:
                    request_repr = repr(request)
                except:
                    request_repr = "Request repr() unavailable"

                message = "%s\n\n%s" % (_get_traceback(exc_info), request_repr)
                mail_admins(subject, message, fail_silently=True)

        resp = HttpResponse(simplejson.dumps(response_dict,
                                             ensure_ascii=False),
                            content_type='application/javascript')
        _copy_x_headers(origin_resp, resp)

        return resp
Esempio n. 34
0
 def process_exception(self, request, exception):
     if request.user.is_superuser or getip(
             request) in django_settings.INTERNAL_IPS:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 35
0
 def process_exception(request: HttpRequest,
                       exception: Exception) -> HttpResponse:
     # noinspection PyUnresolvedReferences
     if request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 36
0
 def process_exception(self, request, exception):
     # 如果关闭debug模式,并且是管理员:可以看到错误页面,否则根据系统配置进行跳转。
     if settings.DEBUG is False and request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 37
0
def raises(request):
    try:
        raise Exception
    except Exception:
        return technical_500_response(request, *sys.exc_info())
Esempio n. 38
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
Esempio n. 39
0
 def process_exception(self, request, exception):
     if request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 40
0
 def debug_500_response(self, request, exception, exc_info):
     from django.views import debug
     return debug.technical_500_response(request, *exc_info)
Esempio n. 41
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,
            exc_info=sys.exc_info(),
        )

    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,
            exc_info=sys.exc_info(),
        )

    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),
            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())
        log_response(
            '%s: %s', response.reason_phrase, request.path,
            response=response,
            request=request,
            exc_info=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
Esempio n. 42
0
 def process_exception(self, request, exception):
     if request.user.is_superuser or request.META.get(
             'REMOTE_ADDR') in settings.INTERNAL_IPS:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 43
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
        set_urlconf(urlconf)
        resolver = 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
                    set_urlconf(urlconf)
                    resolver = 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
Esempio n. 44
0
        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:
                raise
            elif settings.DEBUG:
                from django.views import debug
                return debug.technical_500_response(request, *exc_info)
            else:
                # When DEBUG is False, send an error message to the admins.
                subject = 'Error (%s IP): %s' % (
                    (request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS
                     and 'internal' or 'EXTERNAL'), request.path)
                try:
                    request_repr = repr(request)
                except:
                    request_repr = "Request repr() unavailable"
                message = "%s\n\n%s" % (self._get_traceback(exc_info),
                                        request_repr)
                mail_admins(subject, message, fail_silently=True)
                # Return an HttpResponse that displays a friendly error message.
                callback, param_dict = resolver.resolve500()
                return callback(request, **param_dict)
Esempio n. 45
0
def handler500(request):
    return debug.technical_500_response(request, *sys.exc_info())
Esempio n. 46
0
 def process_exception(self, request, exception):
     print(request.META.get('REMOTE_ADDR'))
     # if request.user.is_superuser or request.META.get('REMOTE_ADDR') in settings.INTERNAL_IPS:
     if repr(request.META.get('REMOTE_ADDR')) == repr("127.0.0.1"):  # 允许的ip
         print("ahah")
         return technical_500_response(request, *sys.exc_info())
Esempio n. 47
0
 def process_exception(self, request, exception):
     # 对管理员展示错误页面,一般用户只能看到404 500等页面
     ip = request.META.get('REMOTE_ADDR')
     if ip == '127.0.0.1':
         return technical_500_response(request, *sys.exc_info())
     return redirect(reverse('App:errors'))
Esempio n. 48
0
def server_error_display(request):
    error_html = debug.technical_500_response(request, *sys.exc_info()).content
    return HttpResponseServerError(error_html)
Esempio n. 49
0
 def __call__(self, request):
     response = self.get_response(request)
     if request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
     return response
Esempio n. 50
0
 def process_exception(request: HttpRequest,
                       exception: Exception) -> HttpResponse:
     if request.user.is_superuser:
         return technical_500_response(request, *sys.exc_info())
Esempio n. 51
0
def my_customized_server_error(request, template_name='500.html'):
    import sys
    from django.views import debug
    error_html = debug.technical_500_response(request, *sys.exc_info()).content
    return HttpResponseServerError(error_html)
Esempio n. 52
0
 def process_exception(self, request, exception):
     ip = request.META.get('REMOTE_ADDR')
     if ip == '127.0.0.1':
         return technical_500_response(request, *sys.exc_info())
     return redirect(reverse('film:index'))
Esempio n. 53
0
 def _build_html_response(request: HttpRequest,
                          debug_info_enabled: bool) -> HttpResponse:
     if debug_info_enabled:
         return technical_500_response(request, *sys.exc_info())
     return server_error(request)