manage.py如何开始flask的迭代



我正在制作一个价格跟踪器。我的项目结构是这样的:

Myapp-folder     
manage.py-from flask script module     
subApp-folder
__init__.py 
form.py 
models.py 
views.py 
pricemonitor-folder 
main.py    
__init__.py 
send_email.py 
price_compare_sendemail.py-with class Compare_sendemail and start_monitor function

在main.py中,我有一个交互,每60秒比较一次价格,并在需要时发送电子邮件。

from app.PriceMonitor.price_compare_sendmail import Compare_sendemail
break_time = 60  # set waiting time for one crawl round
monitor = Compare_sendemail()
monitor.start_monitor(break_time)

manage.py如下:

from flask_script import Manager, Server
from app import app, db
manager = Manager(app)
manager.add_command("runserver",Server(host='127.0.0.1', port=5000, use_debugger=True))
if __name__ == '__main__':
manager.run()

但是,当我成功地直接运行main.py时,运行python manage.py runserver时,迭代就不起作用了。我如何编写代码以在后台运行compare_sendemail迭代的情况下运行flask服务器?谢谢

我想您正在寻找芹菜您可以使用芹菜后台任务。如果你的应用程序有一个长时间运行的任务,比如处理一些上传的数据或发送电子邮件,你不想在请求过程中等待它完成。相反,使用任务队列将必要的数据发送到另一个进程,该进程将在请求立即返回时在后台运行该任务。

在这里你可以找到芹菜的文档https://flask.palletsprojects.com/en/1.1.x/patterns/celery/

如果你想等待任务完成,你可以使用推论和任务

https://docs.python.org/3/library/asyncio-task.html

烧瓶后台任务还有其他选项像

RQhttps://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-xxii-background-jobs

其他一些选择https://smirnov-am.github.io/background-jobs-with-flask/

线程

uWSGI线程

uWSGI后台处理程序uSWGI后台处理程序非常适合执行简单任务。比如发送OTP短信或电子邮件。

我回答了我自己的部分问题。在main.py中,我使用while循环和时间模块来迭代price_compare_sendemail.py每60年代。虽然这不是一个理想的后台任务处理程序,但这个项目目前只供我自己使用,所以对我来说还可以。我最初的想法是使用flask脚本管理器来处理所有的python命令——但我不知道这是否是正确的想法,因为我刚刚开始学习flask。经过谷歌搜索,我找到了使用manager的方法。

from subapp.pricemonitor.main import Start_monitor
Monitor=Start_monitor()
@manager.command
def monitor_start():
break_time=10
Monitor.start_monitoring(break_time)

然后使用命令"python manage.py monitor_start"启动后台任务。我不知道它是否有用,但至少它符合我最初的想法。

最新更新