1
- from quart import Quart , Response , exceptions , jsonify
2
- from datetime import datetime , date
3
- from aiohttp import ClientSession
4
- from typing import Any , Optional
5
- from quart_cors import cors
1
+ from fastapi import FastAPI , HTTPException , Request
2
+ from utils .response import JSONResponse
6
3
import logging
7
- import json
8
-
9
- import utils
10
-
11
- from api .blueprints import auth , guilds , users
12
4
13
5
14
6
log = logging .getLogger ()
15
7
16
8
17
- class JSONEncoder (json .JSONEncoder ):
18
- def default (self , o : Any ) -> Any :
19
- if isinstance (o , (datetime , date )):
20
- o .replace (microsecond = 0 )
21
- return o .isoformat ()
22
-
23
- return super ().default (o )
24
-
25
-
26
- class API (Quart ):
27
- """Quart subclass to implement more API like handling."""
28
-
29
- http_session : Optional [ClientSession ] = None
30
- request_class = utils .Request
31
- json_encoder = JSONEncoder
32
-
9
+ class API (FastAPI ):
10
+ """FastAPI subclass to implement more API like handling."""
33
11
def __init__ (self , * args , ** kwargs ):
34
- kwargs .setdefault ("static_folder" , None )
35
12
super ().__init__ (* args , ** kwargs )
36
13
37
- async def handle_request (self , request : utils . Request ) -> Response :
14
+ async def handle_request (self , request : Request ):
38
15
response = await super ().handle_request (request )
39
16
log .info (f"{ request .method } @ { request .base_url } -> { response .status_code } " )
40
17
return response
41
18
42
- async def handle_http_exception (self , error : exceptions . HTTPException ):
19
+ async def handle_http_exception (self , error : HTTPException ):
43
20
"""
44
21
Returns errors as JSON instead of default HTML
45
22
Uses custom error handler if one exists.
@@ -53,35 +30,26 @@ async def handle_http_exception(self, error: exceptions.HTTPException):
53
30
headers = error .get_headers ()
54
31
headers ["Content-Type" ] = "application/json"
55
32
56
- return (
57
- jsonify ( error = error . name , message = error . description ) ,
58
- error .status_code ,
59
- headers ,
33
+ return JSONResponse (
34
+ headers = headers ,
35
+ status_code = error .status_code ,
36
+ content = { "error" : error . name , "message" : error . description }
60
37
)
61
38
62
- async def startup (self ) -> None :
63
- self .http_session = ClientSession ()
64
- return await super ().startup ()
65
-
66
39
67
- # Set up app
68
- app = API (__name__ )
69
- app .asgi_app = utils .TokenAuthMiddleware (app .asgi_app , app )
70
- app = cors (app , allow_origin = "*" ) # TODO: Restrict the origin(s) in production.
71
- # Set up blueprints
72
- auth .setup (app = app , url_prefix = "/auth" )
73
- users .setup (app = app , url_prefix = "/users" )
74
- guilds .setup (app = app , url_prefix = "/guilds" )
40
+ app = API ()
41
+ app .router .default_response_class = JSONResponse
42
+ app .add_exception_handler (HTTPException , app .handle_http_exception )
75
43
76
44
77
- @app .route ("/" )
45
+ @app .get ("/" )
78
46
async def index ():
79
47
"""Index endpoint used for testing."""
80
- return jsonify ( status = "OK" )
48
+ return { " status" : "ok" }
81
49
82
50
83
- @app .errorhandler (500 )
84
- async def error_500 (error : BaseException ):
51
+ @app .exception_handler (500 )
52
+ async def error_500 (request , error : HTTPException ):
85
53
"""
86
54
TODO: Handle the error with our own error handling system.
87
55
"""
@@ -90,7 +58,7 @@ async def error_500(error: BaseException):
90
58
exc_info = (type (error ), error , error .__traceback__ ),
91
59
)
92
60
93
- return (
94
- jsonify ( error = "Internal Server Error" , message = "Server got itself in trouble" ) ,
95
- 500 ,
61
+ return JSONResponse (
62
+ status_code = 500 ,
63
+ content = { "error" : "Internal Server Error" , "message" : "Server got itself in trouble" }
96
64
)
0 commit comments