Spaces:
Sleeping
Sleeping
File size: 2,064 Bytes
ba3347a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# import sqlite3
# import os
# from flask import g
# # --- Database Functions ---
# DATABASE = "chat.db"
# def init_db():
# if not os.path.exists(DATABASE):
# with sqlite3.connect(DATABASE) as conn:
# # Assuming schema.sql exists and is correctly defined
# with open("schema.sql", "r") as f:
# conn.executescript(f.read())
# def get_db():
# if "db" not in g:
# g.db = sqlite3.connect(DATABASE)
# g.db.row_factory = sqlite3.Row
# return g.db
# def close_db(e=None):
# db = g.pop("db", None)
# if db is not None:
# db.close()
import sqlite3
import os
# --- Database Constants ---
DATABASE = "/tmp/chat.db"
# --- Database Functions ---
def init_db():
"""Initializes the database if it doesn't exist."""
if not os.path.exists(DATABASE):
# Use a context manager to ensure the connection is closed
with sqlite3.connect(DATABASE) as conn:
# Check if schema.sql exists before trying to open it
if os.path.exists("schema.sql"):
with open("schema.sql", "r") as f:
conn.executescript(f.read())
else:
print("WARNING: schema.sql not found. Database will be created but will be empty.")
# You might want to define the schema here directly if schema.sql is not guaranteed
# For example:
# conn.executescript("""
# CREATE TABLE users (...);
# CREATE TABLE conversations (...);
# CREATE TABLE messages (...);
# """)
def get_db():
"""
Dependency function to get a database connection.
This will be called for each request that needs a DB connection.
"""
db = sqlite3.connect(DATABASE)
db.row_factory = sqlite3.Row
try:
yield db
finally:
db.close()
# The close_db function is no longer needed as the `finally` block in `get_db` handles it. |