如何使用Django缓存?(最好在GAE)

Emm*_*t B 9 django google-app-engine memcached

我无法使用GAE进行memcached工作.当我使用Google缓存后端时,按照GAE网站上的教程,不会缓存视图.所以我使用了Django教程中建议的缓存网址(例如:

`(r'^example$', cache_page(60*15)(views.example)),
Run Code Online (Sandbox Code Playgroud)

然后我明白了:

File "/python27_runtime/python27_lib/versions/third_party/django-1.4/django/middleware/cache.py", line 205, in __init__
self.cache_timeout = self.cache.default_timeout

 AttributeError: 'Client' object has no attribute 'default_timeout'
Run Code Online (Sandbox Code Playgroud)

AttributeError:'Client'对象没有属性'default_timeout',如果我使用谷歌后端(django.core.cache.backends.memcached.MemcachedCache)我得到

Error: ImproperlyConfigured: Error importing middleware django.contrib.sessions.middleware: "No module named memcache".
Run Code Online (Sandbox Code Playgroud)

以前有人问过使用Django缓存后端并建议安装python-memcached,我这样做了,但它仍然无效.

有人建议为GAE写后端.我不太明白.如果对这个问题的最佳回答将逐步解释如何非常粗略地编写后端,那么我将接受这个答案.

Nik*_*luk 4

并非所有 Django 功能都可以在 App Engine 上运行。因此,由于 App Engine 基础设施的限制,您尝试使用的功能对于 App Engine Django 库来说是不允许的。

如果我理解正确的话,您想缓存整个页面或者换句话说整个视图的响应?你可以用这种方式做到这一点(只是例子):

# Django on App Engine view example
from google.appengine.api import memcache
from django.http import HttpResponse

def cached_index_page(request):
  output_html = memcache.get('index_page')  # here we "take" from cache
  if output is not None:
    pass
  else:
    output_html = get_page_content()
    memcache.add('index_page', output_html, 60)  # here we "put" to cache" (timeout also here)
  HttpResponse(output_html)
Run Code Online (Sandbox Code Playgroud)

为了您的目的,您可以创建 Django 的中间件,自动缓存您需要的任何页面。

还要确保您从配置文件中删除了所有与 App Engine 无关/不可接受的内容。考虑帮助页面(https://developers.google.com/appengine/articles/django),最小配置如下所示:

import os

# 'project' refers to the name of the module created with django-admin.py
ROOT_URLCONF = 'project.urls'

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
#    'django.contrib.sessions.middleware.SessionMiddleware',
#    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'google.appengine.ext.ndb.django_middleware.NdbDjangoMiddleware', # NoSQL db middleware
)

INSTALLED_APPS = (
#    'django.contrib.auth',
    'django.contrib.contenttypes',
#    'django.contrib.sessions',
    'django.contrib.sites',
)

ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or
    # "C:/www/django/templates".  Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    ROOT_PATH + '/templates',
)
Run Code Online (Sandbox Code Playgroud)

请记住,App Engine 具有自己的本机缓存,例如,Python 运行时环境在单个 Web 服务器上的请求之间缓存导入的模块,除了导入的模块之外,您还可以告诉 App Engine 缓存 CGI 处理程序脚本本身。

有用的链接: https://developers.google.com/appengine/articles/django-nonrel https://developers.google.com/appengine/docs/python/tools/libraries27