Django:如何在urls.py中获取请求对象

时间:2017-10-19 18:12:42

标签: django

我无法弄清楚如何在urls.py文件中获取请求对象。

我尝试导入

from django.http.request import HttpRequest

但我被困在这里。 有人可以帮忙吗?

编辑回复评论:

我正在尝试设置一个新的缓存装饰器,以便清除缓存项目:

根据Mihajlo的回答: Expire a view-cache in Django?

def simple_cache_page(cache_timeout):
    """
    Decorator for views that tries getting the page from the cache and
    populates the cache if the page isn't in the cache yet.

    The cache is keyed by view name and arguments.
    """
    def _dec(func):
        def _new_func(*args, **kwargs):
            key = func.__name__
            if kwargs:
                key += ':' + request.LANGUAGE_CODE + ':'.join([kwargs[key] for key in kwargs])

            response = cache.get(key)
            if not response:
                response = func(*args, **kwargs)
                cache.set(key, response, cache_timeout)
                print "set key", key
            else:
                print "key exists", key
            return response
        return _new_func
    return _dec

我以为我会把这个功能放在urls.py中。也许这不是一个好主意?我需要构建密钥请求的语言代码。

1 个答案:

答案 0 :(得分:3)

_new_func方法中,请求当前是第一个参数args[0]

但是,如果您将签名更改为:

,我认为会更容易阅读
def _new_func(request, *args, **kwargs):

并将函数调用更改为

response = func(request, *args, **kwargs)