| | import os |
| | import uvicorn |
| | from fastapi.middleware.cors import CORSMiddleware |
| | from fastapi.templating import Jinja2Templates |
| | import logging |
| | from fastapi.responses import HTMLResponse |
| | from fastapi import FastAPI, Request, HTTPException |
| | from pathlib import Path |
| | from dateutil import parser |
| | from contextlib import asynccontextmanager |
| | from news_data import scheduler |
| | from db import Database |
| |
|
| | database = Database(Path("./")) |
| | logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO")) |
| |
|
| |
|
| | @asynccontextmanager |
| | async def lifespan(app: FastAPI): |
| | print("Startup") |
| | scheduler.start() |
| | yield |
| | scheduler.shutdown() |
| | print("Shutdown") |
| |
|
| |
|
| | app = FastAPI(lifespan=lifespan) |
| |
|
| | app.add_middleware( |
| | CORSMiddleware, |
| | allow_origins=["*"], |
| | allow_credentials=True, |
| | allow_methods=["*"], |
| | allow_headers=["*"], |
| | ) |
| |
|
| |
|
| | def format_date(value): |
| | format = "%A, %d %B %Y" |
| | |
| | try: |
| | date = parser.parse(value) |
| | return date.strftime(format) |
| | except Exception: |
| | return value |
| |
|
| |
|
| | templates = Jinja2Templates(directory="templates") |
| | templates.env.filters["formatdate"] = format_date |
| |
|
| |
|
| | @app.get("/", response_class=HTMLResponse) |
| | async def main(request: Request): |
| | data = database.filter("world") |
| | return templates.TemplateResponse( |
| | request=request, name="index.j2", context={"data": data} |
| | ) |
| |
|
| |
|
| | if __name__ == "__main__": |
| | uvicorn.run(app, host="0.0.0.0", port=7860) |
| |
|