File size: 1,476 Bytes
8f4b172
 
 
 
 
 
 
 
 
b78a4d5
 
8f4b172
 
 
 
 
 
b78a4d5
 
 
 
 
 
 
 
 
 
8f4b172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b78a4d5
8f4b172
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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"
    # Use dateutil's parser to automatically handle different date formats
    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)