我使用 Django 创建了一个 REST Web 服务。此 Web 服务有一个日志文件。我想在日志文件中记录所有 Web 服务 (http) 请求。然而,Web 服务请求处理是由 Django 完成的,我只设置 url 请求处理程序映射并创建请求处理程序(Django 命名法中的 View )。有没有一种方法可以在一个中心点记录所有请求,而不需要在其关联的请求处理程序( View )中记录每个请求?
提前致谢。
最佳答案
是的,Django 有一个内置的 signals框架。
它允许您注册一个在每次请求开始时调用的函数。
This documenation页面解释了如何一步一步进行
使用装饰器方法:
from django.core.signals import request_started
from django.dispatch import receiver
@receiver(request_started)
def my_callback(sender, **kwargs):
# log the request here
pass
Where should this code live? You can put signal handling and registration code anywhere you like. However, you’ll need to make sure that the module it’s in gets imported early on so that the signal handling gets registered before any signals need to be sent. This makes your app’s models.py a good place to put registration of signal handlers.
关于django - 在 Django 中记录 Web 服务请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15026270/