Skip to content

Commit

Permalink
add example on multiple files
Browse files Browse the repository at this point in the history
  • Loading branch information
IndominusByte committed Oct 7, 2020
1 parent 679eb1b commit 74de1ec
Show file tree
Hide file tree
Showing 24 changed files with 496 additions and 1 deletion.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ There are:

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

## License
This project is licensed under the terms of the MIT license.
12 changes: 12 additions & 0 deletions examples/multiple_files/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Cython
email-validator
pydantic --no-binary pydantic
SQLAlchemy
databases[sqlite]
bcrypt
uvicorn
python-dotenv
alembic
redis
fastapi
fastapi-jwt-auth
4 changes: 4 additions & 0 deletions examples/multiple_files/services/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
DB_URL=sqlite:///./sql.db
REDIS_DB_HOST=localhost
AUTHJWT_BLACKLIST_ENABLED=true
AUTHJWT_SECRET_KEY=secretkey
Empty file.
85 changes: 85 additions & 0 deletions examples/multiple_files/services/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s

# timezone to use when rendering the date
# within the migration file as well as the filename.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =

# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; this defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url =


[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples

# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks=black
# black.type=console_scripts
# black.entrypoint=black
# black.options=-l 79

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
1 change: 1 addition & 0 deletions examples/multiple_files/services/alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
93 changes: 93 additions & 0 deletions examples/multiple_files/services/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context

import os, sys
BASE_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)),"..")
sys.path.append(BASE_DIR)

from config import settings
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option("sqlalchemy.url", settings.db_url)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from sqlalchemy import MetaData
from models import UserModel

def combine_metadata(*args):
m = MetaData()
for metadata in args:
for t in metadata.tables.values():
t.tometadata(m)
return m


target_metadata = combine_metadata(UserModel.metadata)
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.


def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix="sqlalchemy.",
poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
24 changes: 24 additions & 0 deletions examples/multiple_files/services/alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}


def upgrade():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
"""init db
Revision ID: 4e36b7b730e5
Revises:
Create Date: 2020-10-07 17:23:10.739779
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '4e36b7b730e5'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=100), nullable=False),
sa.Column('email', sa.String(length=100), nullable=False),
sa.Column('password', sa.String(length=100), nullable=False),
sa.Column('role', sa.Integer(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_users_email'), table_name='users')
op.drop_table('users')
# ### end Alembic commands ###
16 changes: 16 additions & 0 deletions examples/multiple_files/services/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from fastapi import FastAPI
from database import database
from routers import Users

app = FastAPI()

@app.on_event("startup")
async def startup():
await database.connect()

@app.on_event("shutdown")
async def shutdown():
await database.disconnect()


app.include_router(Users.router, prefix="/users", tags=['users'])
41 changes: 41 additions & 0 deletions examples/multiple_files/services/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from os.path import abspath, dirname, join
from fastapi_jwt_auth import AuthJWT
from datetime import timedelta
from pydantic import BaseSettings
from typing import Literal
from redis import Redis

ENV_FILE = join(dirname(abspath(__file__)),".env")

class Settings(BaseSettings):
db_url: str
redis_db_host: str
authjwt_access_token_expires: timedelta = timedelta(minutes=15)
authjwt_refresh_token_expires: timedelta = timedelta(days=30)
# remember literal type only available for python 3.8
authjwt_blacklist_enabled: Literal['true','false']
authjwt_secret_key: str

class Config:
env_file = ENV_FILE
env_file_encoding = "utf-8"


settings = Settings()

conn_redis = Redis(host=settings.redis_db_host, port=6379, db=0,decode_responses=True)

# You can load env from pydantic or environment variable
@AuthJWT.load_env
def get_setting():
return settings

@AuthJWT.token_in_blacklist_loader
def check_if_token_in_blacklist(decrypted_token):
jti = decrypted_token['jti']
entry = conn_redis.get(jti)
return entry and entry == 'true'


ACCESS_EXPIRES = int(settings.authjwt_access_token_expires.total_seconds())
REFRESH_EXPIRES = int(settings.authjwt_refresh_token_expires.total_seconds())
40 changes: 40 additions & 0 deletions examples/multiple_files/services/controller/UserController.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import bcrypt
from sqlalchemy import select
from fastapi import HTTPException
from models.UserModel import users
from database import database

class UserLogic:
def check_user_password(password: str, hashed_pass: str) -> bool:
return bcrypt.checkpw(password.encode(), hashed_pass.encode())

class UserCrud:
async def create_user(**kwargs) -> int:
email_exists = await UserFetch.filter_by_email(kwargs['email'])
hashed_pass = bcrypt.hashpw(kwargs['password'].encode(), bcrypt.gensalt())
kwargs.update({'password': hashed_pass.decode('utf-8')})
if email_exists is None:
return await database.execute(query=users.insert(),values=kwargs)
raise HTTPException(status_code=400,detail="User already exists")

async def update_user(user_id: int, **kwargs) -> None:
query = users.update().where(users.c.id == user_id).values(**kwargs)
await database.execute(query=query)

async def delete_user(user_id: int) -> int:
user_exists = await UserFetch.filter_by_id(id=user_id)
if user_exists:
return await database.execute(query=users.delete().where(users.c.id == user_id))
raise HTTPException(status_code=400,detail="User not found!")

class UserFetch:
async def all_user() -> users:
return await database.fetch_all(query=select([users]))

async def filter_by_email(email: str) -> users:
query = select([users]).where(users.c.email == email)
return await database.fetch_one(query=query)

async def filter_by_id(id: int) -> users:
query = select([users]).where(users.c.id == id)
return await database.fetch_one(query=query)
Empty file.
6 changes: 6 additions & 0 deletions examples/multiple_files/services/database.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from sqlalchemy import MetaData
from databases import Database
from config import settings

metadata = MetaData()
database = Database(settings.db_url)
10 changes: 10 additions & 0 deletions examples/multiple_files/services/models/UserModel.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from database import metadata
from sqlalchemy import Table, Column, Integer, String

users = Table("users", metadata,
Column('id', Integer, primary_key=True),
Column('username', String(100), nullable=False),
Column('email', String(100), unique=True, index=True, nullable=False),
Column('password', String(100), nullable=False),
Column('role', Integer, default=1)
)
Empty file.
Loading

0 comments on commit 74de1ec

Please sign in to comment.