Skip to content

Commit

Permalink
removed dep fatapi-cli and added logging
Browse files Browse the repository at this point in the history
  • Loading branch information
SparrowSurya committed Aug 24, 2024
1 parent c49c63a commit e847a9c
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 11 deletions.
7 changes: 1 addition & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,6 @@ A fastapi service for code sharing.
![os](https://img.shields.io/badge/os-Linux-blue)


## TODOS
* logger
* deployment


## Run
0. Download this project
```sh
Expand Down Expand Up @@ -37,5 +32,5 @@ python3 -m pip install -r requirements.txt

3. Run the api
```sh
fastapi dev api/main.py
uvicrn api.main:app --log-config=log_config.yaml
```
12 changes: 10 additions & 2 deletions api/background_tasks.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,23 @@
import asyncio
import logging

from sqlalchemy.orm import Session

from . import crud


logger = logging.getLogger(__name__)


async def delete_expired_paste_task(interval: float, db: Session):
while True:
run = 1
logger.info(f"Task started: delete-expired-paste after each {interval}s.")
while run:
try:
await asyncio.sleep(interval)
except asyncio.CancelledError:
return
run = False
else:
crud.delete_expired_pastes(db)

logger.info("Task ended: delete-expired-paste.")
5 changes: 4 additions & 1 deletion api/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from functools import lru_cache


logger = logging.getLogger(__name__)


class Settings(BaseSettings):
"""Settings for the application."""

Expand All @@ -19,5 +22,5 @@ class Settings(BaseSettings):
def get_settings() -> Settings:
"""Get the application settings."""
settings = Settings()
logging.info(f"Loading settings for {settings.env_name}")
logger.info(f"Loading settings for {settings.env_name}")
return settings
7 changes: 7 additions & 0 deletions api/main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import logging
from contextlib import asynccontextmanager

from fastapi import Depends, FastAPI, HTTPException, Request
Expand All @@ -10,13 +11,18 @@
from .background_tasks import delete_expired_paste_task


logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("Application lifespan started!")
interval = float(get_settings().interval)
db = SessionLocal()
asyncio.create_task(delete_expired_paste_task(interval, db))
yield
db.close()
logger.info("Application lifespan ended!")


app = FastAPI(lifespan=lifespan)
Expand All @@ -33,6 +39,7 @@ def create_paste(paste: schemas.Paste, db: Session = Depends(get_db)):
try:
db_paste = crud.create_db_paste(db, paste)
except RuntimeError as error:
logger.exception(error)
raise HTTPException(status_code=500, detail=str(error))

url = get_settings().base_url + f"/{db_paste.key}"
Expand Down
34 changes: 34 additions & 0 deletions log_config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
version: 1
disable_existing_loggers: False
formatters:
default:
# "()": uvicorn.logging.DefaultFormatter
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
access:
# "()": uvicorn.logging.AccessFormatter
format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
default:
formatter: default
class: logging.StreamHandler
stream: ext://sys.stderr
access:
formatter: access
class: logging.StreamHandler
stream: ext://sys.stdout
loggers:
uvicorn.error:
level: INFO
handlers:
- default
propagate: no
uvicorn.access:
level: INFO
handlers:
- access
propagate: no
root:
level: DEBUG
handlers:
- default
propagate: no
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ dependencies = [
"dnspython==2.6.1",
"email_validator==2.2.0",
"fastapi==0.112.0",
"fastapi-cli==0.0.5",
"greenlet==3.0.3",
"h11==0.14.0",
"httpcore==1.0.5",
Expand Down
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ click==8.1.7
dnspython==2.6.1
email_validator==2.2.0
fastapi==0.112.0
fastapi-cli==0.0.5
greenlet==3.0.3
h11==0.14.0
httpcore==1.0.5
Expand Down

0 comments on commit e847a9c

Please sign in to comment.