Skip to content

Commit

Permalink
Merge pull request #182 from grillazz/179-reflect-latest-and-greatest…
Browse files Browse the repository at this point in the history
…-fastapi-improvements

179 reflect latest and greatest fastapi improvements
  • Loading branch information
grillazz authored Nov 11, 2024
2 parents 48cbb8c + 34ab82f commit c7775c7
Show file tree
Hide file tree
Showing 10 changed files with 26 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ PYTHONUNBUFFERED=1
POSTGRES_HOST=db
POSTGRES_PORT=5432
POSTGRES_DB=devdb
POSTGRES_USER=user
POSTGRES_USER=devdb
POSTGRES_PASSWORD=secret

# Redis
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ docker-create-db-migration: ## Create new alembic database migration aka databa

.PHONY: docker-test
docker-test: ## Run project tests
docker compose -f compose.yml -f test-compose.yml run --rm app pytest tests
docker compose -f compose.yml -f test-compose.yml run --rm app pytest tests --durations=0

.PHONY: docker-test-snapshot
docker-test-snapshot: ## Run project tests with inline snapshot
Expand Down
8 changes: 6 additions & 2 deletions app/api/user.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from fastapi import APIRouter, Depends, status, Request, HTTPException
from typing import Annotated

from fastapi import APIRouter, Depends, status, Request, HTTPException, Form
from sqlalchemy.ext.asyncio import AsyncSession

from app.database import get_db
Expand Down Expand Up @@ -29,7 +31,9 @@ async def create_user(
"/token", status_code=status.HTTP_201_CREATED, response_model=TokenResponse
)
async def get_token_for_user(
user: UserLogin, request: Request, db_session: AsyncSession = Depends(get_db)
user: Annotated[UserLogin, Form()],
request: Request,
db_session: AsyncSession = Depends(get_db),
):
_user: User = await User.find(db_session, [User.email == user.email])

Expand Down
6 changes: 5 additions & 1 deletion app/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@
async def get_db() -> AsyncGenerator:
async with AsyncSessionFactory() as session:
# logger.debug(f"ASYNC Pool: {engine.pool.status()}")
yield session
try:
yield session
except Exception as e:
logger.error(f"Error getting database session: {e}")
raise
2 changes: 1 addition & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ async def lifespan(_app: FastAPI):
dependencies=[Depends(AuthBearer())],
)

_scheduler_data_store = SQLAlchemyDataStore(engine)
_scheduler_data_store = SQLAlchemyDataStore(engine, schema="scheduler")
_scheduler_event_broker = RedisEventBroker(
client_or_url=global_settings.redis_url.unicode_string()
)
Expand Down
4 changes: 4 additions & 0 deletions app/services/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@

from fastapi import Request, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from app.utils.logging import AppLogger

logger = AppLogger().get_logger()


async def get_from_redis(request: Request, key: str):
Expand Down Expand Up @@ -37,6 +40,7 @@ async def __call__(self, request: Request):
raise HTTPException(
status_code=403, detail="Invalid token or expired token."
)
logger.info(f"Token verified: {credentials.credentials}")
return credentials.credentials


Expand Down
2 changes: 1 addition & 1 deletion compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ services:
- "8080:8080"
depends_on:
- db
- redis
- inmemory

db:
container_name: fsap_db
Expand Down
4 changes: 2 additions & 2 deletions db/create.sql
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
-- DROP DATABASE IF EXISTS devdb;
-- CREATE DATABASE devdb;
\connect devdb;
CREATE SCHEMA shakespeare;
CREATE SCHEMA happy_hog;
CREATE SCHEMA scheduler;

DROP DATABASE IF EXISTS testdb;
CREATE DATABASE testdb;
\connect testdb;
CREATE SCHEMA shakespeare;
CREATE SCHEMA happy_hog;
CREATE SCHEMA scheduler;
2 changes: 0 additions & 2 deletions test-compose.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
version: '3.8'

services:
app:
environment:
Expand Down
6 changes: 5 additions & 1 deletion tests/api/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,11 @@ async def test_add_user(client: AsyncClient):
# TODO: parametrize test with diff urls including 404 and 401
async def test_get_token(client: AsyncClient):
payload = {"email": "[email protected]", "password": "s1lly"}
response = await client.post("/user/token", json=payload)
response = await client.post(
"/user/token",
data=payload,
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
assert response.status_code == status.HTTP_201_CREATED
claimset = jwt.decode(
response.json()["access_token"], options={"verify_signature": False}
Expand Down

0 comments on commit c7775c7

Please sign in to comment.