I am following this part of Django docs trying to add cache to generated sitemaps. Docs provide following sample code:
from django.contrib.sitemaps import views as sitemaps_views
from django.views.decorators.cache import cache_page
urlpatterns = [
path('sitemap.xml',
cache_page(86400)(sitemaps_views.index),
{'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
path('sitemap-<section>.xml',
cache_page(86400)(sitemaps_views.sitemap),
{'sitemaps': sitemaps}, name='sitemaps'),
]
It works as expected and caches result in my default cache (redis).
But since I have really large sitemap, I would the cache to be stored in file cache, not in memory. My django settings.py does include required settings:
CACHES = {
# Redis cache
"default": { ... },
# File cache
"file": { ... },
}
However when I try to specify correct arguments to cache_page decorator:
urlpatterns = [
path('sitemap.xml',
cache_page(86400)(sitemaps_views.index)(cache="file"), # <--- !!!
{'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
]
I receive an error:
TypeError: _wrapped_view() missing 1 required positional argument: 'request'
Which is the correct way of providing cache backend in such case ?
CodePudding user response:
You mixed up the function calls. Instead of
urlpatterns = [
path('sitemap.xml',
cache_page(86400)(sitemaps_views.index)(cache="file"), # <--- !!!
{'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
]
it should be
urlpatterns = [
path('sitemap.xml',
cache_page(86400, cache="file")(sitemaps_views.index), # <--- !!!
{'sitemaps': sitemaps, 'sitemap_url_name': 'sitemaps'}),
]
The argument cache needs to be in the cache_page call.
