如何在django中间件中获取实例?

时间:2018-09-18 21:28:01

标签: python django

我想写一个访问保护程序。我的逻辑:我收到对中间件中特定视图的请求,并在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)

1 个答案:

答案 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)