谷歌应用引擎 jsonpickle

4 投票
2 回答
1566 浏览
提问于 2025-04-15 17:38

有没有人成功在谷歌应用引擎上使用jsonpickle?我的日志显示没有这个模块,但我可以肯定这个模块是存在的。我现在用的是jsonpickle 0.32版本。

<type 'exceptions.ImportError'>: No module named jsonpickle
Traceback (most recent call last):
  File "/base/data/home/apps/xxxxx/xxxxxxxxxxxxxxxxx/main.py", line 4, in <module>
    import jsonpickle

2 个回答

3

正如这篇帖子所说,jsonpickle需要一些特定的JSON模块来正常工作。解决这个问题的方法是,在你需要用到jsonpickle的模块顶部加上以下几行代码:

import sys
import django.utils.simplejson
sys.modules['simplejson'] = django.utils.simplejson

这样做可以解决问题:jsonpickle需要使用simplejson这个JSON模块,但在GAE中,它是以django.utils.simplejson的形式存在,所以你需要正确地“别名”它。

4

我已经成功地把 django.utils.simplejson 注册为一个可以处理 JSON 的编码器和解码器。在这个实际的文件 index.py 中,Pizza 类被编码和解码回来了:

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app

import jsonpickle

class Pizza:
    pass                

class Example(webapp.RequestHandler):
    def get(self):
        jsonpickle.load_backend('django.utils.simplejson',
                                'dumps','loads',ValueError)
        encoded = jsonpickle.encode(Pizza())
        self.response.out.write( jsonpickle.decode(encoded).__class__ )

run_wsgi_app(webapp.WSGIApplication([('/', Example),],debug=True))

撰写回答