Browse Source

Adds db connection script and schema

Jose Reyes 5 years ago
parent
commit
ecc4a4f67a
2 changed files with 56 additions and 0 deletions
  1. 38
    0
      flaskr/db.py
  2. 18
    0
      flaskr/schema.sql

+ 38
- 0
flaskr/db.py View File

@@ -0,0 +1,38 @@
1
+import sqlite3
2
+
3
+import click
4
+from flask import current_app, g
5
+from flask.cli import with_appcontext
6
+
7
+def get_db():
8
+    if 'db' not in g:
9
+        g.db = sqlite3.connect(
10
+                current_app.config['DATABASE'],
11
+                detect_types=sqlite3.PARSE_DECLTYPES
12
+        )
13
+        g.db.row_factory = sqlite3.Row
14
+
15
+    return g.db
16
+
17
+def close_db(e=None):
18
+    db = g.pop('db', None)
19
+
20
+    if db is not None:
21
+        db.close()
22
+
23
+def init_db():
24
+    db = get_db()
25
+
26
+    with current_app.open_resource('schema.sql') as f:
27
+        db.executescript(f.read().decode('utf8'))
28
+
29
+@click.command('init-db')
30
+@with_appcontext
31
+def init_db_command():
32
+    init_db()
33
+    click.echo('Initialized the database.')
34
+
35
+def init_app(app):
36
+    app.teardown_appcontext(close_db)
37
+    app.cli.add_command(init_db_command)
38
+

+ 18
- 0
flaskr/schema.sql View File

@@ -0,0 +1,18 @@
1
+DROP TABLE IF EXISTS user;
2
+DROP TABLE IF EXISTS post;
3
+
4
+CREATE TABLE user (
5
+    id INTEGER PRIMARY KEY AUTOINCREMENT,
6
+    username TEXT UNIQUE NOT NULL,
7
+    password TEXT NOT NULL
8
+);
9
+
10
+CREATE TABLE post (
11
+    id INTEGER PRIMARY KEY AUTOINCREMENT,
12
+    author_id INTEGER NOT NULL,
13
+    created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
14
+    title TEXT NOT NULL,
15
+    body TEXT NOT NULL,
16
+    FOREIGN KEY (author_id) REFERENCES user (id)
17
+);
18
+