Spaces:
Sleeping
Sleeping
| # 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. |