chatgpt/letters/Flask_and_backend_process.py

63 lines
1.3 KiB
Python

from flask import Flask
import threading
import sqlite3
app = Flask(__name__)
# Create a lock for synchronizing access to the database
lock = threading.Lock()
def my_background_process():
# Acquire the lock
lock.acquire()
# Connect to the in-memory database
conn = sqlite3.connect(':memory:')
c = conn.cursor()
# Create a table in the database
c.execute("CREATE TABLE mytable (col1 INTEGER, col2 TEXT)")
# Write to the database
c.execute("INSERT INTO mytable (col1, col2) VALUES (?, ?)", (value1, value2))
conn.commit()
# Close the connection
conn.close()
# Release the lock
lock.release()
@app.route('/')
def read_from_database():
# Acquire the lock
lock.acquire()
# Connect to the in-memory database
conn = sqlite3.connect(':memory:')
c = conn.cursor()
# Read from the database
c.execute("SELECT * FROM mytable")
rows = c.fetchall()
# Close the connection
conn.close()
# Release the lock
lock.release()
# Return the rows to the client
return rows
if __name__ == '__main__':
# Create a new thread for the background process
thread = threading.Thread(target=my_background_process)
# Start the thread
thread.start()
# Start the Flask app
app.run()