-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
63 lines (53 loc) · 2 KB
/
main.py
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
63
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
import asyncio
from typing import AsyncGenerator
from datetime import datetime
import os
from hn_scraper import start_scraper
from database import get_stories, init_db
async def lifespan(app: FastAPI) -> AsyncGenerator:
# Initialize the database
await init_db()
app.state.scraper_task = asyncio.create_task(start_scraper())
yield
app.state.scraper_task.cancel()
app = FastAPI(lifespan=lifespan)
# Mount the static directory
app.mount("/static", StaticFiles(directory="static"), name="static")
# Set up Jinja2 templates
templates = Jinja2Templates(directory="templates")
def time_ago(dt: datetime) -> str:
now = datetime.now()
diff = now - dt
if diff.days > 365:
return f"{diff.days // 365} year{'s' if diff.days >= 730 else ''} ago"
if diff.days > 30:
return f"{diff.days // 30} month{'s' if diff.days >= 60 else ''} ago"
if diff.days > 0:
return f"{diff.days} day{'s' if diff.days > 1 else ''} ago"
if diff.seconds > 3600:
return f"{diff.seconds // 3600} hour{'s' if diff.seconds >= 7200 else ''} ago"
if diff.seconds > 60:
return f"{diff.seconds // 60} minute{'s' if diff.seconds >= 120 else ''} ago"
return f"{diff.seconds} second{'s' if diff.seconds > 1 else ''} ago"
def get_trend_symbol(trend: str) -> str:
return {'up': '▲', 'down': '▼'}.get(trend, '')
@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
stories = await get_stories()
return templates.TemplateResponse(
"index.html",
{
"request": request,
"stories": stories,
"time_ago": time_ago,
"get_trend_symbol": get_trend_symbol,
},
)
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 80))
uvicorn.run("main:app", host="0.0.0.0", port=port, reload=True)