Commit 6ed2088e authored by berumuron's avatar berumuron
Browse files

Initialize the SQLite database

parent 8587220a
__pycache__
/env
/instance
......@@ -4,6 +4,10 @@
dep: ## Install the dependencies
python3 -m pip install -r requirements.txt
.PHONY: db-setup
db-setup: ## Initialize the database
FLASK_APP=src FLASK_ENV=development flask db-init
.PHONY: run
run: ## Run the application binary
FLASK_APP=src FLASK_ENV=development flask run
......
......@@ -83,6 +83,17 @@ Si vous disposez de la commande `make` sur votre PC, vous pouvez aussi utiliser
reflets$ make dep
```
## Initialiser la base de données
Avant de lancer l'application, il est nécessaire d'initialiser la base de
données avec :
```console
reflets$ FLASK_APP=src FLASK_ENV=development flask db-init
reflets$ # ou avec la commande make
reflets$ make db-setup
```
## Lancer l'application (développement)
Une fois les dépendances installées, pour lancer l'application, exécutez la
......
import os
from flask import Flask, render_template
from . import cli, db
__version__ = "0.1.0"
app = Flask(__name__)
def create_app():
app = Flask(__name__, instance_relative_config=True)
app.config.from_mapping(DATABASE=os.path.join(app.instance_path, "db.sqlite"))
try:
os.makedirs(app.instance_path)
except FileExistsError:
pass
# Register commands and teardowns to the app.
cli.init_app(app)
db.init_app(app)
# Define a default basic route (it will be improved later).
@app.route("/")
def index():
return render_template("index.html")
@app.route("/")
def index():
return render_template("index.html")
return app
import click
from flask.cli import with_appcontext
from . import db
@click.command("db-init")
@with_appcontext
def db_init_command():
"""Clear the existing data and create new tables."""
db.init_db()
click.echo("Database initialized.")
def init_app(app):
"""Register CLI commands to the application."""
app.cli.add_command(db_init_command)
import sqlite3
from flask import current_app, g
def get_db():
"""Return the app database."""
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 init_db():
"""Initialize the database with the src/schema.sql file."""
db = get_db()
with current_app.open_resource("schema.sql") as f:
db.executescript(f.read().decode("utf8"))
def close_db(e=None):
"""Close the app database (it should not be called directly)."""
db = g.pop("db", None)
if db is not None:
db.close()
def init_app(app):
"""Register the db closing on app teardown."""
app.teardown_appcontext(close_db)
DROP TABLE IF EXISTS users;
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
);
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment