【问题标题】:How do I get Celery to return a json object instead of bytea?如何让 Celery 返回一个 json 对象而不是 bytea?
【发布时间】:2017-06-11 20:31:57
【问题描述】:

这是我第一次在 Python 3 中使用 Celery。为了弄湿我的脚,我从工作人员那里返回了一个字符串“这是一个你好任务”,并将其存储为一个 Postgres 数据库。当我从我的数据库中访问结果时,它以 Python 中的 memoryview 的形式出现,并且数据库本身有一个 celery_taskmeta 的结果列作为数据类型 bytea(这也是 Celery 发送到数据库的内容)。

这是我的芹菜配置:

import os

broker_url = os.environ.get('RABBITMQ_BIGWIG_TX_URL')
worker_concurrency = 3
result_backend = 'db+postgres://...'
task_serializer = 'json'
result_serializer = 'json'
accept_content = ['json']

为什么我的数据库中没有存储 json 结果?此外,我无法将 bytea 解码为 json 或 utf-8 文本,我收到此错误:

这是它的字节数:b'\x80\x04\x95\x1b\x00\x00\x00\x00\x00\x00\x00\x8c\x17"this was a hello task"\x94.'

命令:json.loads(t.tobytes())

结果:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

【问题讨论】:

    标签: python json postgresql celery


    【解决方案1】:

    你需要将字节数据转换成unicode

    t.decode("utf-8")
    

    【讨论】:

    • 我试过了,但我得到了同样的错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
    • docs.python.org/3.5/library/stdtypes.html#bytes.decode 你可以使用第二个参数来抑制像t.decode("utf-8", errors="ignore")这样的错误
    【解决方案2】:

    你需要用pickle加载它。

    import pickle
    
    pickle.loads(t, encoding='utf-8')
    

    我自己也在为此苦苦挣扎,试图让 Celery 将结果存储在 DB JSON 序列化而不是腌制中。

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 2021-05-18
      • 2015-09-05
      • 2019-09-24
      • 1970-01-01
      • 2013-07-07
      • 2014-08-20
      • 2017-09-22
      相关资源
      最近更新 更多