【问题标题】:Are php memcached and django memcached storage different?php memcached 和 django memcached 存储有区别吗?
【发布时间】:2017-02-03 09:00:57
【问题描述】:

我正在尝试在我的新 Django 项目中实现缓存,这里的问题是,缓存是通过 PHP 服务器设置的,我需要从 Django 代码中读取它。我可以在 Django 中设置缓存,并在 Django 中读取,我也可以在 PHP 中设置缓存,并在 PHP 中读取。但是,我无法跨平台进行。即我无法读取 PHP、Django 中的缓存集,反之亦然。虽然,如果我执行telnet localhost 11211 并获取两个密钥,我只能获取在 PHP 中设置的密钥。 我已经完成了pip install python-memcached 安装以将 Memcached 与 Python 一起使用。 那么,我的问题是如何为 Django 和 PHP 使用通用缓存服务器?

这是我的 PHP sn-p

$memObj = new Memcached();
$memObj->addServer('localhost', 11211);
$memObj->set('php_key', 'hello php');
var_dump($memObj->get('django_key')); #prints False
echo $memObj->get('php_key'); #prints 'hello php'

以下是我的 Python/Django sn-p

settings.py

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

在视图中,

from django.core.cache import cache

cache.set('django_key', 'Hello world')
php_cache = cache.get('php_key')
print(php_cache) # Outputs None
django_cache = cache.get('django_key')
print(django_cache) # Outputs 'Hello world'

在 ubuntu 终端中

telnet localhost 11211
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
get php_key
VALUE php_key
hello php
END
get django_key
END

【问题讨论】:

  • 所以 django_key 不能在 memcached shell 中工作?
  • 是的,只有 php_key 在 memcached shell 中工作

标签: python django caching memcached


【解决方案1】:

这是因为 django 传递给 memcached 的密钥并不完全是您在调用 cache.set 时使用的密钥

用户提供的缓存键不是逐字使用的——它是组合的 使用缓存前缀和键版本来提供最终的缓存键。经过 默认情况下,这三个部分使用冒号连接以生成最终字符串

https://docs.djangoproject.com/en/1.10/topics/cache/#cache-key-transformation

要么调整设置,要么创建自己的KEY_FUNCTION 以确保 PHP 键与 django 键匹配。

【讨论】:

  • 我明白了,让我试一试。
  • 感谢您的项目,祝您一切顺利
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 2013-10-25
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多