与 Flask 服务器同时运行 while 循环 [英] Run while loop concurrently with Flask server

查看:24
本文介绍了与 Flask 服务器同时运行 while 循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 python 更新一些 LED.我一直在这样做:

I'm updating some LEDs using python. I've been doing this like so:

from LEDs import *
myLEDs = LEDs()
done = False
while not done:
  myLEDs.iterate()

我想使用 Flask 充当一些可以在浏览器中运行的漂亮 ReactJS 前端(以更改当前模式等)和 Python 中的 LED 控制代码之间的桥梁.

I wanted to use Flask to act as a bridge between some nice-looking ReactJS front-end I can run in my browser (to change the current pattern, etc) and the LED-controlling code in Python.

我的 Flask 工作正常,可以处理 HTTP 请求等.我想知道如何设置 myLEDs.iterate() 与我的同时持续运行(或快速运行)Flask 应用程序,同时仍然能够相互通信,如下所示:

I have Flask working fine, can handle HTTP requests, etc. I'm wondering how I can set myLEDs.iterate() to continuously run (or run on a rapid schedule) concurrently with my flask app, while still being able to communicate with one another, like so:

myLEDs = LEDs()

@app.route('/changePattern',methods=['POST'])
def changePattern():
  n = request.json['num']
  myLEDs.setPattern(n)
  return jsonify(**locals())

if __name__ == '__main__':
  app.debug = True
  myLEDs.setToFrequentlyIterateAndStillTalkToFlask()
  app.run()

我遇到了 celery,这似乎可以解决问题,但对于我的问题的简单程度来说似乎有点过分了.

I came across celery, which seems like it would do the trick, but also seems like overkill for how simple my problem is.

仅仅想要一个 UI 来管理我的 python 后端代码,使用 Flask 是否太过分了?是否有比 Celery 更简单的库可用于在后台运行某些东西?

Is using Flask overkill for simply wanting a UI to manage my python back-end code? Is there a simpler library than Celery to use for running something in the background?

编辑

这是一个更大项目的一部分,该项目旨在开发一个将 Node-Webkit 前端连接到 Python 后端的应用程序.如果它看起来不可行,我愿意改变我对这个应用程序的方法.

This is part of a larger project to develop an app with a Node-Webkit front-end attached to a Python backend. I'm open to changing my approach to this app if it doesn't seem feasible.

推荐答案

使用 multiprocess 在不同的进程中运行循环作为 Flask HTTP 请求:

Use multiprocess to run the loop in a different process as the Flask HTTP requests:

import time
from flask import Flask, jsonify
from multiprocessing import Process, Value


app = Flask(__name__)


tasks = [
   {
      'id': 1,
      'title': u'Buy groceries',
      'description': u'Milk, Cheese, Pizza, Fruit, Tylenol', 
      'done': False
   },
   {
      'id': 2,
      'title': u'Learn Python',
      'description': u'Need to find a good Python tutorial on the web', 
      'done': False
   }
]


@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
   return jsonify({'tasks': tasks})


def record_loop(loop_on):
   while True:
      if loop_on.value == True:
         print("loop running")
      time.sleep(1)


if __name__ == "__main__":
   recording_on = Value('b', True)
   p = Process(target=record_loop, args=(recording_on,))
   p.start()  
   app.run(debug=True, use_reloader=False)
   p.join()

任务部分来自这里,来自我的多处理代码.
注意use_reloader=False"部分.这对于避免循环运行两次是必要的.原因请参见此处

The tasks part is from here, multiprocessing code from me.
Note the "use_reloader=False" part. This is necessary to avoid running the loop twice. For the reason see here

可以通过启动服务器来测试功能

The functionality can be tested by starting up the server with

python <your_name_for_the example>.py

并打电话

curl -i http://localhost:5000/todo/api/v1.0/tasks

这篇关于与 Flask 服务器同时运行 while 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆