Skip to content

Commit 0a0701e

Browse files
db added, models added, configuration updated
1 parent 6215aef commit 0a0701e

17 files changed

+280
-3
lines changed

__pycache__/config.cpython-38.pyc

215 Bytes
Binary file not shown.

app.db

32 KB
Binary file not shown.

app/__init__.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
from flask import Flask
22
from config import Config
3+
from flask_sqlalchemy import SQLAlchemy
4+
from flask_migrate import Migrate
35

46
app = Flask(__name__)
57
app.config.from_object(Config)
8+
db = SQLAlchemy(app)
9+
migrate = Migrate(app, db)
610

7-
from app import routes
11+
from app import routes, models
812

148 Bytes
Binary file not shown.

app/__pycache__/models.cpython-38.pyc

1.23 KB
Binary file not shown.

app/models.py

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from app import db
2+
from datetime import datetime
3+
4+
class User(db.Model):
5+
id = db.Column(db.Integer, primary_key = True)
6+
username = db.Column(db.String(64), index = True, unique = True)
7+
email = db.Column(db.String(120),index = True, unique = True)
8+
password_hash = db.Column(db.String(128))
9+
posts = db.relationship('Post', backref = 'author', lazy = 'dynamic')
10+
11+
def __repr__(self):
12+
return '<User {}>'.format(self.username)
13+
14+
class Post(db.Model):
15+
id = db.Column(db.Integer, primary_key = True)
16+
caption = db.Column(db.String(150))
17+
timestamp = db.Column(db.DateTime, index = True, default = datetime.utcnow)
18+
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
19+
20+
def __repr__(self):
21+
return '<Post {}>'.format(self.body)

config.py

+6-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,9 @@
11
import os
2+
basedir = os.path.abspath(os.path.dirname(__file__))
23

34
class Config(object):
4-
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hello111'
5+
SECRET_KEY = os.environ.get('SECRET_KEY') or 'hello111'
6+
SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') or \
7+
'sqlite:///' + os.path.join(basedir,'app.db')
8+
9+
SQLALCHEMY_TRACK_MODIFICATIONS = False

microblog.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
1-
from app import app
1+
from app import app, db
2+
from app.models import User, Post
23

4+
@app.shell_context_processor
5+
def make_shell_context():
6+
return {'db':db, 'User' : User, 'Post' : Post}
7+
8+

migrations/README

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.
2.23 KB
Binary file not shown.

migrations/alembic.ini

+45
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

+96
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',
27+
str(current_app.extensions['migrate'].db.engine.url).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

+24
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"}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
"""users table
2+
3+
Revision ID: 1248a02332e6
4+
Revises:
5+
Create Date: 2020-04-01 03:19:13.195378
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '1248a02332e6'
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('username', sa.String(length=64), nullable=True),
24+
sa.Column('email', sa.String(length=120), nullable=True),
25+
sa.Column('password_hash', sa.String(length=128), nullable=True),
26+
sa.PrimaryKeyConstraint('id')
27+
)
28+
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
29+
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
30+
# ### end Alembic commands ###
31+
32+
33+
def downgrade():
34+
# ### commands auto generated by Alembic - please adjust! ###
35+
op.drop_index(op.f('ix_user_username'), table_name='user')
36+
op.drop_index(op.f('ix_user_email'), table_name='user')
37+
op.drop_table('user')
38+
# ### end Alembic commands ###
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""posts table
2+
3+
Revision ID: 3666a9cbfb06
4+
Revises: 1248a02332e6
5+
Create Date: 2020-04-01 03:56:29.842307
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '3666a9cbfb06'
14+
down_revision = '1248a02332e6'
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('post',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('caption', sa.String(length=150), nullable=True),
24+
sa.Column('timestamp', sa.DateTime(), nullable=True),
25+
sa.Column('user_id', sa.Integer(), nullable=True),
26+
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
27+
sa.PrimaryKeyConstraint('id')
28+
)
29+
op.create_index(op.f('ix_post_timestamp'), 'post', ['timestamp'], unique=False)
30+
# ### end Alembic commands ###
31+
32+
33+
def downgrade():
34+
# ### commands auto generated by Alembic - please adjust! ###
35+
op.drop_index(op.f('ix_post_timestamp'), table_name='post')
36+
op.drop_table('post')
37+
# ### end Alembic commands ###
Binary file not shown.
Binary file not shown.

0 commit comments

Comments
 (0)