【发布时间】: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