带背景线程的烧瓶将队列视为空而不是uwsgi

时间:2018-09-10 09:39:20

标签: python multithreading flask queue

关于这个问题:Flask: Background thread sees a non-empty queue as empty

我有同样的问题,一个队列存在两次。但即时通讯不使用uWSGI。我只是从控制台启动.py脚本。

有没有一种方法可以解决此问题,而无需为--lazy-apps选项添加uWSGI?

如果那是唯一的方法,我如何更改脚本以与uWSGI一起运行?

以下是代码:

import json
import logging
import os
import queue
import sys
import time
from threading import Thread

from flask import Flask, jsonify, render_template

import win32file
import win32pipe

app = Flask(__name__)
myQueue = queue.Queue(maxsize=0)

def pipe_client():

    status = False

    while not status:
        try:
            fileHandle = win32file.CreateFile("\\\\.\\pipe\\chat",  # Pipename
                                    win32file.GENERIC_READ,       # Access type
                                    0, 
                                    None,
                                    win32file.OPEN_EXISTING,
                                    0, 
                                    None
                                    )

            while True:
                reply = win32file.ReadFile(fileHandle, 4096)
                if reply[0] == 0:
                    myQueue.put(reply[1])
                    print('Queuesize: ' + str(myQueue.qsize()))

        except Exception as e:
            if e.args[0] == 2:
                print(e)
                time.sleep(5) 
            else:
                print(e)
                status = True  

# Routes
@app.route('/<channel>')        
def channel(channel):
    return render_template('index.html', channel=channel)

@app.route('/')
def index():
    return render_template('index.html', channel='geekandsundry')

@app.route('/chat')
def chat():
    data = list()
    print('Queuesize before: ' + str(myQueue.qsize()))

    while not myQueue.empty():
            message = myQueue.get()
            print(message)
            message.decode("UTF-8")
            print(message)
            data.append(message)
            myQueue.task_done()

    print('Queuesize after: ' + str(myQueue.qsize()))
    return json.dumps(data)

if __name__ == '__main__':
    thread = Thread(target=pipe_client)
    thread.start()

    app.run(debug=True)

谢谢

0 个答案:

没有答案