我想写一个访问保护程序。我的逻辑:我收到对中间件中特定视图的请求,并在Redis中设置数据。如何获取视图实例?
我的模型。py
class HitPoint(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE)
ip = models.GenericIPAddressField('ip', protocol='both', unpack_ipv4=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.post)
还有我的自定义中间件:
class MultipleProxyMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
# PostDetail is CBV with slug.
if view_func.__name__ == PostDetail.__name__:
ip, is_routable = get_client_ip(request)
cache_name = f'post_{uuid.uuid4()}'
cache.set(cache_name, {
'ip': ip,
# HOW CAN I GET THE INSTANCE OF POST?
'post_id': ???,
'created': now(),
}, timeout=None)
答案 0 :(得分:0)
您可以从中间件的view_kwargs
方法的process_view
参数中获取 url参数。由此,您可以简单地进行查询以获取id
。我假设您的url
有一个名为slug
的参数,那么您可以执行以下操作:
class MultipleProxyMiddleware(MiddlewareMixin):
def process_view(self, request, view_func, view_args, view_kwargs):
# PostDetail is CBV with slug.
if view_func.__name__ == PostDetail.__name__:
ip, is_routable = get_client_ip(request)
cache_name = f'post_{uuid.uuid4()}'
post_id = Post.objects.get(slug=view_kwargs['slug']).id
cache.set(cache_name, {
'ip': ip,
'post_id': post_id,
'created': now(),
}, timeout=None)