Skip to content

Commit e6c8fbd

Browse files
committed
Database, Models and Migrations
1 parent 8b0a7f8 commit e6c8fbd

File tree

10 files changed

+269
-1
lines changed

10 files changed

+269
-1
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ __pycache__/
44
*.py[cod]
55
*$py.class
66

7+
blog.db
8+
79
.vscode/
810

911
# C extensions

blog/__init__.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,20 @@
11
from flask import Flask
22

3+
from flask_migrate import Migrate
4+
from flask_sqlalchemy import SQLAlchemy
5+
6+
from config import Config
7+
38
app = Flask(__name__)
9+
app.config.from_object(Config)
10+
11+
db = SQLAlchemy(app)
12+
migrate = Migrate(app, db)
13+
14+
with app.app_context():
15+
if db.engine.url.drivername == 'sqlite':
16+
migrate.init_app(app, db, render_as_batch=True)
17+
else:
18+
migrate.init_app(app, db)
419

5-
from blog import routes
20+
from blog import models, routes

blog/models.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from datetime import datetime
2+
3+
from blog import db
4+
5+
6+
class User(db.Model):
7+
id = db.Column(db.Integer, primary_key=True)
8+
created_at = db.Column(db.DateTime, default=datetime.now)
9+
username = db.Column(db.String(12), unique=True, nullable=False)
10+
email = db.Column(db.String(50), unique=True, nullable=False)
11+
password = db.Column(db.String(250), nullable=False)
12+
posts = db.relationship('Post', backref='author', lazy='dynamic')
13+
14+
15+
class Post(db.Model):
16+
id = db.Column(db.Integer, primary_key=True)
17+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
18+
created_at = db.Column(db.DateTime, default=datetime.now)
19+
title = db.Column(db.String(120), nullable=False)
20+
description = db.Column(db.String(240))
21+
body = db.Column(db.Text(), nullable=False)

config.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import os
2+
3+
basedir = os.path.abspath(os.path.dirname(__file__))
4+
5+
6+
class Config:
7+
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'blog.db')
8+
SQLALCHEMY_TRACK_MODIFICATIONS = False

migrations/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

migrations/alembic.ini

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# template used to generate migration files
5+
# file_template = %%(rev)s_%%(slug)s
6+
7+
# set to 'true' to run the environment during
8+
# the 'revision' command, regardless of autogenerate
9+
# revision_environment = false
10+
11+
12+
# Logging configuration
13+
[loggers]
14+
keys = root,sqlalchemy,alembic
15+
16+
[handlers]
17+
keys = console
18+
19+
[formatters]
20+
keys = generic
21+
22+
[logger_root]
23+
level = WARN
24+
handlers = console
25+
qualname =
26+
27+
[logger_sqlalchemy]
28+
level = WARN
29+
handlers =
30+
qualname = sqlalchemy.engine
31+
32+
[logger_alembic]
33+
level = INFO
34+
handlers =
35+
qualname = alembic
36+
37+
[handler_console]
38+
class = StreamHandler
39+
args = (sys.stderr,)
40+
level = NOTSET
41+
formatter = generic
42+
43+
[formatter_generic]
44+
format = %(levelname)-5.5s [%(name)s] %(message)s
45+
datefmt = %H:%M:%S

migrations/env.py

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
from __future__ import with_statement
2+
3+
import logging
4+
from logging.config import fileConfig
5+
6+
from sqlalchemy import engine_from_config
7+
from sqlalchemy import pool
8+
9+
from alembic import context
10+
11+
# this is the Alembic Config object, which provides
12+
# access to the values within the .ini file in use.
13+
config = context.config
14+
15+
# Interpret the config file for Python logging.
16+
# This line sets up loggers basically.
17+
fileConfig(config.config_file_name)
18+
logger = logging.getLogger('alembic.env')
19+
20+
# add your model's MetaData object here
21+
# for 'autogenerate' support
22+
# from myapp import mymodel
23+
# target_metadata = mymodel.Base.metadata
24+
from flask import current_app
25+
config.set_main_option(
26+
'sqlalchemy.url', current_app.config.get(
27+
'SQLALCHEMY_DATABASE_URI').replace('%', '%%'))
28+
target_metadata = current_app.extensions['migrate'].db.metadata
29+
30+
# other values from the config, defined by the needs of env.py,
31+
# can be acquired:
32+
# my_important_option = config.get_main_option("my_important_option")
33+
# ... etc.
34+
35+
36+
def run_migrations_offline():
37+
"""Run migrations in 'offline' mode.
38+
39+
This configures the context with just a URL
40+
and not an Engine, though an Engine is acceptable
41+
here as well. By skipping the Engine creation
42+
we don't even need a DBAPI to be available.
43+
44+
Calls to context.execute() here emit the given string to the
45+
script output.
46+
47+
"""
48+
url = config.get_main_option("sqlalchemy.url")
49+
context.configure(
50+
url=url, target_metadata=target_metadata, literal_binds=True
51+
)
52+
53+
with context.begin_transaction():
54+
context.run_migrations()
55+
56+
57+
def run_migrations_online():
58+
"""Run migrations in 'online' mode.
59+
60+
In this scenario we need to create an Engine
61+
and associate a connection with the context.
62+
63+
"""
64+
65+
# this callback is used to prevent an auto-migration from being generated
66+
# when there are no changes to the schema
67+
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
68+
def process_revision_directives(context, revision, directives):
69+
if getattr(config.cmd_opts, 'autogenerate', False):
70+
script = directives[0]
71+
if script.upgrade_ops.is_empty():
72+
directives[:] = []
73+
logger.info('No changes in schema detected.')
74+
75+
connectable = engine_from_config(
76+
config.get_section(config.config_ini_section),
77+
prefix='sqlalchemy.',
78+
poolclass=pool.NullPool,
79+
)
80+
81+
with connectable.connect() as connection:
82+
context.configure(
83+
connection=connection,
84+
target_metadata=target_metadata,
85+
process_revision_directives=process_revision_directives,
86+
**current_app.extensions['migrate'].configure_args
87+
)
88+
89+
with context.begin_transaction():
90+
context.run_migrations()
91+
92+
93+
if context.is_offline_mode():
94+
run_migrations_offline()
95+
else:
96+
run_migrations_online()

migrations/script.py.mako

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
${imports if imports else ""}
11+
12+
# revision identifiers, used by Alembic.
13+
revision = ${repr(up_revision)}
14+
down_revision = ${repr(down_revision)}
15+
branch_labels = ${repr(branch_labels)}
16+
depends_on = ${repr(depends_on)}
17+
18+
19+
def upgrade():
20+
${upgrades if upgrades else "pass"}
21+
22+
23+
def downgrade():
24+
${downgrades if downgrades else "pass"}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""Creazione Tabelle Post e User
2+
3+
Revision ID: 4fd5c8b52471
4+
Revises:
5+
Create Date: 2019-05-31 17:59:59.229407
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '4fd5c8b52471'
14+
down_revision = None
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table('user',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('created_at', sa.DateTime(), nullable=True),
24+
sa.Column('username', sa.String(length=12), nullable=False),
25+
sa.Column('email', sa.String(length=50), nullable=False),
26+
sa.Column('password', sa.String(length=250), nullable=False),
27+
sa.PrimaryKeyConstraint('id'),
28+
sa.UniqueConstraint('email'),
29+
sa.UniqueConstraint('username')
30+
)
31+
op.create_table('post',
32+
sa.Column('id', sa.Integer(), nullable=False),
33+
sa.Column('user_id', sa.Integer(), nullable=False),
34+
sa.Column('created_at', sa.DateTime(), nullable=True),
35+
sa.Column('title', sa.String(length=120), nullable=False),
36+
sa.Column('description', sa.String(length=240), nullable=True),
37+
sa.Column('body', sa.Text(), nullable=False),
38+
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
39+
sa.PrimaryKeyConstraint('id')
40+
)
41+
# ### end Alembic commands ###
42+
43+
44+
def downgrade():
45+
# ### commands auto generated by Alembic - please adjust! ###
46+
op.drop_table('post')
47+
op.drop_table('user')
48+
# ### end Alembic commands ###

requirements.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,15 @@
1+
alembic==1.0.10
12
Click==7.0
23
Flask==1.0.3
4+
Flask-Migrate==2.5.2
5+
Flask-SQLAlchemy==2.4.0
36
itsdangerous==1.1.0
47
Jinja2==2.10.1
8+
Mako==1.0.10
59
MarkupSafe==1.1.1
10+
python-dateutil==2.8.0
611
python-dotenv==0.10.2
12+
python-editor==1.0.4
13+
six==1.12.0
14+
SQLAlchemy==1.3.4
715
Werkzeug==0.15.4

0 commit comments

Comments
 (0)