2017-10-19 66 views
0

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

我试图导入

from django.http.request import HttpRequest 

但我困在这里。 任何人都可以帮忙吗?

编辑回答评论:

我想设置一个新的缓存装饰,以允许清除缓存项:

基于回答米哈伊洛这里: 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中。也许这不是一个好主意?我需要从构建密钥的请求中获得语言代码。

+2

你不能做到这一点。在处理任何请求之前,服务器启动时会加载url配置。如果你解释一下你想用'request'来做什么,我们可能会提出一种替代方法。 – Alasdair

+0

我编辑了这个问题来提供我的意图。 – caliph

回答

2

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

但是,我认为,如果你改变了签名会更容易阅读:

def _new_func(request, *args, **kwargs): 

,改变函数调用

response = func(request, *args, **kwargs) 
相关问题