创建后台任务以在 Flask 中检索 PyMongo DB 以进行分析

Creating background task to retrieve PyMongo DB in Flask for Analytics

我目前正在连接到远程 mongodb 以在 Flask 中生成仪表板。数据库连接和加载到 Pandas 发生在每个页面请求上。

@app.route("/")

   #connects to db
   #loads to pandas
   #perform analysis and display

@app.route("/recent/")

   #connects to db
   #loads to pandas
   #perform analysis and display

为每个页面请求将整个数据集加载到 Pandas 中显然效率低下。正在加载的数据不会频繁更改(可能每 10 分钟左右)。

在这种情况下最有效的方法/最佳实践是什么。是否可以定义一个全局函数,每 x 分钟更新一次数据集,本地函数在每个页面请求上对全局数据集执行分析?

谢谢。

创建后台任务的一种方法是使用 Celery。要安装 celery 只需 pip install celery(在 virtualenv 中像往常一样理想)。 Here is complete tutorial for the basics of that. Here 是 Miguel 在他的博客 post 中构建的项目的存储库。为了 posterity,我将在此处复制并解释一些基础知识:

from flask import Flask
from celery import Celery

app = Flask(__name__)
app.config['CELERY_BROKER_URL'] = 'redis://localhost:6379/0'
app.config['CELERY_RESULT_BACKEND'] = 'redis://localhost:6379/0'

celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
celery.conf.update(app.config)

显然只是一个基本的应用程序实例,配置为与 celery 一起使用。下一个障碍是设置 "message broker"。在这个例子中,redis 就是这样使用的。

这是一个脚本,用于为您下载和 运行ning redis,运行-redis.sh:

#!/bin/bash
if [ ! -d redis-stable/src ]; then
    curl -O http://download.redis.io/redis-stable.tar.gz
    tar xvzf redis-stable.tar.gz
    rm redis-stable.tar.gz
fi
cd redis-stable
make
src/redis-server

如果你线性地遵循这个,你现在应该有一个终端 运行ning redis,现在你需要再打开两个,一个到 运行 celery,然后一个到 运行 开发服务器。

celery worker -A app.celery --loglevel=info

然后:

python app.py 

假设 app.run()app.py.

中调用

最后,为了适应您的用例,您需要在 app.py.

中创建 任务
from celery import Celery

@app.task
def add(x, y):
    return x + y

在后台获取 运行 为:

add.delay(4, 4)

就是这样。您可以在以后的某个时间将任务设置为 运行。您还可以定期将任务设置为 运行:http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html