gpt4 book ai didi

python - 将远程 FIFO 队列实现为 Python GAE 应用程序的最简单方法是什么?

转载 作者:行者123 更新时间:2023-12-01 00:00:34 24 4
gpt4 key购买 nike

将远程 FIFO 队列实现为 Python GAE 应用程序,然后向其推送/拉取名称-值对字典的最简单方法是什么?

例如,当对 GAE 应用程序进行 http get 时,GAE 应用程序将返回发布到应用程序且之前未从队列中提取的名称/值对的最旧集合。然后,这些名称-值对将在客户端重新实例化为字典。 urllib.urlencode 提供了一种将字典编码为参数的简单机制,但是当您通过 http“获取”参数时将参数解码为字典的类似简单方法是什么?当队列中没有项目时,GAE 应用程序应返回 null 或客户端可以响应的其他更合适的标识符。

#A local python script
import urllib
targetURL="http://myapp.appspot.com/queue"

#Push to dictionary to GAE queue
params = urllib.urlencode({'spam': 1, 'eggs': 2, 'bacon': 0})
f = urllib.urlopen(targetURL, params)
print f.read()
params = urllib.urlencode({'foo': 1, 'bar': 2})
f = urllib.urlopen(targetURL, params)
print f.read()


#Pull oldest set of name-value pairs from the GAE queue and create a local dictionary from them.
#f = urllib.urlopen(targetURL, ……)
#returnedDictionary = ????

实现这个简短的 GAE 应用程序的最简单方法是什么?

#queue.py a url handler in a GAE application.  
# For posts, create an object from the posted name-value pairs and insert it into the queue as the newest item in the queue
# For gets, return the name-value pairs for the oldest object in the queue and remove the object from the queue.
# If there are no items in the queue, return null

最佳答案

大致如下:

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

class QueueItem(db.Model):
created = db.DateTimeProperty(required=True, auto_now_add=True)
data = db.BlobProperty(required=True)

@staticmethod
def push(data):
"""Add a new queue item."""
return QueueItem(data=data).put()

@staticmethod
def pop():
"""Pop the oldest item off the queue."""
def _tx_pop(candidate_key):
# Try and grab the candidate key for ourselves. This will fail if
# another task beat us to it.
task = QueueItem.get(candidate_key)
if task:
task.delete()
return task
# Grab some tasks and try getting them until we find one that hasn't been
# taken by someone else ahead of us
while True:
candidate_keys = QueueItem.all(keys_only=True).order('created').fetch(10)
if not candidate_keys:
# No tasks in queue
return None
for candidate_key in candidate_keys:
task = db.run_in_transaction(_tx_pop, candidate_key)
if task:
return task

class QueueHandler(webapp.RequestHandler):
def get(self):
"""Pop a request off the queue and return it."""
self.response.headers['Content-Type'] = 'application/x-www-form-urlencoded'
task = QueueItem.pop()
if not task:
self.error(404)
else:
self.response.out.write(task.data)

def post(self):
"""Add a request to the queue."""
QueueItem.push(self.request.body)

需要注意的是:由于队列排序依赖于时间戳,因此,由于没有全局时钟(只有 NFS 同步服务器),因此在不同计算机上非常接近地到达的任务可能会乱序排队。不过,可能不是真正的问题,具体取决于您的用例。

关于python - 将远程 FIFO 队列实现为 Python GAE 应用程序的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1397864/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com