Skip to content

Commit

Permalink
new version with profiling, docker-compose, user auth, and much more,…
Browse files Browse the repository at this point in the history
… ...
  • Loading branch information
JeyDi committed Oct 11, 2021
1 parent a7c4b66 commit 5297e72
Show file tree
Hide file tree
Showing 30 changed files with 405 additions and 477 deletions.
13 changes: 6 additions & 7 deletions .env
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@

DB_PORT = 5442
DB_PORT=5442

APP_DB_NAME=fastcash
APP_DB_USER=root
APP_DB_PASSWORD="SUPERduper42"
APP_DB_PORT=5432
APP_DB_HOST="localhost"
APP_DB_HOST="fastcash-db"

APP_ENDPOINT_HOST="localhost"
APP_API_ENDPOINT_PORT=8044
APP_DOCKER_PORT=8044
APP_ENDPOINT_PORT=8044
APP_DOCKER_PORT=8042
APP_ENDPOINT_PORT=8000
APP_SECRET_KEY="SUPERsecretKEY42!!"
APP_DEBUG_MODE="False"
APP_VERBOSITY="DEBUG"
APP_API_TOKEN = "PythonBiellaGroup"
APP_VERBOSITY="INFO"
APP_API_TOKEN="PythonBiellaGroup"

#POSTGRES_DATA_DIR="f:\\tmp\\data"
#POSTGRES_BACKUP_DIR="f:\\temp\\backup"
Expand Down
5 changes: 3 additions & 2 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@
"args": ["app.main:app", "--reload", "--port", "8044"],
"env": {
"PYTHONPATH": "${cwd}",
"API_ENDPOINT_PORT": "8042",
"VERBOSITY": "DEBUG"
"API_ENDPOINT_PORT": "8044",
"API_ENDPOINT_HOST": "localhost",
"APP_VERBOSITY": "DEBUG",
}
},
{
Expand Down
1 change: 0 additions & 1 deletion FastCash Local.session.sql

This file was deleted.

20 changes: 12 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,23 @@ Then you have to initialize the project with: `poetry install`

If you want to use the environment variable, you have to create a .env variable with this values inside:
```bash
DB_PORT=<your_db_external_port>

APP_DB_NAME=fastcash
APP_DB_USER=root
APP_DB_PASSWORD=<yourpassword>
APP_DB_PORT=<yourport>
APP_DB_HOST="fastcash-db"

APP_ENDPOINT_HOST="localhost"
APP_API_ENDPOINT_PORT=8044
APP_DOCKER_PORT=8044
APP_DOCKER_PORT=<your_docker_app_external_port>
APP_ENDPOINT_PORT=8044
APP_SECRET_KEY=<yourappsecret>
APP_SECRET_KEY=<your_app_secret>
APP_DEBUG_MODE="False"
APP_VERBOSITY="DEBUG"
APP_API_TOKEN=<your_secret_app_api_token>

#optional
POSTGRES_DATA_DIR=<your_machine_data_folder>
POSTGRES_BACKUP_DIR=<your_machine_backup_folder>
```
Expand Down Expand Up @@ -76,13 +79,14 @@ The content of the file is this one (paste inside the file).
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": ["app.main:app", "--reload", "--port", "8042"],
"args": ["app.main:app", "--reload", "--port", "8044"],
"env": {
"PYTHONPATH": "${cwd}",
"API_ENDPOINT_PORT": "8042",
"VERBOSITY": "DEBUG"
"PYTHONPATH": "${cwd}",
"API_ENDPOINT_PORT": "8044",
"API_ENDPOINT_HOST": "localhost",
"APP_VERBOSITY": "DEBUG",
}
}
},
]
}

Expand Down
33 changes: 22 additions & 11 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from fastapi import FastAPI, Depends, HTTPException, status
from fastapi.security import APIKeyHeader
import uvicorn
from starlette.middleware.cors import CORSMiddleware
from sqlmodel import select
from app.src.common.security import get_password_hash
from fastapi import FastAPI, responses


# from app.src.api.endpoints.login import api_token
from app.src.common.security import get_password_hash
from app.src.db.engine import get_session_sqlmodel
from app.src.db.manager import create_table, insert_data
from app.src.api.api import api_router
Expand All @@ -17,7 +17,6 @@
PROJECT_NAME,
API_V1_STR,
BACKEND_CORS_ORIGINS,
APP_API_TOKEN,
)
from app.src.config import (
APP_USER_NAME,
Expand All @@ -30,12 +29,6 @@
)
from app.src.models.app_user import AppUser


# async def api_token(token: str = Depends(APIKeyHeader(name="Token"))):
# if token != APP_API_TOKEN:
# raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)


app = FastAPI(
title=PROJECT_NAME,
openapi_url=f"{API_V1_STR}/openapi.json",
Expand Down Expand Up @@ -82,8 +75,26 @@ def on_startup():
logger.debug("Default user inserted")


@app.get("/")
def index():
url_swagger = f"http://{API_ENDPOINT_HOST}:{API_ENDPOINT_PORT}/docs"
url_redoc = f"http://{API_ENDPOINT_HOST}:{API_ENDPOINT_PORT}/redoc"
body = (
"<html>"
"<body style='padding: 10px;'>"
"<h1>Welcome to: PythonBiellaGroup FastCash Server App</h1>"
"<ul>"
f"<li><a href={url_swagger}>Link to the Swagger documentation</a></li>"
f"<li><a href={url_redoc}>Link to the Redoc documentation</a></li>"
"</ul>"
"</body>"
"</html>"
)
return responses.HTMLResponse(content=body)


if __name__ == "__main__":
logger.debug(f"Starting server on: {API_ENDPOINT_HOST}:{API_ENDPOINT_PORT}")
logger.info(f"Starting server on: {API_ENDPOINT_HOST}:{API_ENDPOINT_PORT}")

if DEBUG_MODE:
uvicorn.run(app, port=API_ENDPOINT_PORT, host=API_ENDPOINT_HOST)
2 changes: 1 addition & 1 deletion app/src/api/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@
product_type.router, prefix="/product_type", tags=["product_type"]
)
api_router.include_router(app_user.router, prefix="/user", tags=["user"])
api_router.include_router(login.router, prefix="/login", tags=["login", "token"])
api_router.include_router(login.router, prefix="/login", tags=["login"])
30 changes: 21 additions & 9 deletions app/src/api/endpoints/app_user.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ async def read_all_users(
status_code=400, detail="Token not valid or user not authenticated"
)
list_users = session.exec(select(AppUser).offset(offset).limit(limit)).all()
profiling_api("User:get:all", start_time)
profiling_api("User:get:all", start_time, current_user.username)
return list_users


Expand All @@ -92,29 +92,34 @@ async def read_single_user(
"""
Retrieve a single user by id
"""
profiling_api(f"User:get:by_id:{user_id}", user_time_obj["start_time"])
profiling_api(
f"User:get:by_id:{user_id}",
user_time_obj["start_time"],
user_time_obj["db_user"].username,
)
return user_time_obj["db_user"]


@router.post("/", response_model=AppUserRead)
async def create_new_user(
user: AppUserCreate,
session: Session = Depends(get_session),
current_user: AppUser = Depends(get_current_admin_user),
) -> Any:
"""
Insert new user
"""
# Check user existing by email and username
start_time = dt.datetime.now()
try:
#create the hash password
# create the hash password
user.password = get_password_hash(user.password)
#insert the new user

# insert the new user
db_user = AppUser.from_orm(user)
session.add(db_user)
session.commit()
profiling_api("User:insert:single", start_time)
profiling_api("User:insert:single", start_time, current_user.username)
return db_user
except Exception as message:
logger.error(f"Impossible to insert new user: {message}")
Expand All @@ -130,7 +135,6 @@ async def update_user_id(
user: AppUserUpdate,
session: Session = Depends(get_session),
user_time_obj: AppUser = Depends(get_user_or_404_by_id),
current_user: AppUser = Depends(get_current_admin_user),
):
"""
Update a user by id
Expand All @@ -143,7 +147,11 @@ async def update_user_id(
session.add(existing_user)
session.commit()
session.refresh(existing_user)
profiling_api(f"User:delete:by_id:{user_id}", user_time_obj["start_time"])
profiling_api(
f"User:update:by_id:{user_id}",
user_time_obj["start_time"],
user_time_obj["db_user"].username,
)
return existing_user
except Exception as message:
logger.error(
Expand All @@ -167,7 +175,11 @@ async def delete_user_id(
try:
session.delete(existing_user)
session.commit()
profiling_api(f"User:delete:by_id:{user_id}", user_time_obj["start_time"])
profiling_api(
f"User:delete:by_id:{user_id}",
user_time_obj["start_time"],
user_time_obj["db_user"].username,
)
return {"User deleted": True}
except Exception as message:
logger.error(f"Impossible to delete the user: {user_id}")
Expand Down
14 changes: 8 additions & 6 deletions app/src/api/endpoints/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session

from app.src.config import SECURITY_ACCESS_TOKEN_EXPIRE_MINUTES, API_V1_STR
from app.src.config import (
SECURITY_ACCESS_TOKEN_EXPIRE_MINUTES,
API_V1_STR,
)
from app.src.models.token import Token
from app.src.models.app_user import AppUser, AppUserRead
from app.src.db.engine import get_session, get_db, get_session_sqlmodel
from app.src.db.engine import get_session
from app.src.common.security import (
get_current_user,
create_access_token,
Expand All @@ -20,13 +23,12 @@
router = APIRouter()

reusable_oauth2 = OAuth2PasswordBearer(tokenUrl=f"{API_V1_STR}/login/access-token")
API_TOKEN = "test"


# Api Token function test
# Api Token function test (auth based on token)
# async def api_token(token: str = Depends(APIKeyHeader(name="Token"))):
# if token != API_TOKEN:
# raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
# if token != APP_API_TOKEN:
# raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)


@router.get("/test")
Expand Down
Loading

0 comments on commit 5297e72

Please sign in to comment.