为什么我会收到此 PicklingError 错误?

Pab*_*lav 5 python django pickle wagtail

我正在开发一个 Python/Django/Wagtail 项目,并且我有一些 api 来返回一些分页文章。事情是这样的:

在 URL 中:

url(r'^morearticles/', views.get_live_articles),
Run Code Online (Sandbox Code Playgroud)

在视图中:

def get_live_articles(request):
  context = {'articles': getLiveArticles(request) }
  return render(request, 'app/components/articles-live.html', context, content_type="text/html; charset=utf-8")
Run Code Online (Sandbox Code Playgroud)

getLiveArticles函数如下所示:

def getLiveArticles(request):

 # Articles
 a = get_articles() #this is getting the articles correctly
 p = Paginator(a, 4)
 page_n = request.GET.get('page')

 try:
     articles = p.page(page_n)
 except Exception, e:
     articles = []

 return articles
Run Code Online (Sandbox Code Playgroud)

但是,当访问 api 端点时,我得到以下信息:

    Traceback (most recent call last):
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/john/app/app/views.py", line 90, in get_live_articles
    context = {'articles': getLiveArticles(request) }
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/cache_utils/decorators.py", line 48, in wrapper
    cache.set(key, value, timeout, **backend_kwargs)
  File "/Users/john/.virtualenvs/upgrade/lib/python2.7/site-packages/django/core/cache/backends/locmem.py", line 75, in set
    pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL)
PicklingError: Can't pickle <class 'wagtail.wagtailcore.blocks.base.RichTextBlockMeta'>: attribute lookup wagtail.wagtailcore.blocks.base.RichTextBlockMeta failed
Run Code Online (Sandbox Code Playgroud)

我以前遇到过 Pickling 错误,但从未完全理解它是什么。知道是什么原因造成的吗?

如果我应该提供更多信息,请告诉我。调试后,我认为问题必须包含在这些代码块中,但我可能是错的。

编辑:对象的字段之一已转变为包含最近主要内容的 StreamField 对象。这可能有什么关系吗?

Gio*_*ili 2

我认为这与缓存相关(最近有同样的问题),其中某些对象无法被腌制以进行缓存,并且正如您所确认的那样,您正在使用缓存。所以禁用缓存就可以解决问题。

我建议使用 pickle 兼容的对象类型。另一方面,Python 文档中有一些如何实现/自定义 pickling/unpickling 逻辑的指南。