【问题标题】:Run code alongside a Flask application与 Flask 应用程序一起运行代码
【发布时间】:2018-11-21 02:22:30
【问题描述】:

我已经为我的 python 应用程序编写了一个 Web 界面。当运行export FLASK_APP=main.py 后跟flask run 时,此功能非常有效。现在我希望实际的应用程序也能运行,这样界面就会很有用。

下面的代码是我的main.py,我在这里调用flask应用工厂函数。

from webinterface import create_app

if __name__ == '__main__':
    create_app()
    while(True):
        # Some code logging different things

我想在无限循环中做一些事情,但是当我尝试运行应用程序时,它要么只运行 Web 界面,要么运行无限循环,这取决于我是使用 flask run 还是 python main.py 启动它。

我怎样才能最好地做到这一点?

【问题讨论】:

  • 为什么你需要这个while 循环呢?如果是关于日志记录,你有一堆使用 logging 模块的解决方案
  • @PRMoureu 用于从外部组件进行日志记录。温度传感器等并将其记录到数据库中,它需要永久运行。
  • WSGI 应用程序不是为并行运行其他任务而设计的。它可能适用于开发服务器,但在生产设置中您会遇到麻烦。
  • @KlausD。那么您是否建议必须单独运行 python 脚本才能完成任务?一个处理 Web 界面,一个处理所有的日志记录和测量任务?
  • 是的,听起来好多了。

标签: python flask


【解决方案1】:

在前台应用程序的线程中运行 Flask 是可能的,有时也很方便。有一个技巧,一个大陷阱和一个约束。

限制是您需要在“安全”环境中执行此操作(例如,在您的笔记本电脑上为本地浏览器提供服务器,或在您的家庭内部网中),因为它涉及运行开发服务器,即你不想在恶劣的环境中做的事情。您也不能使用自动页面重新加载(但您可以启用调试)。

陷阱在于,如果 UI 与前台应用程序共享任何重要的状态(包括字典),您将需要使用共享的 threading.Lock() 来保护访问,这样一次只有一个线程正在读取或写入数据。

诀窍是在创建应用程序之后但在启动应用程序之前将对共享状态的引用注入到应用程序的配置中,执行以下操作:

def webserver(state):
    app.config['STATE'] = state
    # If running on, say, a Raspberry Pi, use 0.0.0.0 so that
    # you can connect to the web server from your intranet.
    app.run(host='0.0.0.0', use_reloader=False, debug=True)

def main():
    state = SharedState()
    web_thread = threading.Thread(target=webserver, args=(state,))
    web_thread.start()

    state.set('counter' 0)
    while True:
        # Do whatever you want in the foreground thread
        state.set('counter', state.get('counter') + 1)

class SharedState():
    def __init__(self):
        self.lock = threading.Lock()
        self.state = dict()

    def get(self, key):
        with self.lock:
            return self.state.get(key)

    def set(self, key, value):
        with self.lock:
            self.state[key] = value

然后,在 Flask 视图函数中,执行类似的操作

@app.route('/')
def home():
    state = app.config['STATE']
    counter = state.get(counter)
    return render_template("index.html", counter=counter)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多