Skip to content

Commit 74de1ec

Browse files
author
IndominusByte
committed
add example on multiple files
1 parent 679eb1b commit 74de1ec

24 files changed

+496
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ There are:
218218

219219
Optional:
220220
- [Use AuthJWT Without Dependency Injection](/examples/without_dependency.py)
221-
- [On Mutiple Files]()
221+
- [On Mutiple Files](/examples/multiple_files)
222222

223223
## License
224224
This project is licensed under the terms of the MIT license.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
Cython
2+
email-validator
3+
pydantic --no-binary pydantic
4+
SQLAlchemy
5+
databases[sqlite]
6+
bcrypt
7+
uvicorn
8+
python-dotenv
9+
alembic
10+
redis
11+
fastapi
12+
fastapi-jwt-auth
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
DB_URL=sqlite:///./sql.db
2+
REDIS_DB_HOST=localhost
3+
AUTHJWT_BLACKLIST_ENABLED=true
4+
AUTHJWT_SECRET_KEY=secretkey

examples/multiple_files/services/__init__.py

Whitespace-only changes.
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = alembic
6+
7+
# template used to generate migration files
8+
# file_template = %%(rev)s_%%(slug)s
9+
10+
# timezone to use when rendering the date
11+
# within the migration file as well as the filename.
12+
# string value is passed to dateutil.tz.gettz()
13+
# leave blank for localtime
14+
# timezone =
15+
16+
# max length of characters to apply to the
17+
# "slug" field
18+
# truncate_slug_length = 40
19+
20+
# set to 'true' to run the environment during
21+
# the 'revision' command, regardless of autogenerate
22+
# revision_environment = false
23+
24+
# set to 'true' to allow .pyc and .pyo files without
25+
# a source .py file to be detected as revisions in the
26+
# versions/ directory
27+
# sourceless = false
28+
29+
# version location specification; this defaults
30+
# to alembic/versions. When using multiple version
31+
# directories, initial revisions must be specified with --version-path
32+
# version_locations = %(here)s/bar %(here)s/bat alembic/versions
33+
34+
# the output encoding used when revision files
35+
# are written from script.py.mako
36+
# output_encoding = utf-8
37+
38+
sqlalchemy.url =
39+
40+
41+
[post_write_hooks]
42+
# post_write_hooks defines scripts or Python functions that are run
43+
# on newly generated revision scripts. See the documentation for further
44+
# detail and examples
45+
46+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
47+
# hooks=black
48+
# black.type=console_scripts
49+
# black.entrypoint=black
50+
# black.options=-l 79
51+
52+
# Logging configuration
53+
[loggers]
54+
keys = root,sqlalchemy,alembic
55+
56+
[handlers]
57+
keys = console
58+
59+
[formatters]
60+
keys = generic
61+
62+
[logger_root]
63+
level = WARN
64+
handlers = console
65+
qualname =
66+
67+
[logger_sqlalchemy]
68+
level = WARN
69+
handlers =
70+
qualname = sqlalchemy.engine
71+
72+
[logger_alembic]
73+
level = INFO
74+
handlers =
75+
qualname = alembic
76+
77+
[handler_console]
78+
class = StreamHandler
79+
args = (sys.stderr,)
80+
level = NOTSET
81+
formatter = generic
82+
83+
[formatter_generic]
84+
format = %(levelname)-5.5s [%(name)s] %(message)s
85+
datefmt = %H:%M:%S
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
from logging.config import fileConfig
2+
3+
from sqlalchemy import engine_from_config
4+
from sqlalchemy import pool
5+
6+
from alembic import context
7+
8+
import os, sys
9+
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)),"..")
10+
sys.path.append(BASE_DIR)
11+
12+
from config import settings
13+
# this is the Alembic Config object, which provides
14+
# access to the values within the .ini file in use.
15+
config = context.config
16+
config.set_main_option("sqlalchemy.url", settings.db_url)
17+
18+
# Interpret the config file for Python logging.
19+
# This line sets up loggers basically.
20+
fileConfig(config.config_file_name)
21+
22+
# add your model's MetaData object here
23+
# for 'autogenerate' support
24+
# from myapp import mymodel
25+
# target_metadata = mymodel.Base.metadata
26+
from sqlalchemy import MetaData
27+
from models import UserModel
28+
29+
def combine_metadata(*args):
30+
m = MetaData()
31+
for metadata in args:
32+
for t in metadata.tables.values():
33+
t.tometadata(m)
34+
return m
35+
36+
37+
target_metadata = combine_metadata(UserModel.metadata)
38+
# other values from the config, defined by the needs of env.py,
39+
# can be acquired:
40+
# my_important_option = config.get_main_option("my_important_option")
41+
# ... etc.
42+
43+
44+
def run_migrations_offline():
45+
"""Run migrations in 'offline' mode.
46+
47+
This configures the context with just a URL
48+
and not an Engine, though an Engine is acceptable
49+
here as well. By skipping the Engine creation
50+
we don't even need a DBAPI to be available.
51+
52+
Calls to context.execute() here emit the given string to the
53+
script output.
54+
55+
"""
56+
url = config.get_main_option("sqlalchemy.url")
57+
context.configure(
58+
url=url,
59+
target_metadata=target_metadata,
60+
literal_binds=True,
61+
dialect_opts={"paramstyle": "named"},
62+
)
63+
64+
with context.begin_transaction():
65+
context.run_migrations()
66+
67+
68+
def run_migrations_online():
69+
"""Run migrations in 'online' mode.
70+
71+
In this scenario we need to create an Engine
72+
and associate a connection with the context.
73+
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, target_metadata=target_metadata
84+
)
85+
86+
with context.begin_transaction():
87+
context.run_migrations()
88+
89+
90+
if context.is_offline_mode():
91+
run_migrations_offline()
92+
else:
93+
run_migrations_online()
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: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
"""init db
2+
3+
Revision ID: 4e36b7b730e5
4+
Revises:
5+
Create Date: 2020-10-07 17:23:10.739779
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = '4e36b7b730e5'
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('users',
22+
sa.Column('id', sa.Integer(), nullable=False),
23+
sa.Column('username', sa.String(length=100), nullable=False),
24+
sa.Column('email', sa.String(length=100), nullable=False),
25+
sa.Column('password', sa.String(length=100), nullable=False),
26+
sa.Column('role', sa.Integer(), nullable=True),
27+
sa.PrimaryKeyConstraint('id')
28+
)
29+
op.create_index(op.f('ix_users_email'), 'users', ['email'], 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_users_email'), table_name='users')
36+
op.drop_table('users')
37+
# ### end Alembic commands ###
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from fastapi import FastAPI
2+
from database import database
3+
from routers import Users
4+
5+
app = FastAPI()
6+
7+
@app.on_event("startup")
8+
async def startup():
9+
await database.connect()
10+
11+
@app.on_event("shutdown")
12+
async def shutdown():
13+
await database.disconnect()
14+
15+
16+
app.include_router(Users.router, prefix="/users", tags=['users'])

0 commit comments

Comments
 (0)