1

I cannot figuring out how I can get ahold of the request object in the urls.py file.

I tried to import

from django.http.request import HttpRequest

But I am stuck here. Can anybody help?

Edit to answer to comment:

I am trying to set a new caching decorator in order to allow for clearing cache items:

based on answer from Mihajlo here: 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

I assumed I would place this function in urls.py. Maybe that was not a good idea? And I need the language code from request for building the key.

caliph
  • 1,389
  • 3
  • 27
  • 52
  • 2
    You can't do this. The url config is loaded when the server starts, before any requests have been processed. If you explain what you want to do with the `request`, we might be able to suggest an alternative approach. – Alasdair Oct 19 '17 at 18:15
  • I edited the question to provide my intention. – caliph Oct 19 '17 at 18:44

1 Answers1

3

In the _new_func method, the request is currently the first argument args[0].

However, I think it would be easier to read if you changed the signature to:

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

and change the function call to

response = func(request, *args, **kwargs)
Alasdair
  • 298,606
  • 55
  • 578
  • 516