gpt4 book ai didi

django - 在 django Traceback 错误中包含 django 登录用户

转载 作者:行者123 更新时间:2023-12-02 04:03:49 25 4
gpt4 key购买 nike

在 django Traceback 错误中包含用户名、名字和姓氏以及电子邮件的最简单方法是什么。

我知道方法是create a custom error report :

  1. 创建一个继承自 django.views.debug.SafeExceptionReporterFilter 的新类
  2. 设置DEFAULT_EXCEPTION_REPORTER_FILTER

但是,应该重写什么方法来接收包含此信息的回溯?

我希望我的三背看起来像:

Traceback (most recent call last):

File "/usr...o/core/handlers/base.py", line 89, in get_response
response = middleware_method(request)

File "/.../g...ap/utils/middleware.py", line 23,...
if elapsedTime.min > 15:

TypeError: can't compare datetime.timedelta to int

Logged user information:
User: pepito
name: Pepito Grillo
e-mail: grillo@peppeto.com

最佳答案

我使用自定义中间件完成了它。我不确定这是最好的答案,但这就是我为我的项目解决这个问题的方法。

设置.py:

MIDDLEWARE_CLASSES = (
...
'utilities.custom_middleware.CustomMiddleware',
...
)

实用程序/custom_middleware.py:

from utilities.request import AddRequestDetails

class CustomMiddleware(object):
"""
Adds user details to request context during request processing, so that they
show up in the error emails. Add to settings.MIDDLEWARE_CLASSES and keep it
outermost(i.e. on top if possible). This allows it to catch exceptions in
other middlewares as well.
"""

def process_exception(self, request, exception):
"""
Process the request to add some variables to it.
"""

# Add other details about the user to the META CGI variables.
try:
if request.user.is_authenticated():
AddRequestDetails(request)
request.META['AUTH_VIEW_ARGS'] = str(view_args)
request.META['AUTH_VIEW_CALL'] = str(view_func)
request.META['AUTH_VIEW_KWARGS'] = str(view_kwargs)
except:
pass

实用程序/request.py:

def AddRequestDetails(request):
"""
Adds details about the user to the request, so any traceback will include the
details. Good for troubleshooting; this will be included in the email sent to admins
on error.
"""
if request.user.is_anonymous():
request.META['AUTH_NAME'] = "Anonymous User"
request.META['AUTH_USER'] = "Anonymous User"
request.META['AUTH_USER_EMAIL'] = ""
request.META['AUTH_USER_ID'] = 0
request.META['AUTH_USER_IS_ACTIVE'] = False
request.META['AUTH_USER_IS_SUPERUSER'] = False
request.META['AUTH_USER_IS_STAFF'] = False
request.META['AUTH_USER_LAST_LOGIN'] = ""
else:
request.META['AUTH_NAME'] = str(request.user.first_name) + " " + str(request.user.last_name)
request.META['AUTH_USER'] = str(request.user.username)
request.META['AUTH_USER_EMAIL'] = str(request.user.email)
request.META['AUTH_USER_ID'] = str(request.user.id)
request.META['AUTH_USER_IS_ACTIVE'] = str(request.user.is_active)
request.META['AUTH_USER_IS_SUPERUSER'] = str(request.user.is_superuser)
request.META['AUTH_USER_IS_STAFF'] = str(request.user.is_staff)
request.META['AUTH_USER_LAST_LOGIN'] = str(request.user.last_login)

关于django - 在 django Traceback 错误中包含 django 登录用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9294043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com