Skip to content

Commit 906877a

Browse files
upgrading docs
1 parent b2cc01f commit 906877a

File tree

10 files changed

+241
-12
lines changed

10 files changed

+241
-12
lines changed

.env.example

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
SECRET_KEY="your_secret_key_here"

.gitignore

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,5 @@ dmypy.json
128128
# Pyre type checker
129129
.pyre/
130130
test.db
131-
migrations/
132131

133132
.vscode

README.md

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,16 +17,40 @@ Flask API using JWT token
1717

1818
- Install all the dependencies
1919

20+
```bash
21+
python -m pip install -r requirements.txt
22+
```
23+
24+
- Add your secret key in `.env.example` and save as it `.env`.
25+
26+
- Load Environment variable
27+
28+
```bash
29+
# linux
30+
> export FLASK_APP=manage
31+
> export FLASK_ENV=development
32+
```
33+
34+
```cmd
35+
# windows powershell
36+
> $env:FLASK_APP=manage
37+
> $env:FLASK_ENV=development
38+
```
39+
40+
Get more details about the flask env check docs [here](https://flask.palletsprojects.com/en/1.1.x/cli/)
41+
2042
- Migrate the database
2143

2244
```bash
23-
$ python manage.py db init
24-
$ python manage.py db migrate
25-
$ python manage.py db upgrade
45+
> flask db init
46+
> flask db migrate -m "Initial migration."
47+
> flask db upgrade
2648
```
2749

50+
- Run the server
51+
2852
```bash
29-
$ python manage.py runserver
53+
flask run
3054
```
3155

3256
- Create a admin user on `url/user`. Give admin access using sql query
@@ -54,3 +78,4 @@ $ python manage.py runserver
5478
## Upcoming Change in Repo
5579

5680
- Api limiter
81+
- Blog API

manage.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,5 @@
66

77
migrate = Migrate(app, db)
88

9-
manager = Manager(app)
10-
manager.add_command('db', MigrateCommand)
11-
129
if __name__ == '__main__':
13-
manager.run()
10+
app.run()

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: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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,flask_migrate
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+
[logger_flask_migrate]
38+
level = INFO
39+
handlers =
40+
qualname = flask_migrate
41+
42+
[handler_console]
43+
class = StreamHandler
44+
args = (sys.stderr,)
45+
level = NOTSET
46+
formatter = generic
47+
48+
[formatter_generic]
49+
format = %(levelname)-5.5s [%(name)s] %(message)s
50+
datefmt = %H:%M:%S

migrations/env.py

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

src/main.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,3 @@ def delete_todo(current_user, todo_id):
209209
db.session.commit()
210210

211211
return jsonify({'status': f"{todo.todo_name} deleted from db"})
212-
213-
if __name__ == '__main__':
214-
app.run()

0 commit comments

Comments
 (0)