Python+Memcache将数组更改为字符串

2024-10-02 00:21:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Amazon Elasticache和pythonspymemcache模块。在

client = Client(('xxxx', 11211))
test=[1,2,3,4]
client.set('test_key', test)
result = client.get('test_key')

pprint.pprint(result)
pprint.pprint(test)

这将输出以下内容:

^{pr2}$

如您所见,memcache结果已更改为字符串。如何存储阵列?或者将字符串转换回数组?在


Tags: 模块key字符串testclientamazongetresult
3条回答

Memcache本身将值存储为字符串。如果需要,您可以在pymemcachecustomize your serialization。它看起来像是由defaultpymemcache只是在值上使用__str__方法,如果没有提供序列化程序:

Values must have a str() method to convert themselves to a byte string. Unicode objects can be a problem since str() on a Unicode object will attempt to encode it as ASCII (which will fail if the value contains code points larger than U+127). You can fix this with a serializer or by just calling encode on the string (using UTF-8, for instance).

If you intend to use anything but str as a value, it is a good idea to use a serializer and deserializer. The pymemcache.serde library has some already implemented serializers, including one that is compatible with the python-memcache library.

我个人更喜欢^{}而不是pymemcache。它可以很好地处理非字符串值。在

图书馆似乎想让你先把数据序列化。 https://pymemcache.readthedocs.io/en/latest/getting_started.html#serialization

也许你可以用另一个图书馆? https://github.com/pinterest/pymemcache#comparison-with-other-libraries

我不确定它是否适合您的目的,但是dogpile.cache可能也值得一看。使用它很好,而且它的后端之一是memcached。在

pymemcache作为客户端的服务memcached只支持字符串值。这就是为什么默认情况下pymemcache返回一个字符串。 我建议添加一个小包装器来序列化和反序列化从字符串到对象(如数组)的值。客户机支持添加自己的序列化程序,如下所示

import json
from pymemcache.client.base import Client

def json_serializer(key, value):
    if type(value) == str:
        return value, 1
    return json.dumps(value), 2

def json_deserializer(key, value, flags):
    if flags == 1:
        return value
    if flags == 2:
        return json.loads(value)
    raise Exception("Unknown serialization format")

client = Client(('localhost', 11211), serializer=json_serializer,
            deserializer=json_deserializer)
client.set('key', [1,2,3,4])
result = client.get('key')

相关问题 更多 >

    热门问题