-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
77 lines (61 loc) · 2.57 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
76
77
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException
from starlette.middleware.cors import CORSMiddleware
from starlette.middleware.sessions import SessionMiddleware
from ratelimit import RateLimitMiddleware, Rule
from ratelimit.auths import EmptyInformation
from ratelimit.backends.redis import RedisBackend
from ratelimit.auths.ip import client_ip
from ratelimit.auths.session import from_session
from api.errors.http_error import http_error_handler
from api.errors.validation_error import http422_error_handler
from api.routes.api import router as api_router
from api.routes.api import router_rate_limits
from api.core.config import ALLOWED_HOSTS, API_PREFIX, DEBUG, SECRET_KEY
from api.core.events import create_start_app_handler, create_stop_app_handler
async def AUTH_FUNCTION(scope):
return scope['client'][0], "default" #USER_UNIQUE_ID, GROUP_NAME
def get_application() -> FastAPI:
application = FastAPI(
debug = True,
title = "Smart Server",
description = "MP session and game handler",
version = "0.0.1",
docs_url = "/api/docs",
redoc_url = "/api/redocs"
)
application.add_middleware(
CORSMiddleware,
allow_origins=ALLOWED_HOSTS or ["*"],
allow_credentials=True,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
application.add_middleware(
SessionMiddleware,
secret_key=SECRET_KEY,
same_site='None'
)
'''
Note: If the API is a proxy to base play url (eg: play.localhost/cjs/...), it's better to use from_session
else, for generic purpose, you can rate limit using IP address too.
'''
#AUTH_FUNCTION = client_ip or from_session
application.add_middleware(
RateLimitMiddleware,
authenticate=AUTH_FUNCTION,
backend=RedisBackend(),
config=router_rate_limits
#{
# r"^/second_limit": [Rule(second=1), Rule(group="admin")],
# r"^/minute_limit": [Rule(minute=1), Rule(group="admin")],
#},
)
application.add_event_handler("startup", create_start_app_handler(application))
application.add_event_handler("shutdown", create_stop_app_handler(application))
application.add_exception_handler(HTTPException, http_error_handler)
application.add_exception_handler(RequestValidationError, http422_error_handler)
application.include_router(api_router)
return application
app = get_application()