如何在Protorpc中使用任务队列(推送队列)。
我有一个登陆页表单,在发送它时执行多个操作:
表单发送是在服务器端用protorpc实现的。
class FormRequest(messages.Message)
field1 = messages.StringField(1, required=True)
field2 = messages.StringField(2, required=True)..。
class FormApi(remote.Service):
@remote.method(TravelRequest, message_types.VoidMessage)
def insert(self, request):
# Save the form in the DataStore
travel = FormModel(field1=request.field1, field2=request.field2)
travel.put()
# Send an email to the client
...
# Send the data to a third party
...
return message_types.VoidMessage()由于用户需要等待所有这些请求时间,因此该解决方案停滞不前。(在这种情况下,它只是2-3,但它是一个登陆页形式的很多)
一个好的解决方案是使用taskqueue来减少用户需要等待的时间:
(作为一个例子)
class ...
@remote ...
def ...
# Save the form in the DataStore
taskqueue.add(url='/api/worker/save_to_db', params={'field1': request.field1, 'field2': request.field2})
# Send an email to the client
taskqueue.add(url='/api/worker/send_email', params={'field1': request.field1, 'field2': request.field2})
# Send the data to a third party (CRM)
taskqueue.add(url='/api/worker/send_to_crm', params={'field1': request.field1, 'field2': request.field2})“问题”是protorpc只有json对象作为请求。如何使用TaskQueue(Push)完成此操作?
TaskQueue的默认行为是将params作为一串urlencoded发送,这对protorpc来说并不方便。
发布于 2014-10-14 17:21:32
让我们为任务队列定义一个工作人员服务:
class WorkersApi(remote.Service):
@remote.method(TravelRequest, message_types.VoidMessage)
def save_to_db(self, request):
# Instead of write each parameter, I am using this "cheat"
params = {}
for field in request.all_fields():
params[field.name] = getattr(request, field.name)
# Save data in the datastore
form_model = FormModel(**params)
form_model.put()
return message_types.VoidMessage()请注意,对于实际请求和任务队列请求,我使用相同的message对象(不需要为每个请求创建不同的message对象是一个很大的优势),问题是如何使用这个protorpc函数来使用taskqueue。
正如我在问题中所说的,任务队列的默认行为并不方便。
解决方案是将原始请求/消息(在我们的示例中是application/json**.** )对象转换回字符串,并为有效负载为FormRequest的任务队列设置一个头。
下面是代码:
# This format string is take from the util file in the protorpc folder in Google App Engine source code
format_string = '%Y-%m-%dT%H:%M:%S.%f'
params = {}
for field in request.all_fields():
value = getattr(request, field.name)
if (isinstance(value, datetime.datetime)):
value = value.strftime(format_string)
params[field.name] = value
taskqueue.add(url='/api/workers.save_to_db', payload=json.dumps(params), headers={'content-type':'application/json'})对“电子邮件”和"crm“也要这样做。
发布于 2015-10-01 23:55:55
您可以在没有时间的情况下使用异步()编写:异步地将实体的数据写入数据存储。
例如:
travel = FormModel(field1=request.field1, field2=request.field2)
travel.put_async()
# next actionhttps://stackoverflow.com/questions/26366588
复制相似问题