Safe database query (peewee) from thread Flask


I have couple of simple tasks which could take maximum 20 seconds to complete, so I decided to use separate thread to accomplish them. I want thread to do the job and update database with result.

While it works (no exceptions yet) I have lack of understanding Flask internals and how it works with WSGI server. I’m not quite sure that on some amount of parallel requests it won’t end with some database access error.

Simplified code:

from time import time, sleep
from threading import Thread
from peewee import *
from playhouse.shortcuts import model_to_dict
from flask import Flask, abort, jsonify

db = SqliteDatabase("test.db")

class Task(Model):
    status = IntegerField(default=0)
    result = TextField(null=True)

    class Meta:
        database = db

def do_smth(task_id):
    start = time()
    Task.update({Task.status: 1, Task.result: f"{start} - {time()}"})\
        .where( == task_id).execute()

def new_task():
        task = Task.create()
    except IntegrityError:
        Thread(target=do_smth, args=(,)).start()

        return jsonify(model_to_dict(task))

def get_task(task_id):
        task = Task.get( == task_id)
    except Task.DoesNotExist:
        return jsonify(model_to_dict(task))

def before_request():

def after_request(response):
    return response

if __name__ == "__main__":
    with db:
        db.create_tables([Task])"", port=5000)

As it suggested in peewee tutorial I added custom Flask.before_request and Flask.after_request which open and close database connection.

So the question is how to update database from separate thread safely? I have had an idea to add route which will update database and send request from thread, but I find it kinda dumb.

P.S. I’ve tried my best trying to be precise, but if something is unclear I will try to clarify it, just ask it in comments section.


This is a good question:

how to update database from separate thread safely?

With Sqlite you have to remember that it only allows one writer at a time. So you have to manage your connections carefully to ensure that you are only doing a write txn when you have to, and that you’re committing it as soon as you’re done with it.

Since you’re opening and closing the DB during the lifetime of a request, and running your DB operations in separate thread(s), you should be OK for a smallish number of operations (100?). I think the main thing I’d be careful about is, during your task body, be sure you’re only holding that write txn open for as short a time as possible:

def do_smth(task_id):
    # open a database connection. it will be read-only for now.
    with db.connection_context():
        start = time()
        with db.atomic() as txn:  # here is write tx, keep this brief!
            Task.update({Task.status: 1, Task.result: f"{start} - {time()}"})\
                .where( == task_id).execute()

See the first section on transactions:

For a more drastic approach, you can try this:

Answered By – coleifer

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published