Update database.py
Browse files- database.py +40 -33
database.py
CHANGED
|
@@ -1,38 +1,45 @@
|
|
| 1 |
import sqlite3
|
| 2 |
import os
|
|
|
|
| 3 |
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
def
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
print(f"Veritabanı bağlantısı oluşturulamadı: {e}")
|
| 18 |
-
return None
|
| 19 |
|
| 20 |
-
def
|
| 21 |
-
|
| 22 |
-
if
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import sqlite3
|
| 2 |
import os
|
| 3 |
+
from flask import g
|
| 4 |
|
| 5 |
+
def get_db_path():
|
| 6 |
+
# Hugging Face Spaces için özel yol kontrolü
|
| 7 |
+
if os.path.exists('/data'):
|
| 8 |
+
return '/data/database.db' # users.db → database.db
|
| 9 |
+
elif os.path.exists('/home/user_data'):
|
| 10 |
+
return '/home/user_data/database.db' # users.db → database.db
|
| 11 |
+
return 'database.db' # users.db → database.db
|
| 12 |
|
| 13 |
+
def get_db():
|
| 14 |
+
if 'db' not in g:
|
| 15 |
+
db_path = get_db_path()
|
| 16 |
+
# Dizin yoksa oluştur
|
| 17 |
+
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
| 18 |
+
g.db = sqlite3.connect(db_path)
|
| 19 |
+
g.db.row_factory = sqlite3.Row
|
| 20 |
+
return g.db
|
|
|
|
|
|
|
| 21 |
|
| 22 |
+
def close_db(e=None):
|
| 23 |
+
db = g.pop('db', None)
|
| 24 |
+
if db is not None:
|
| 25 |
+
db.close()
|
| 26 |
+
|
| 27 |
+
def init_db(app):
|
| 28 |
+
with app.app_context():
|
| 29 |
+
db = get_db()
|
| 30 |
+
cursor = db.cursor()
|
| 31 |
+
|
| 32 |
+
cursor.execute('''
|
| 33 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 34 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 35 |
+
name TEXT NOT NULL,
|
| 36 |
+
score INTEGER DEFAULT 0
|
| 37 |
+
)
|
| 38 |
+
''')
|
| 39 |
+
|
| 40 |
+
cursor.execute('SELECT COUNT(*) FROM users')
|
| 41 |
+
if cursor.fetchone()[0] == 0:
|
| 42 |
+
cursor.executemany('INSERT INTO users (name, score) VALUES (?, ?)',
|
| 43 |
+
[('Ahmet', 85), ('Mehmet', 92)])
|
| 44 |
+
|
| 45 |
+
db.commit()
|