flask如何使数据库查询引用保持最新 [英] flask how to keep database queries references up to date

查看:49
本文介绍了flask如何使数据库查询引用保持最新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个烧瓶应用程序,其中包含两个面板,一个用于管理员,另一个用于用户.在应用程序方案中,我有一个实用程序文件,除其他功能外,我还保留了大多数冗余变量(通过冗余,是指我在应用程序的许多不同部分中使用了它)

I am creating a flask app with two panels one for the admin and the other is for users. In the app scheme I have a utilities file where I keep most of the redundant variables besides other functions, (by redundant i mean i use it in many different parts of the application)

utilities.py

# ...
opening_hour = db_session.query(Table.column).one()[0]  # 10:00 AM
# ...

Table.column 或上面的 opening_hour 变量的值由管理员通过其Web面板输入到数据库中.此值限制用户在指定的小时之前访问应用程序的某些功能.

The Table.column or let's say the opening_hour variable's value above is entered to the database by the admin though his/her web panel. This value limits the users from accessing certain functionalities of the application before the specified hour.

问题是:

如果管理员通过他/她的网络面板更改了该值,则假设是 11:00 AM .所做的更改不会直接显示在用户面板中.即使已将其输入数据库!".

If the admin changes that value through his/her web panel, let's say to 11:00 AM. the changes is not being shown directly in the users panel."even though it was entered to the database!".

如果我想要新的 opening_hour 值来控制.我必须手动关闭应用程序并有时甚至无法正常工作"重新启动它

If I want the new opening_hour's value to take control. I have to manually shutdown the app and restart it "sometimes even this doesn't work"

我尝试添加 gc.collect() ...什么也没做.除了手动关闭和重新启动应用程序外,还必须有其他解决方法.首先,我怀疑管理员能够做到这一点.第二,即使他/她可以,那也确实令人沮丧.

I have tried adding gc.collect()...did nothing. There must be a way around this other than shutting and restarting the app manually. first, I doubt the admin will be able to do that. second, even if he/she can, that would be really frustrating.

如果有人可以对此进行说明,请解释为什么会发生这种情况以及如何解决它.在此先感谢:)

If someone can relate to this please explain why is this occurring and how to get around it. Thanks in advance :)

推荐答案

您正在尝试向简单的变量添加高级逻辑:您只想查询数据库一次,并通过重新加载变量来定期强制更新该变量.模块.那不是应该使用模块和导入机制的方式.

You are trying to add advanced logic to a simple variable: You want to query the DB only once, and periodically force the variable to update by re-loading the module. That's not how modules and the import mechanism is supposed to be used.

如果要从数据库访问可能更改的值,则必须一遍又一遍地读取它.

If you want to access a possibly changing value from the database, you have to read it over and over again.

解决方案是定义一个函数 opening_hours (而不是变量),该函数每次您检查值时都会执行数据库查询

The solution is to, instead of a variable, define a function opening_hours that executes the DB query every time you check the value

def opening_hours():
    return (
        db_session.query(Table.column).one()[0],  # 10:00 AM
        db_session.query(Table.column).one()[1]   # 5:00 PM
    )

现在,您可能不需要每次检查该值时都必须查询数据库,但可以将其缓存几分钟.最简单的方法是使用 cachetools :

Now you may not want to have to query the Database every time you check the value, but maybe cache it for a few minutes. The easiest would be to use cachetools for that:

import cachetools

cache = cachetools.TTLCache(maxsize=10, ttl=60) # Cache for 60 seconds

@cachetools.cached(cache)
def opening_hours():
    return (
        db_session.query(Table.column).one()[0],  # 10:00 AM
        db_session.query(Table.column).one()[1]   # 5:00 PM
    )

此外,由于您使用的是Flask,因此您可以创建路由装饰器,以根据当天的视图来控制对视图的访问

Also, since you are using Flask, you can create a route decorator that controls access to your views depending on the view of the day

from datetime import datetime, time
from functools import wraps
from flask import g, request, render_template

def only_within_office_hours(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        start_time, stop_time = opening_hour()
        if start_time <= datetime.now().time() <= stop_time:
            return render_template('office_hours_error.html')
        return f(*args, **kwargs)
    return decorated_function

您可以像

@app.route('/secret_page')
@login_required
@only_within_office_hours
def secret_page():
    pass

这篇关于flask如何使数据库查询引用保持最新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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