I have the following bit of code:
import sqlite3
from flask import Flask
app = Flask(__name__)
db = sqlite3.connect('/etc/db.sqlite')
@app.route('/')
def handle():
# run a query and return a response
if __name__ == '__main__':
app.run('0.0.0.0', 8080, debug=True)
However, when I try to perform some operations on the database object in the request handler, I get the following exception from sqlite3 because it is not a thread-safe library and the query is run from a different thread that Flask spawns, and not from the main thread:
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread.The object was created in thread id 139886422697792 and this is thread id 139886332843776
I am aware that the "proper" way to do this is to have a function to create an instance of the sqlite3.Connection object and store it in the Flask g global, as outlined here: http://flask.pocoo.org/docs/1.0/patterns/sqlite3/. However, when running this application on production, I use gunicorn -w 4 -b 0.0.0.0:8080 app:app, and there it works fine, because the threads are spawned at the beginning in this case.
While the Flask g global method works in all cases, I would really like to avoid the overhead of creating and destroying sqlite3.Connection objects with every request. So, I would like to disable threading in Flask so that the above code can run without causing issues.
However, even when I change the last line of the above code to app.run(..., threaded=False), I am unable to avoid this error. It seems that Flask still spawns a thread for handling requests.
So, how can I disable threading with Flask?