(Python 3)
我正在使用 Python 生成器从队列中读取消息。
消费者读取队列消息后,需要能够告诉生成器删除队列消息,如果消息已经成功处理。
为了向 Python 生成器发送 .send(),似乎我必须先向生成器发送 .send(None)。这使得我的代码比我认为的要臃肿。
有人能建议一种方法,让 qconsumer.py 用更少的代码驱动生成器吗?我已经确定了我希望消除的哪些行。
简而言之,如何使下面的代码更紧凑,有什么建议可以删除行?
以下是 qconsumer.py 的代码:
from qserver import Qserver
myqserver = Qserver()
myproducer = myqserver.producer() # trying to eliminate this line
# first send to a generator must be None
myproducer.send(None) # trying to eliminate this line
for msg in myproducer:
# do something with message
print(msg)
if messageprocessok:
myproducer.send('delete')
以下是qserver.py的代码:
# -*- coding: utf-8 -*-
import boto
from boto.sqs.connection import SQSConnection
from boto.sqs.message import Message
QNAME = 'qinbound'
SQSREGION = 'us-west-1'
class Qserver():
"""A simple Q server."""
def __init__(self, qname=None, sqsregion=None):
self.qname = qname or QNAME
self.sqsregion = sqsregion or SQSREGION
self.sqsconn = boto.sqs.connect_to_region(self.sqsregion)
self.q_in = self.sqsconn.get_queue(self.qname)
def producer(self):
while True:
qmessage = self.q_in.read(wait_time_seconds=20)
if qmessage is None:
continue
action = (yield qmessage.get_body())
if action == 'delete':
# if processing completed ok, clear message from this queue
self.q_in.delete_message(qmessage)
None
是你可以发送给未启动生成器的唯一内容,但你并不一定需要发送。使用一个较简单的虚拟生成器对你的qconsumer.py
代码进行简单测试时,即使没有调用myproducer.send(None)
,也可以正常运行。然而,generator.send()
返回生成器的下一个值;你正在将迭代生成器与显式地使用myproducer.send
获取下一个值混合在for
循环中——你应该只使用其中之一。 - lanzz