python - 为 App Engine 上的 Django session 缓存设置 Memcached

标签 python django google-app-engine caching memcached

当设置 Django 以使用 Memcached 进行缓存时(在我的例子中,我想使用 session 缓存),在 settings.py 中我们设置

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

我将在 App Engine 中运行该项目,所以我的问题是如何处理 LOCATION 条目?

最佳答案

碰巧的是,过去几天我一直在将 Django (1.6.5) 应用程序移植到 GAE(GAE Development SDK 1.9.6)。我现在对缓存的需求不大,但很高兴知道它在我需要时可用。

所以我只是尝试使用 django.core.cache.backends.memcached.MemcachedCache 作为我的缓存后端(按照你在问题中描述的设置,我把 python-memcached 放在我的 libs 文件夹中) 和

SESSION_ENGINE = 'django.contrib.sessions.backends.cache' 

为了管理我的 session ,GAE 给了我错误:

RuntimeError: Unable to create a new session key. It is likely that the cache is unavailable.

无论如何...

...即使您可以让它工作,使用 Google 的 API 库并借用 Django Memcached 实现肯定更好,特别是因为 Google 库被设计为 compatible with python-memcached否则您的应用程序可能会随时因 SDK 更新而中断。创建一个 python 模块,例如 my_project/backends.py:

import pickle
from django.core.cache.backends.memcached import BaseMemcachedCache


class GaeMemcachedCache(BaseMemcachedCache):
    "An implementation of a cache binding using google's app engine memcache lib (compatible with python-memcached)"
    def __init__(self, server, params):
        from google.appengine.api import memcache
        super(GaeMemcachedCache, self).__init__(server, params,
                                             library=memcache,
                                             value_not_found_exception=ValueError)

    @property
    def _cache(self):
        if getattr(self, '_client', None) is None:
            self._client = self._lib.Client(self._servers, pickleProtocol=pickle.HIGHEST_PROTOCOL)
        return self._client

然后你的缓存设置变成:

CACHES = {
    'default': {
        'BACKEND': 'my_project.backends.GaeMemcachedCache',
    }
}

就是这样!这似乎工作正常,但我应该清楚它没有经过严格测试!

一边

在您的 GAE SDK 文件夹中的 google.appengine.api.memcache.__init__.py 中搜索一下,您会发现:

  def __init__(self, servers=None, debug=0,
               pickleProtocol=cPickle.HIGHEST_PROTOCOL,
               pickler=cPickle.Pickler,
               unpickler=cPickle.Unpickler,
               pload=None,
               pid=None,
               make_sync_call=None,
               _app_id=None):
    """Create a new Client object.

    No parameters are required.

    Arguments:
      servers: Ignored; only for compatibility.
    ...

即即使您可以在云中找到您的内存缓存实例的 LOCATION,Google 自己的库也会忽略它。

关于python - 为 App Engine 上的 Django session 缓存设置 Memcached,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699935/

相关文章:

mysql - Django 按年、月、日、时、分过滤日期时间

django - 是 BigTable 慢还是我笨?

android - 使用 Android Studio 的 Google Cloud Endpoints 模板时的 Proguard 配置

python - 如何在 C++ 中为 Cython 中的两种类型使用模板化函数?

django - 避免 Django 迁移问题的技术?

python - 如何仅按字符串中的第一个特殊字符拆分字符串?

python - Django 显示所有用户

java - FinalizationException - AppEngine Java Blobstore API

python - Flask-SQL 中没有 SQLAlchemy 模块

python - Flask 无法识别两个 URL 参数