Application Context & Best Practices
- Rich W
- 2014-06-26 @ 00:27
I'm currently writing my first Flask application. I'm liking what I've
seen of it so far.
My site uses a SQLite database containing a single table which is to be
used on every request. It's only ever used for reading, never writing.
The recent Python 3.4 added a way to open a SQLite database as read only
but as I'm using Python 2.7, Python itself isn't aware of this.
The data within it could probably work simply as a large dict but due to
ease of management and a performance increase I suspect, I've elected to
use SQLite. Using a real client-server based database engine would be
overkill for what I need it for.
The Flask homepage has an article regarding SQLite. From my understanding
of it, every time a database connection is requested using get_db() in a
request, it'll create one unless it's been created already. In my case, as
every page will be using it and since it won't be writing, would it be
best to leave the connection open for the entire duration that Flask is
As SQLite has no connection pool, I thinking that there may be a
performance hit every time the database is opened, loading its index into
memory and such.
The second part of my question is, if so, where exactly should I do this?
I can put it outside of Flask altogether but from what I've read, the
right thing to do is place it in the application context I think. This is
what the SQLite article is using but on the same page, it mentions I can
also use it by 'with app.app_context():'
After I create my Flask object, I make use of it like such;
app = Flask(__name__)with app.app_context(): try: DB =
sqlite3.connect(DatabaseFile) except Exception: raise
Is the right way to make use of it, and am I correct in assuming that it
remains open for the duration of Flask this way? I couldn't find many
examples 'with app.app_context():' being used this way.
Thanks to any replies. Hopefully my question isn't too dumb.