我正在尝试使用带有 ProtoRPC 的 memcache 来加速某些进程(带有 Python 的 Google App Engine)。为了简化问题,我使用了 Hello World 示例,并对其进行了一些修改。这是我的版本:

from protorpc import messages
from protorpc import remote
from protorpc.wsgi import service

from google.appengine.api import memcache

class HelloRequest(messages.Message):
  my_name = messages.StringField(1, required=True)

class ElementOfArrayResponse(messages.Message):
  value=messages.IntegerField(1)

class HelloResponse(messages.Message):
  hello = messages.StringField(1, required=True)
  list = messages.MessageField(ElementOfArrayResponse, 2, repeated=True)

class HelloService(remote.Service):
  @remote.method(HelloRequest, HelloResponse)
  def hello(self, request):
    response = memcache.get(request.my_name)

    if response is None:
      list = []
      for i in range(7):
        list.append(SomeElementResponse(value=i))
      response = HelloResponse(hello='Hello there, %s!' % request.my_name, list=list)
      memcache.set(request.my_name,response)
    return response

app = service.service_mappings([('/hello.*', HelloService)])

但是,不幸的是,此代码返回一个错误: ERROR 2013-01-12 17:17:31,081 service.py:196] Encountered unexpected error from ProtoRPC method implementation: PicklingError (Can't pickle <type 'weakref'>: attribute lookup __builtin__.weakref failed)

但是,当我使用与原始 HelloResponse 几乎相同的代码时,memcache 效果很好。

那么,我做错了什么?

最佳答案

两件事,看起来你的 memcache 键是一个 List 对象(想确保你知道这一点)。在您的代码旁边,您必须在放入/退出 message api 时序列化 memcache 对象。

这是一个重写:

from protorpc import remote
from protorpc import messages
from protorpc import protojson
from protorpc.wsgi import service
from google.appengine.api import memcache


class HelloRequest(messages.Message):
  my_name = messages.StringField(1, required=True)

class ElementOfArrayResponse(messages.Message):
  value=messages.IntegerField(1)

class HelloResponse(messages.Message):
  hello = messages.StringField(1, required=True)
  list = messages.MessageField(ElementOfArrayResponse, 2, repeated=True)

class HelloService(remote.Service):
  @remote.method(HelloRequest, HelloResponse)
  def hello(self, request):
    response = memcache.get(request.my_name)
    if response:
      # decode the value to a message..
      response = protojson.decode_message(HelloResponse, response)
    else:
      list = []
      for i in range(7):
        list.append(SomeElementResponse(value=i))
      response = HelloResponse(hello='Hello there, %s!' % request.my_name, list=list)
      # encode the message to a serializable format..
      value = protojson.encode_message(message)
      memcache.set(request.my_name, value)
    return response

app = service.service_mappings([('/hello.*', HelloService)])

关于python - 如何在 ProtoRPC 中使用 Memcache (Google App Engine - Python),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14296243/

10-12 22:26