Files
propedal-planner/db.py
2024-06-23 21:20:03 +02:00

64 lines
1.8 KiB
Python

import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
def get_db(mod_path=None):
if 'db' not in g:
# provide modified path if is not None
if mod_path is None:
path=current_app.config["DATABASE_URI"]
else:
path=mod_path
g.db = sqlite3.connect(
path,
detect_types=sqlite3.PARSE_DECLTYPES
)
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()
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Clear the existing data and create new tables."""
path = "./users.db"
db = get_db(mod_path="users.db")
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
click.echo('Initialized the database at %s. Copy it to the according directory.'% path)
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
if __name__ == "__main__":
import csv
from datetime import datetime
# Connect to the SQLite database
conn = sqlite3.connect('users.db')
c = conn.cursor()
# Load data from CSV file
with open('users.db.backup.txt', 'r') as csvfile:
reader = csv.reader(csvfile, delimiter='|')
for row in reader:
username, email, password, confirmed, confirmation_date = row[1:] #drop first col
c.execute("INSERT INTO user (username, email, password, confirmed, confirmation_date) VALUES (?, ?, ?, ?, ?)",
(username.strip(), email.strip(), password, int(confirmed), datetime.strptime(confirmation_date, '%Y-%m-%d %H:%M:%S.%f')))
# Commit the changes and close the connection
conn.commit()
conn.close()