Django 1.8 official document translation: 6-6-5 error report

Time:2021-2-24

Error report

When you run a public site, you should always shut it downDEBUGset up. This will make your server run faster and prevent malicious users from seeing some of the application details displayed by the error page.

However, running onDEBUGbyFalseIn this case, you don’t see the errors generated by your site – everyone can only see the public error page. You need to track errors on the deployed site, so you can configure Django to generate reports with error details.

Report mail

Server error

DEBUGbyFalseWhenever the code generates an unhandled exception and a server internal error (HTTP status code 500), Django will give theADMINSUsers in settings send mail. This will provide the administrator with timely notification of any errors.  ADMINSYou’ll get a description of the error, a complete Python traceback, as well as the HTTP request and the details that caused the error.

be careful

In order to send mail, Django needs some settings to tell it how to connect to the mail server. At least, you need to specifyEMAIL_HOST, may needEMAIL_HOST_USERandEMAIL_HOST_PASSWORD, although the other settings you need may also depend on the configuration of your mail server. For a complete list of email related settings, see_ Django settings document_

Django usually starts fromComplete tracebackTraceback frameEach local variable of, andHttpRequestOf_ Properties_

However, sometimes specific message types are too sensitive to track messages, such as the user’s password or credit card number. So Django provides a set of function decorators to help you control what you need in the production environment (i.eDEBUGbyFalseMessage filtered in the error report in:sensitive_variables()andsensitive_post_parameters()

sensitive_variables(_*variables_)[source]

If a function (view or regular callback) in your code uses local variables that may contain sensitive information, you may need to usesensitive_variablesDecorator to prevent error reports from containing the values of these variables.

from django.views.decorators.debug import sensitive_variables

@sensitive_variables('user', 'pw', 'cc')
def process_info(user):
    pw = user.pass_word
    cc = user.credit_card_number
    name = user.name
    ...

In the example above,user, pwandccThe value of the variable is hidden in the error report and an asterisk (< cite > 0) is used**< / cite >), thoughnameThe value of the variable is exposed.

To hide all local variables of a function in an error report in order, do notsensitive_variablesThe decorator provides any parameters:

@sensitive_variables()
def my_function():
    ...

When using multiple decorators

If you want to hide the variable is also a function parameter (for example, in the following example)user)And the decorated function has multiple decorators, you need to make sure that@sensitive_variablesAt the top of the decorator chain. This method also hides function parameters, although it is passed through other decorators:

@sensitive_variables('user', 'pw', 'cc')
@some_decorator
@another_decorator
def process_info(user):
    ...

sensitive_post_parameters(_*parameters_)[source]

If a view in your code receives a view that may have sensitive information withPost parametersOfHttpRequestObject that you may need to usesensitive_post_parametersDecorator to prevent error reports from containing the values of these parameters.

from django.views.decorators.debug import sensitive_post_parameters

@sensitive_post_parameters('pass_word', 'credit_card_number')
def record_user_profile(request):
    UserProfile.create(user=request.user,
                       password=request.POST['pass_word'],
                       credit_card=request.POST['credit_card_number'],
                       name=request.POST['name'])
    ...

In the example above,pass_wordandcredit_card_numberThe value of the post parameter is hidden in the error report and an asterisk (< cite > 0) is used**< / cite >), thoughnameThe value of the variable is exposed.

To hide all the post parameters of a request in order in the error report, do notsensitive_post_parametersThe decorator provides any parameters:

@sensitive_post_parameters()
def my_view(request):
    ...

All post parameters are filtered out in orderdjango.contrib.auth.viewsError reporting for views(login, password_reset_confirm, password_change, add_viewandauthInuser_change_password)To prevent the disclosure of sensitive information such as user passwords.

Custom error reporting

Allsensitive_variables()Andsensitive_post_parameters()Annotate the decorated function with the name of sensitive variable, and annotate the function with the name of post sensitive parameterHttpRequestObject so that sensitive information in the report can be filtered out later when an error occurs. Django’s default error packet filterdjango.views.debug.SafeExceptionReporterFilterWill complete the actual filtering operation.
When an error report is generated, the filter uses the decorator’s annotation to replace the corresponding value with an asterisk (< cite >)**</cite>) 。 If you want to override or customize this default property for your entire site, you need to define your own filter class andDEFAULT_EXCEPTION_REPORTER_FILTERSet to let Django use it.

DEFAULT_EXCEPTION_REPORTER_FILTER = 'path.to.your.CustomExceptionReporterFilter'

You may also be able to control in a more subtle way which filters are used in the provided view by settingHttpRequestOfexception_reporter_filterProperty.

def my_view(request):
    if request.user.is_authenticated():
        request.exception_reporter_filter = CustomExceptionReporterFilter()
    ...

Your custom filter class needs to inherit fromdjango.views.debug.SafeExceptionReporterFilter, and you may need to override the following methods:

_class _SafeExceptionReporterFilter[source]

SafeExceptionReporterFilter.`is_active`(_request_)[source]

If the filter operated in other methods has been activated, return toTrue. IfDEBUGbyFalse, usually the filter is active.

SafeExceptionReporterFilter.`get_request_repr`(_request_)

Returns the representation string of the request object, that is, the value that would be returned by repr(request), except it uses the filtered dictionary of POST parameters as determined by SafeExceptionReporterFilter.get_post_parameters().

SafeExceptionReporterFilter.`get_post_parameters`(_request_)[source]

Returns the filtered post parameter dictionary. Usually, the values of sensitive parameters are marked with an asterisk (< cite >)**< / cite >).

SafeExceptionReporterFilter.`get_traceback_frame_variables`(_request_, _tb_frame_)[source]

Returns the dictionary of the local variables of the provided traceback frame after filtering. Usually, the value of sensitive variable is marked with an asterisk (< cite >)**< / cite >).

See also

You can also write custom_exception middleware_To create a custom error report. If you write a custom error handler to simulate Django’s built-in error handler, onlyDEBUGbyFalseIt’s a good idea to report or record errors when you do.

translator:Django document collaborative translation teamOriginal text:Tracking code errors by email

This paper is based onCC BY-NC-SA 3.0Please keep the author’s signature and the source of the article.

Django document collaborative translation teamWe are short of staff. Interested friends can join us. It is totally public welfare. Communication group: 467338606.