Skip to content

Commit

Permalink
adding async sqlalchemy as of: fastapi#359
Browse files Browse the repository at this point in the history
  • Loading branch information
Yassine Elassad committed Mar 30, 2023
1 parent 490c554 commit 6631a72
Show file tree
Hide file tree
Showing 25 changed files with 347 additions and 272 deletions.
32 changes: 20 additions & 12 deletions {{cookiecutter.project_slug}}/backend/app/alembic/env.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from __future__ import with_statement

import asyncio
import os

from alembic import context
from sqlalchemy import engine_from_config, pool
from sqlalchemy.ext.asyncio import AsyncEngine
from logging.config import fileConfig

# this is the Alembic Config object, which provides
Expand Down Expand Up @@ -35,7 +37,7 @@ def get_url():
password = os.getenv("POSTGRES_PASSWORD", "")
server = os.getenv("POSTGRES_SERVER", "db")
db = os.getenv("POSTGRES_DB", "app")
return f"postgresql://{user}:{password}@{server}/{db}"
return f"postgresql+asyncpg://{user}:{password}@{server}/{db}"


def run_migrations_offline():
Expand All @@ -59,7 +61,16 @@ def run_migrations_offline():
context.run_migrations()


def run_migrations_online():
def do_run_migrations(connection):
context.configure(
connection=connection, target_metadata=target_metadata, compare_type=True
)

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


async def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
Expand All @@ -68,20 +79,17 @@ def run_migrations_online():
"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata, compare_type=True
connectable = AsyncEngine(
engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool, future=True,
)
)

with context.begin_transaction():
context.run_migrations()
async with connectable.connect() as connection:
await connection.run_sync(do_run_migrations)


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
asyncio.run(run_migrations_online())
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Any, List

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, models, schemas
from app.api import deps
Expand All @@ -10,8 +10,8 @@


@router.get("/", response_model=List[schemas.Item])
def read_items(
db: Session = Depends(deps.get_db),
async def read_items(
db: AsyncSession = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
current_user: models.User = Depends(deps.get_current_active_user),
Expand All @@ -20,59 +20,61 @@ def read_items(
Retrieve items.
"""
if crud.user.is_superuser(current_user):
items = crud.item.get_multi(db, skip=skip, limit=limit)
items = await crud.item.get_multi(db, skip=skip, limit=limit)
else:
items = crud.item.get_multi_by_owner(
items = await crud.item.get_multi_by_owner(
db=db, owner_id=current_user.id, skip=skip, limit=limit
)
return items


@router.post("/", response_model=schemas.Item)
def create_item(
async def create_item(
*,
db: Session = Depends(deps.get_db),
db: AsyncSession = Depends(deps.get_db),
item_in: schemas.ItemCreate,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Create new item.
"""
item = crud.item.create_with_owner(db=db, obj_in=item_in, owner_id=current_user.id)
item = await crud.item.create_with_owner(
db=db, obj_in=item_in, owner_id=current_user.id
)
return item


@router.put("/{id}", response_model=schemas.Item)
def update_item(
async def update_item(
*,
db: Session = Depends(deps.get_db),
db: AsyncSession = Depends(deps.get_db),
id: int,
item_in: schemas.ItemUpdate,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Update an item.
"""
item = crud.item.get(db=db, id=id)
item = await crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
item = crud.item.update(db=db, db_obj=item, obj_in=item_in)
item = await crud.item.update(db=db, db_obj=item, obj_in=item_in)
return item


@router.get("/{id}", response_model=schemas.Item)
def read_item(
async def read_item(
*,
db: Session = Depends(deps.get_db),
db: AsyncSession = Depends(deps.get_db),
id: int,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Get item by ID.
"""
item = crud.item.get(db=db, id=id)
item = await crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
Expand All @@ -81,19 +83,19 @@ def read_item(


@router.delete("/{id}", response_model=schemas.Item)
def delete_item(
async def delete_item(
*,
db: Session = Depends(deps.get_db),
db: AsyncSession = Depends(deps.get_db),
id: int,
current_user: models.User = Depends(deps.get_current_active_user),
) -> Any:
"""
Delete an item.
"""
item = crud.item.get(db=db, id=id)
item = await crud.item.get(db=db, id=id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not crud.user.is_superuser(current_user) and (item.owner_id != current_user.id):
raise HTTPException(status_code=400, detail="Not enough permissions")
item = crud.item.remove(db=db, id=id)
return item
item = await crud.item.remove(db=db, id=id)
return item
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

from fastapi import APIRouter, Body, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from sqlalchemy.ext.asyncio import AsyncSession

from app import crud, models, schemas
from app.api import deps
Expand All @@ -20,13 +20,14 @@


@router.post("/login/access-token", response_model=schemas.Token)
def login_access_token(
db: Session = Depends(deps.get_db), form_data: OAuth2PasswordRequestForm = Depends()
async def login_access_token(
db: AsyncSession = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
) -> Any:
"""
OAuth2 compatible token login, get an access token for future requests
"""
user = crud.user.authenticate(
user = await crud.user.authenticate(
db, email=form_data.username, password=form_data.password
)
if not user:
Expand All @@ -43,19 +44,19 @@ def login_access_token(


@router.post("/login/test-token", response_model=schemas.User)
def test_token(current_user: models.User = Depends(deps.get_current_user)) -> Any:
async def test_token(current_user: models.User = Depends(deps.get_current_user)) -> Any:
"""
Test access token
"""
return current_user


@router.post("/password-recovery/{email}", response_model=schemas.Msg)
def recover_password(email: str, db: Session = Depends(deps.get_db)) -> Any:
async def recover_password(email: str, db: AsyncSession = Depends(deps.get_db)) -> Any:
"""
Password Recovery
"""
user = crud.user.get_by_email(db, email=email)
user = await crud.user.get_by_email(db, email=email)

if not user:
raise HTTPException(
Expand All @@ -70,18 +71,18 @@ def recover_password(email: str, db: Session = Depends(deps.get_db)) -> Any:


@router.post("/reset-password/", response_model=schemas.Msg)
def reset_password(
async def reset_password(
token: str = Body(...),
new_password: str = Body(...),
db: Session = Depends(deps.get_db),
db: AsyncSession = Depends(deps.get_db),
) -> Any:
"""
Reset password
"""
email = verify_password_reset_token(token)
if not email:
raise HTTPException(status_code=400, detail="Invalid token")
user = crud.user.get_by_email(db, email=email)
user = await crud.user.get_by_email(db, email=email)
if not user:
raise HTTPException(
status_code=404,
Expand All @@ -92,5 +93,5 @@ def reset_password(
hashed_password = get_password_hash(new_password)
user.hashed_password = hashed_password
db.add(user)
db.commit()
return {"msg": "Password updated successfully"}
await db.commit()
return {"msg": "Password updated successfully"}
Loading

0 comments on commit 6631a72

Please sign in to comment.