我有一个正在运行仪表板的 flask 应用程序,仪表板的某些部分使用日期作为输入表单来过滤来自数据库的数据。但是如果用户没有输入日期作为请求参数,那么路由会返回一个模板,该模板使用表 gps_data 中的最后一个可用日期呈现。
我有我想要的仪表板索引的下一条路线:
import psycopg2 as pg2
@bp.route("/index",methods=["GET","POST"])
def index():
date = request.args.get("date") # date form input
imei = request.args.get("imei") # imei form input
# if the user request 'index' without any date use last date from the table gps_data
if not date:
cur = conn.cursor() # psycopg2 cursor to postgresql database
query = """SELECT
max(timestamp_utc::date)
FROM
gps_data
WHERE imei = imei%s
"""
try:
# gps_data_last_date
cur.execute(query,imei)
date = cur.fetchall()[0][0]
except Exception as e:
conn.rollback()
date = None
print(e)
else:
conn.commit()
return redirect(url_for("dashboard.index",date=date))
return render_template(
"dashboard.html",date=date
)
但问题是我不想在用户加载仪表板页面时获取最大日期,因为表 gps_data 非常大,加载页面时的性能可能会受到影响。所以我想使用一种后台任务来更新全局变量中的最大日期或类似的东西(例如每天一次),避免查询数据库表 gps_data。
我已经研究过哪种最好的方法来实现这一点,似乎有两种选择:
- 添加Celery + Redis,并在flask中设置一个Celery周期任务,然后从Redis读取视图函数中的日期。
- 向 flask 添加一个后台线程,如 this answer 并从全局变量中读取视图函数中的日期。
- 继续使用 SQL 表 gps_data,但在列
timestamp_utc
和imei
上添加索引。
你知道有没有比这两个更好或更有效的选择吗?如果没有其他选择,您认为这两个选项中哪个最好?
编辑:添加第三个选项