RHO
RHO

Reputation: 51

How can I make my flask + sqlite3 application threadsafe

I am attempting to build a python Flask + sqlite3 application. However I can't make it behave. I'm trying to make it threadsafe and that isn't working. I receive the error below:

resp = conn.execute("SELECT * FROM users")
sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread. The object was created in thread id 2532 and this is thread id 17052.
import sqlite3
from queue import Queue
from threading import Lock
from flask import Flask, redirect

class SQLiteConnectionPool:
    def __init__(self, max_connections=5):
        self.max_connections = max_connections
        self.connections = Queue(maxsize=max_connections)
        self.lock = Lock()

    def get_connection(self):
        with self.lock:
            if self.connections.qsize() < self.max_connections:
                conn = sqlite3.connect("./server/data/database.db")
                self.connections.put(conn)
            return self.connections.get()

    def release_connection(self, conn):
        self.connections.put(conn)


pool = SQLiteConnectionPool()



app = Flask(__name__)
@app.route('/')
def index():
    conn = pool.get_connection()

    resp = conn.execute("SELECT * FROM users")
    print(resp)

    pool.release_connection(conn)
    return redirect("/")


app.run(host="0.0.0.0", port=8080)

Please let me know if this is even possible, and if so, how?

Upvotes: 0

Views: 109

Answers (0)

Related Questions