The first problem is the acquisition of compounds, even if they are not needed. The second one has a drawback in the game with internal components of a third-party structure, plus it is quite unreadable.
Of the two, only one, the second is probably the best choice. Not only does it not get a connection for routes that don't need it, it doesn't get a connection if you go on any code path that it doesn't need, even if other code paths on the route require one. (For example, if you have some form of verification, you only need a connection, if the verification passes, it will not open it when the verification fails.) You only get the connections right before you use them with this setting.
However, you can avoid messing around with the internal elements and get all these benefits. Personally, I created my own global methods:
import flask import sqlite3 def request_has_connection(): return hasattr(flask.g, 'dbconn') def get_request_connection(): if not request_has_connection(): flask.g.dbconn = sqlite3.connect(DATABASE)
Then, throughout the application, always get your connection through get_request_connection , just like your get_db function. Simple and high performance. In principle, the best of both worlds.
Edit:
In retrospect, I really don't like the fact that these are global methods, but I think the reason for this is because Flask works this way: it gives you “global” ones that actually point to stream locators.
jpmc26 May 17 '13 at 4:42 2013-05-17 04:42
source share