Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

sqlite3 in asynchronous program with to_thread raises SystemErrors

$
0
0

I created a class that handles my sqlite database in python. This is written in synchronous code. Now, I want to use this code in an asynchronous program.I used asyncio.to_thread to execute a database insert asynchronously.However, I get different SystemError messages everytime I run my code.

Below, you find a minimal example which raises System errors.

There are easy workarounds to this, but I thought sqlite was threadsafe?It took me a while to isolate the problem and I want to understand what is wrong, so I don't run into the same problems later on.I use python3.11 and sqlite3 version=2.6 and sqlite3.threadsafe is 3

import asyncioimport sqlite3from pathlib import PathPath("test.db").unlink(missing_ok=True)con = sqlite3.connect("test.db", check_same_thread=False)def init():    con.execute("""CREATE TABLE test (test INTEGER NOT NULL);""")async def write():    while True:        with con:            con.execute("""INSERT INTO test VALUES (1) """)        await asyncio.sleep(0)async def write2():    while True:        await asyncio.to_thread(write3)def write3():    with con:        con.execute("""INSERT INTO test VALUES (2) """)if __name__ == "__main__":    init()    loop = asyncio.get_event_loop()    try:        loop.create_task(write())        loop.create_task(write2())        loop.run_forever()    finally:        con.commit()        con.close()        loop.close()

Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>