Python Flask只运行一次代码

时间:2014-12-19 06:41:19

标签: python flask global-variables

我正在尝试设置一个全局变量,如:

    # -*- coding: utf8 -*-
from flask import Flask, render_template,redirect,flash, url_for, session, request
from sqlalchemy.sql import text
from sqlalchemy.orm import aliased, Query
from sqlalchemy import exc
from flask_bootstrap import Bootstrap
from .forms import *


import zlib
#from sqlalchemy.orm.query import limit, order_by
from dbmodel import *


app = Flask(__name__)
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
Bootstrap(app)

MAX_ITEMS=50
MAX_ZIPS=5
MAX_ORDERS=20


clientMaxSQL="SELECT * FROM CLIENT WHERE 1"

engine, dbsession = dbconnect() 

@app.route("/clientRegister",methods=['GET', 'POST'])
def clientRegister():
        form = ClientQuery()

        global clientMaxSQL
        flash('maxSql at start %s ' %(clientMaxSQL))
        if form.reset.data == "True":
                flash('RESET TABLE FILTERS')
                clientMaxSQL="SELECT * FROM CLIENT WHERE 1"

        sql = clientMaxSQL
        if form.validate_on_submit():
                if len(form.compareVal.data.strip()) > 0 and ( any(c.isalpha() for c in form.compareVal.data) or any(c.isdigit() for c in form.compareVal.data)):
                        sql = sql + " AND " + form.columnSelection.data + form.comparisonSelection.data + "'" +form.compareVal.data+"'"

        start=int(request.args.get('start', '0'))
        prev=start-MAX_ITEMS
        nextStart = start + MAX_ITEMS
        tmpSQL = clientMaxSQL
        clientMaxSQL = sql
        sql = sql + " LIMIT " + str(start)+","+str(nextStart)
        try:
                clients = engine.execute(sql)
                maxStart=engine.execute(clientMaxSQL).rowcount
                flash('Attempting Query: %s' %(sql))
        except:
                flash('Invalid Comparison of %s' %(form.compareVal.data))
                sql = tmpSQL + " LIMIT " + str(start)+","+str(nextStart)
                clientMaxSQL=tmpSQL
                clients = engine.execute(sql)
                maxStart=engine.execute(clientMaxSQL)
        flash('maxSql at end %s ' %(clientMaxSQL))
        return render_template("clientRegister.html",form=form,maxStart=maxStart,clients=clients,start=start, prev=prev,nextStart=nextStart)

我得到了一些奇怪的结果。看起来这个语句(在我的所有函数定义之上声明)似乎每隔一段时间就会执行一次。这可能吗?我的网络应用程序必须只运行一次,否则我将丢失查询的当前状态。

添加了程序中所有更改变量的代码。它正在自行重置。

1 个答案:

答案 0 :(得分:0)

使用带有该函数的@app.before_first_request装饰器使其仅运行一次

如:

@app.before_first_request
def function_to_run_only_once():
     #your statement(s)

这应确保您的所述陈述仅在程序的整个生命周期内执行一次