【问题标题】:How to us an arg given to Flask app.config inside a route function?如何在路由函数中为 Flask app.config 提供参数?
【发布时间】:2020-03-30 19:49:27
【问题描述】:

我的 webapp 从函数内部运行,因为我与其他函数(只有 1 个烧瓶实例)进行多线程,我的问题是: A. 将队列传递到应用程序的最佳方式是什么? B.通过后,Queue如何在特定路由内部使用?

这是我到目前为止编写的代码的相关部分,当向“/parser”发出请求时,它会给出错误“全局名称'队列'未定义”。

app = Flask(__name__)
q = Queue()
app.config['queue'] = q;

@app.route('/parser')
def Parser():
    arg = request.args.get('arg') #if key doesn't exist, returns None
    queue.put(arg)

def Run():
    app.run(debug=False, host='0.0.0.0')

if __name__ == '__main__':
    q = Queue()
    app.config['queue'] = q;
    thread = Thread(target = Run)
    thread.start()

提前致谢:)

【问题讨论】:

    标签: python multithreading flask queue


    【解决方案1】:

    编辑:添加了一个可能有帮助的代码示例

    from flask import Flask
    from threading import Thread
    from queue import Queue
    
    app = Flask(__name__)
    q = Queue()
    app.config['queue'] = q;
    app.config['test'] = 'testing';
    
    @app.route('/insert/<var>')
    def Insert(var):
        q = app.config['queue']
        q.put(var)
        return "Ok"
    
    @app.route('/pop')
    def Get():
        q = app.config['queue']
        return q.get()
    
    
    def Run():
        app.run(debug=False, host='0.0.0.0')
    
    if __name__ == '__main__':
        thread = Thread(target = Run)
        thread.start()
    

    我很确定flask 不支持在多个线程中运行同一个应用程序实例。

    我感觉这是XY problem的一个实例, 如果您在生产环境中部署,page 列出了一些可以处理多个并发连接的方法。

    【讨论】:

    • 我没有运行多个烧瓶,其他线程正在做完全不同的事情。我的问题不是关于队列,而是关于在其中一个路由中使用通过 app.config 发送的 arg。
    猜你喜欢
    • 2016-08-25
    • 1970-01-01
    • 2018-11-25
    • 2015-09-30
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    • 2018-05-15
    相关资源
    最近更新 更多