为什么此队列无法正常工作?

时间:2018-06-20 12:12:39

标签: python-3.x

以下队列无法正常工作。我犯了明显的错误吗?基本上,每条传入的SMS消息都会放入队列,尝试发送,如果成功,则从队列中删除。如果未成功,它将休眠2秒钟,然后尝试再次发送。

# initialize queue
queue = queue.Queue()

def messagePump():
    while True:
        item = queue.get()
        if item is not None:
            status = sendText(item)
            if status == 'SUCCEEDED':
                queue.task_done()
            else:
                time.sleep(2)

def sendText(item):
    response = getClient().send_message(item)
    response = response['messages'][0]
    if response['status'] == '0':
        return 'SUCCEEDED'
    else:
        return 'FAILED'

@app.route('/webhooks/inbound-sms', methods=['POST'])
def delivery_receipt():
    data = dict(request.form) or dict(request.args)
    senderNumber = data['msisdn'][0]
    incomingMessage = data['text'][0]
    # came from customer service operator
    if (senderNumber == customerServiceNumber):
        try:
            split = incomingMessage.split(';')
            # get recipient phone number
            recipient = split[0]
            # get message content
            message = split[1]
            # check if target number is 10 digit long and there is a message
            if (len(message) > 0):
                # for confirmation send beginning string only
                successText = 'Message successfully sent to: '+recipient+' with text: '+message[:7]
                queue.put({'from': virtualNumber, 'to': recipient, 'text': message})

以上内容在Flask服务器上运行。因此,调用messagePump:

thread = threading.Thread(target=messagePump)
thread.start()

1 个答案:

答案 0 :(得分:0)

在这种情况下,常见的情况是线程在开始向队列中显示项目之前已完成执行,请在运行thread.daemon = True之前调用thread.start()

这里可能发生的另一件事是线程由于异常而终止。确保messagePump处理所有可能的异常。

关于跟踪线程异常的主题可能对您有用:

Catch a thread's exception in the caller thread in Python