Repository navigation
Expand file tree
/
Copy pathctfeed.py
More file actions
104 lines (87 loc) · 2.75 KB
/
Copy pathctfeed.py
File metadata and controls
104 lines (87 loc) · 2.75 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python3
from contextlib import asynccontextmanager
import logging
from fastapi import FastAPI
from starlette.middleware.sessions import SessionMiddleware
from fastapi.middleware.cors import CORSMiddleware
from src.config import settings
from src.database import database
from src.backend.config import update_config_cache
from src.utils import ctf_api
from src import crud
from src import schema
from src import bot
from src import router
# logging
logger = logging.getLogger("uvicorn")
# start and shutdown
@asynccontextmanager
async def lifespan(app:FastAPI):
# startup
## initialize config
try:
async with database.with_get_db() as session:
async with session.begin():
config = await crud.create_or_update_config(session)
except Exception as e:
logger.critical(f"fail to initialize Config in database: {str(e)}")
raise
await update_config_cache(config)
## initialize CTFMenuMessage
try:
async with database.with_get_db() as session:
async with session.begin():
await crud.create_or_update_ctfmenu_message(session)
except Exception as e:
logger.critical(f"fail to initialize CTFMenuMessage in database: {str(e)}")
raise
## initialize aiohttp.ClientSession in src.utils.ctf_api
try:
await ctf_api.init_session()
except Exception as e:
logger.critical(f"fail to initialize aiohttp.ClientSession in src.utils.ctf_api")
raise
## start discord bot
await bot.start_bot()
# app run
yield
# shutdown
## stop discord bot
await bot.stop_bot()
## close aiohttp.ClientSession in src.utils.ctf_api
try:
await ctf_api.close_session()
except Exception as e:
logger.critical(f"fail to stop aiohttp.ClientSession in src.utils.ctf_api")
# app
app = FastAPI(debug=False, lifespan=lifespan)
# middleware
app.add_middleware(
CORSMiddleware,
allow_origins=[settings.HTTP_FRONTEND_URL, settings.HTTP_API_URL],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.add_middleware(
SessionMiddleware,
secret_key=settings.HTTP_SECRET_KEY,
domain=settings.HTTP_COOKIE_DOMAIN,
path="/",
same_site="Lax",
https_only=settings.HTTP_COOKIE_SECURE,
max_age=settings.HTTP_COOKIE_MAX_AGE,
)
# router
app.include_router(router.auth_router)
app.include_router(router.user_router)
app.include_router(router.ctf_router)
app.include_router(router.config_router)
app.include_router(router.guild_router)
# index
@app.get("/", tags=["Shirakami Fubuki"])
async def index() -> schema.General:
return schema.General(
success=True,
message="Shirakami Fubuki is the cutest fox in the world!"
)