Pyramid与memcached: 如何使其工作?错误 - MissingCacheParameter:需要url

3 投票
1 回答
2058 浏览
提问于 2025-04-17 12:20

我有一个基于Pyramid框架的网站,想用memcached来缓存数据。为了测试,我先用了内存缓存,效果很好。我使用的是pyramid_beaker这个包。

这是我之前的代码(可以正常工作的版本)。

.ini文件中:

cache.regions = day, hour, minute, second
cache.type = memory
cache.second.expire = 1
cache.minute.expire = 60
cache.hour.expire = 3600
cache.day.expire = 86400

在views.py文件中:

from beaker.cache import cache_region

@cache_region('hour')
def get_popular_users():
    #some code to work with db
return some_dict

我在文档中找到的.ini设置只涉及内存和文件类型的缓存,但我需要使用memcached。

首先,我从Ubuntu的官方库安装了memcached包,并且在我的虚拟环境中也安装了python-memcached

.ini文件中,我把cache.type = memory改成了cache.type = memcached。结果出现了下面的错误:

beaker.exceptions.MissingCacheParameter

MissingCacheParameter: url is required

我哪里做错了呢?

提前谢谢你们的帮助!

1 个回答

4

根据TurboGears的文档,你在设置url的时候用了什么选项呢?

[app:main]
beaker.cache.type = ext:memcached
beaker.cache.url = 127.0.0.1:11211
# you can also store sessions in memcached, should you wish
# beaker.session.type = ext:memcached
# beaker.session.url = 127.0.0.1:11211

我发现memcached需要一个url才能正确初始化:

def __init__(self, namespace, url=None, data_dir=None, lock_dir=None, **params):
    NamespaceManager.__init__(self, namespace)

    if not url:
        raise MissingCacheParameter("url is required") 

我不太明白为什么代码里url是可选的(默认值是None),但又要求必须提供。我觉得直接把url设为必填参数会简单很多。


后来:针对你下一个问题的回答:

当我使用cache.url时,出现了下列错误:AttributeError: 'MemcachedNamespaceManager'对象没有属性'lock_dir'

根据我对下面代码的理解,你必须提供lock_dirdata_dir来初始化self.lock_dir:

    if lock_dir:
        self.lock_dir = lock_dir
    elif data_dir:
        self.lock_dir = data_dir + "/container_mcd_lock"
    if self.lock_dir:
        verify_directory(self.lock_dir)

你可以用这段测试代码复现这个错误:

class Foo(object):
    def __init__(self, lock_dir=None, data_dir=None):
        if lock_dir:
            self.lock_dir = lock_dir
        elif data_dir:
            self.lock_dir = data_dir + "/container_mcd_lock"
        if self.lock_dir:
            verify_directory(self.lock_dir)

f = Foo()

结果是这样的:

>>> f = Foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in __init__
AttributeError: 'Foo' object has no attribute 'lock_dir'

撰写回答