【问题标题】:How can I reference a user globally in Django for all Exceptions?如何在 Django 中全局引用用户的所有异常?
【发布时间】:2020-03-26 18:08:33
【问题描述】:

我有两个相关的问题。

1) django-rest-framework 是否有办法在全局范围内引用用户?

2) django / python 是否允许我更改通用异常类以在每次抛出时将此用户 ID 作为元数据包含在内?

我知道我可以创建自定义异常类并在代码中引发它们,但是我没有正确处理的异常怎么办?例如,假设抛出除以零异常但我没有正确处理它,现在我的日志只是说“除以零异常”。 有没有办法全局更新这个,所以如果用户登录它会说“除以零异常 user_id {id}”?

class SomeExternalApiHelper:
    @staticmethod
    def do_api_call():
        url = 'https://example.com'
        # do api request
        try:
            home_value = 100 / 0
        except Exception as e:
            # Exception occurs here, I want to be able to reference user_id, without having
            # to pass the user_object all the way down into this call
            raise Exception("Something went wrong for user ID {0}".format(user_id))


class AddNewHouse(APIView):
    def post(self, request, format=None):
        # I can call request.user here and access the user object
        SomeExternalApiHelper.do_api_call()


【问题讨论】:

    标签: python django exception django-rest-framework


    【解决方案1】:

    您可以创建一个捕获所有异常的custom middleware,然后您可以将异常与用户一起记录

    def exception_middleware(get_response):
    
        def middleware(request):
            try:
                response = get_response(request)
            except Exception as e:
                # You now have the exception and request.user and can log how you like
                raise
        return response
    
    return middleware
    

    【讨论】:

    • 正是我想要的!谢谢
    猜你喜欢
    • 2015-04-07
    • 2022-07-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2019-02-05
    • 2020-06-11
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多