-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.py
75 lines (56 loc) · 1.98 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
64
65
66
67
68
69
70
71
72
73
74
75
from fastapi import FastAPI
from fastapi.concurrency import asynccontextmanager
from fastapi.routing import APIRoute
from fastapi.middleware.cors import CORSMiddleware
from database import init_db, session_factory
from seed import seed_if_empty
from routes import main_router
from user.permission import Permission
import os
def generate_unique_id(route: APIRoute):
if len(route.tags) > 0:
return f"{route.tags[0]}-{route.name}"
else:
return f"{route.path}{route.name}"
@asynccontextmanager
async def lifespan(app: FastAPI):
if os.getenv("ENV") == "development":
# Not needed if you setup a migration system like Alembic
init_db()
with session_factory() as db:
seed_if_empty(app, db)
yield
# after yield comes shutdown logic
# No Swagger/OpenAPI page for production
no_docs = os.getenv("ENV") == "production"
dev_origins = [
"http://localhost",
"http://localhost:5175",
]
app = FastAPI(
lifespan=lifespan,
redoc_url=None if no_docs else "/redoc",
docs_url=None if no_docs else "/docs",
generate_unique_id_function=generate_unique_id,
)
if os.getenv("ENV") == "development":
app.add_middleware(
CORSMiddleware,
allow_origins=dev_origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(router=main_router)
@app.get("/")
def hello_route():
return {"message": "Välkommen till F-Sektionens bäckend"}
@app.get("/user-only", dependencies=[Permission.base()])
def user_only():
return {"message": "Hello, you are a user."}
@app.get("/member-only", dependencies=[Permission.member()])
def member_only():
return {"message": "Congratz! Only members can reach this route"}
@app.get("/manage-event-only", dependencies=[Permission.require("manage", "Event")])
def permission_route():
return {"message": "Congratz. You reached a manage:Event route"}