首先:您可能会find drf-tracking to be a useful project,但它将对每个请求的响应存储在数据库中,我们发现这有点疯狂。
我们为此开发的解决方案是一个从drf-tracking 大量借用的mixin,但它只记录统计信息。该解决方案使用我们的缓存服务器 (Redis),因此速度非常快。
如果您已经在使用 Redis,则非常简单:
class LoggingMixin(object):
"""Log requests to Redis
This draws inspiration from the code that can be found at: https://github.com/aschn/drf-tracking/blob/master/rest_framework_tracking/mixins.py
The big distinctions, however, are that this code uses Redis for greater
speed, and that it logs significantly less information.
We want to know:
- How many queries in last X days, total?
- How many queries ever, total?
- How many queries total made by user X?
- How many queries per day made by user X?
"""
def initial(self, request, *args, **kwargs):
super(LoggingMixin, self).initial(request, *args, **kwargs)
d = date.today().isoformat()
user = request.user
endpoint = request.resolver_match.url_name
r = redis.StrictRedis(
host=settings.REDIS_HOST,
port=settings.REDIS_PORT,
db=settings.REDIS_DATABASES['STATS'],
)
pipe = r.pipeline()
# Global and daily tallies for all URLs.
pipe.incr('api:v3.count')
pipe.incr('api:v3.d:%s.count' % d)
# Use a sorted set to store the user stats, with the score representing
# the number of queries the user made total or on a given day.
pipe.zincrby('api:v3.user.counts', user.pk)
pipe.zincrby('api:v3.user.d:%s.counts' % d, user.pk)
# Use a sorted set to store all the endpoints with score representing
# the number of queries the endpoint received total or on a given day.
pipe.zincrby('api:v3.endpoint.counts', endpoint)
pipe.zincrby('api:v3.endpoint.d:%s.counts' % d, endpoint)
pipe.execute()
把它放在你的项目中,然后将 mixin 添加到你的各种视图中,如下所示:
class ThingViewSet(LoggingMixin, viewsets.ModelViewSet):
# More stuff here.
关于课程的一些注意事项:
- 它使用 Redis 管道使所有 Redis 查询以一个请求而不是六个请求到达服务器。
- 它使用Sorted Sets 来跟踪您的 API 中哪些端点使用最多,以及哪些用户使用 API 最多。
- 它每天会在您的缓存中创建一些新的键——可能有更好的方法来做到这一点,但我找不到任何方法。
这应该是记录 API 的一个相当灵活的起点。