I've noticed that SQLite db.commit()
(save to disk) takes between 50ms and 100ms with my small database. This is normal and documented here, but it's too much to do it after each request of a client / after each INSERT like this:
import bottle, sqlite3, random
@bottle.route('/')
def index():
c = db.cursor()
c.execute('INSERT INTO test VALUES (?)', (random.randint(0, 10000)))
c.close()
db.commit() # should we do it here? (100ms is too much after *each* request!)
return 'hello'
def worker():
db.commit() # or here? how to call this worker once every 10 seconds?
db = sqlite3.connect('test.db')
db.execute("CREATE TABLE IF NOT EXISTS test (a int)")
bottle.run(port=80)
More precisely I don't want to lose 100ms after each request: I optimized my server to serve pages very fast (10ms), and it would be a shame to lose 100ms because of DB commit.
Of course I could start a new thread to call worker()
only once every 10 seconds (in the worst case, if the app crashes, only the 10 last seconds of DB will be lost). But I read it's not recommended to use threads in this context.
Question: how to do a SQLite DB commit once every few seconds only (instead of once after each INSERT) in a Bottle/Flask webserver context?