Files
flask-files/files/db.py
2019-03-09 02:44:17 -03:00

78 lines
1.7 KiB
Python

import sqlite3
import click
from flask import current_app, g
from flask.cli import with_appcontext
from werkzeug.security import generate_password_hash
def get_db():
if 'db' not in g:
g.db = sqlite3.connect(
current_app.config['DATABASE'],
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()
def init_db():
db = get_db()
with current_app.open_resource('schema.sql') as f:
db.executescript(f.read().decode('utf8'))
def generate_admin():
db = get_db()
username = current_app.config['USERNAME']
password = current_app.config['PASSWORD']
db.execute(
'INSERT INTO users (username, password) VALUES (?, ?)',
(username, generate_password_hash(password),)
)
db.commit()
def generate_files():
pass
@click.command('init-db')
@with_appcontext
def init_db_command():
"""Inits the database with it's schema"""
init_db()
click.echo('The database was initialized')
@click.command('generate-admin')
@with_appcontext
def generate_admin_command():
"""Creates the admin of the system"""
generate_admin()
click.echo('The admin was created')
@click.command('generate-files')
@with_appcontext
def generate_files_command():
"""
Generates the rows in the database for the files currently uploaded
They all will have default privacy, so, public
"""
generate_files()
click.echo('files generated')
def init_app(app):
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command)
app.cli.add_command(generate_admin_command)