Create database.py
Browse files- database.py +28 -25
database.py
CHANGED
|
@@ -1,37 +1,40 @@
|
|
| 1 |
import sqlite3
|
|
|
|
| 2 |
from flask import g
|
| 3 |
|
|
|
|
|
|
|
|
|
|
| 4 |
def get_db():
|
| 5 |
-
"""Veritabanı bağlantısını oluşturur veya var olanı döndürür"""
|
| 6 |
if 'db' not in g:
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
| 9 |
return g.db
|
| 10 |
|
| 11 |
def close_db(e=None):
|
| 12 |
-
"""Veritabanı bağlantısını kapatır"""
|
| 13 |
db = g.pop('db', None)
|
| 14 |
if db is not None:
|
| 15 |
db.close()
|
| 16 |
|
| 17 |
-
def init_db():
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
db.commit()
|
|
|
|
| 1 |
import sqlite3
|
| 2 |
+
import os
|
| 3 |
from flask import g
|
| 4 |
|
| 5 |
+
def get_db_path():
|
| 6 |
+
return os.getenv('DATABASE_PATH', 'users.db')
|
| 7 |
+
|
| 8 |
def get_db():
|
|
|
|
| 9 |
if 'db' not in g:
|
| 10 |
+
db_path = get_db_path()
|
| 11 |
+
# Dizin yoksa oluştur
|
| 12 |
+
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
| 13 |
+
g.db = sqlite3.connect(db_path)
|
| 14 |
+
g.db.row_factory = sqlite3.Row
|
| 15 |
return g.db
|
| 16 |
|
| 17 |
def close_db(e=None):
|
|
|
|
| 18 |
db = g.pop('db', None)
|
| 19 |
if db is not None:
|
| 20 |
db.close()
|
| 21 |
|
| 22 |
+
def init_db(app):
|
| 23 |
+
with app.app_context():
|
| 24 |
+
db = get_db()
|
| 25 |
+
cursor = db.cursor()
|
| 26 |
+
|
| 27 |
+
cursor.execute('''
|
| 28 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 29 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 30 |
+
name TEXT NOT NULL,
|
| 31 |
+
score INTEGER DEFAULT 0
|
| 32 |
+
)
|
| 33 |
+
''')
|
| 34 |
+
|
| 35 |
+
cursor.execute('SELECT COUNT(*) FROM users')
|
| 36 |
+
if cursor.fetchone()[0] == 0:
|
| 37 |
+
cursor.executemany('INSERT INTO users (name, score) VALUES (?, ?)',
|
| 38 |
+
[('Ahmet', 85), ('Mehmet', 92)])
|
| 39 |
+
|
| 40 |
+
db.commit()
|
|
|
|
|
|