python - Preserving state in mod_wsgi Flask application -
i have flask application running under mod_wsgi makes connection database. there multiple processes running application (only 1 thread per process) , 1 database connection each of these processes.
currently have this:
myapp_wsgi.py
import myapp app = myapp.setup() def application(environ, start_response): homecoming app(environ, start_response) myapp.py
from flask import flask app = flask(__name__) db = none def setup(): global db db = get_db() # other setup homecoming app @app.route("/") def index(): info = db.get_data() homecoming info now utilize of global variables here doesn't sense good. if app class, utilize self.db, it's not. there better, more pythonic, more flask-esque way this?
this suppose depend on database (and orm) you're using with. if you're using sqlalchemy or flask-sqlalchemy, (which highly suggest do), define single global variable database connection. set in init_app()-function. if @ application set code, you'll see quite main flask application object global variable app. you'll find database object global variable db imported app other parts of application.
you should @ application , request-context documentation , locality of context, explains how works. context never shared between requests (and threads), there should no race conditions , no problems.
also, global keyword in case not necessary. point never alter content of variable db. it's object controls database connection , phone call methods offers. global keyword necessary when want mutate contents of variable, assigning new value it.
so, refactor setup() follows (and preferrably set __init__.py it's nicely importable)
from flask import flask def setup(): app = flask(__name__) db = get_db() #this local variable # whatever else needs done homecoming app, db app, db = setup() and in mod_wsgi.py
from myapp import app def application(environ, start_response): homecoming app(environ, start_response) python flask mod-wsgi
No comments:
Post a Comment