asgi.py 1.63 KB
Newer Older
1
2
3
4
import http

from fastapi import FastAPI, HTTPException
from fastapi.responses import HTMLResponse
5
from fastapi.staticfiles import StaticFiles
6
7
8
9
from starlette.middleware.sessions import SessionMiddleware

import aurweb.config

10
from aurweb.routers import html, sso
11

12
13
14
routes = set()

# Setup the FastAPI app.
15
app = FastAPI()
16
17
18
19
20
21
22
23
24
app.mount("/static/css",
          StaticFiles(directory="web/html/css"),
          name="static_css")
app.mount("/static/js",
          StaticFiles(directory="web/html/js"),
          name="static_js")
app.mount("/static/images",
          StaticFiles(directory="web/html/images"),
          name="static_images")
25
26
27
28
29
30
31
32

session_secret = aurweb.config.get("fastapi", "session_secret")
if not session_secret:
    raise Exception("[fastapi] session_secret must not be empty")

app.add_middleware(SessionMiddleware, secret_key=session_secret)

app.include_router(sso.router)
33
34
35
36
37
38
39
40
app.include_router(html.router)

# NOTE: Always keep this dictionary updated with all routes
# that the application contains. We use this to check for
# parameter value verification.
routes = {route.path for route in app.routes}
routes.update({route.path for route in sso.router.routes})
routes.update({route.path for route in html.router.routes})
41
42
43
44
45
46
47
48
49
50
51


@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
    """
    Dirty HTML error page to replace the default JSON error responses.
    In the future this should use a proper Arch-themed HTML template.
    """
    phrase = http.HTTPStatus(exc.status_code).phrase
    return HTMLResponse(f"<h1>{exc.status_code} {phrase}</h1><p>{exc.detail}</p>",
                        status_code=exc.status_code)