yusufgundogdu commited on
Commit
5d57d55
·
verified ·
1 Parent(s): 5d11b0a

Update database.py

Browse files
Files changed (1) hide show
  1. database.py +40 -33
database.py CHANGED
@@ -1,38 +1,45 @@
1
  import sqlite3
2
  import os
 
3
 
4
- # Veritabanı dosyasının oluşturulacağı dizin
5
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
6
- DB_NAME = "database.db"
7
- DB_PATH = os.path.join(BASE_DIR, DB_NAME)
 
 
 
8
 
9
- def create_connection():
10
- try:
11
- # Veritabanı dosyasının bulunduğu dizin mevcut değilse oluştur
12
- if not os.path.exists(BASE_DIR):
13
- os.makedirs(BASE_DIR)
14
- conn = sqlite3.connect(DB_PATH)
15
- return conn
16
- except sqlite3.OperationalError as e:
17
- print(f"Veritabanı bağlantısı oluşturulamadı: {e}")
18
- return None
19
 
20
- def create_table():
21
- conn = create_connection()
22
- if conn is not None:
23
- try:
24
- cursor = conn.cursor()
25
- cursor.execute('''
26
- CREATE TABLE IF NOT EXISTS users (
27
- id INTEGER PRIMARY KEY AUTOINCREMENT,
28
- name TEXT NOT NULL,
29
- email TEXT NOT NULL UNIQUE
30
- )
31
- ''')
32
- conn.commit()
33
- except sqlite3.Error as e:
34
- print(f"Tablo oluşturulurken hata oluştu: {e}")
35
- finally:
36
- conn.close()
37
- else:
38
- print("Veritabanı bağlantısı kurulamadığı için tablo oluşturulamadı.")
 
 
 
 
 
 
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()