2023-07-19 23:51:28 +02:00
|
|
|
"""FastAPI setup."""
|
|
|
|
|
2023-06-23 02:18:28 +02:00
|
|
|
import fastapi
|
2023-08-24 14:57:36 +02:00
|
|
|
import pydantic
|
2023-06-23 02:18:28 +02:00
|
|
|
|
2023-08-05 02:30:42 +02:00
|
|
|
from rich import print
|
2023-06-23 02:18:28 +02:00
|
|
|
from dotenv import load_dotenv
|
2023-08-24 14:57:36 +02:00
|
|
|
from bson.objectid import ObjectId
|
2023-08-27 04:29:16 +02:00
|
|
|
from slowapi.errors import RateLimitExceeded
|
|
|
|
from slowapi.middleware import SlowAPIMiddleware
|
2023-08-05 02:30:42 +02:00
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2023-08-27 04:29:16 +02:00
|
|
|
from slowapi import Limiter, _rate_limit_exceeded_handler
|
|
|
|
|
|
|
|
from helpers import network
|
2023-08-24 14:57:36 +02:00
|
|
|
|
2023-08-01 02:38:55 +02:00
|
|
|
import core
|
2023-08-27 04:29:16 +02:00
|
|
|
import handler
|
2023-06-23 02:18:28 +02:00
|
|
|
|
|
|
|
load_dotenv()
|
|
|
|
|
|
|
|
app = fastapi.FastAPI()
|
|
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
CORSMiddleware,
|
|
|
|
allow_origins=['*'],
|
|
|
|
allow_credentials=True,
|
|
|
|
allow_methods=['*'],
|
|
|
|
allow_headers=['*']
|
|
|
|
)
|
|
|
|
|
2023-08-01 02:38:55 +02:00
|
|
|
app.include_router(core.router)
|
|
|
|
|
2023-08-27 04:29:16 +02:00
|
|
|
limiter = Limiter(
|
|
|
|
swallow_errors=True,
|
2023-08-30 20:55:31 +02:00
|
|
|
key_func=network.get_ratelimit_key, default_limits=[
|
2023-08-27 04:29:16 +02:00
|
|
|
'2/second',
|
|
|
|
'20/minute',
|
|
|
|
'300/hour'
|
|
|
|
])
|
|
|
|
app.state.limiter = limiter
|
|
|
|
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
|
|
|
app.add_middleware(SlowAPIMiddleware)
|
|
|
|
|
2023-06-23 02:18:28 +02:00
|
|
|
@app.on_event('startup')
|
|
|
|
async def startup_event():
|
2023-08-21 20:58:05 +02:00
|
|
|
"""Runs when the API starts up."""
|
2023-08-24 14:57:36 +02:00
|
|
|
# https://stackoverflow.com/a/74529009
|
|
|
|
pydantic.json.ENCODERS_BY_TYPE[ObjectId]=str
|
2023-06-23 02:18:28 +02:00
|
|
|
|
|
|
|
@app.get('/')
|
|
|
|
async def root():
|
2023-08-13 17:12:35 +02:00
|
|
|
"""
|
2023-08-21 20:58:05 +02:00
|
|
|
Returns general information about the API.
|
2023-08-13 17:12:35 +02:00
|
|
|
"""
|
2023-06-23 02:18:28 +02:00
|
|
|
|
|
|
|
return {
|
2023-08-21 20:58:05 +02:00
|
|
|
'hi': 'Welcome to the Nova API!',
|
|
|
|
'learn_more_here': 'https://nova-oss.com',
|
|
|
|
'github': 'https://github.com/novaoss/nova-api',
|
2023-08-23 23:27:09 +02:00
|
|
|
'core_api_docs_for_nova_developers': '/docs',
|
|
|
|
'ping': 'pong'
|
2023-06-23 02:18:28 +02:00
|
|
|
}
|
|
|
|
|
2023-08-27 04:29:16 +02:00
|
|
|
@app.route('/v1/{path:path}', methods=['GET', 'POST', 'PUT', 'DELETE', 'PATCH'])
|
|
|
|
async def v1_handler(request: fastapi.Request):
|
2023-09-14 18:18:19 +02:00
|
|
|
res = await handler.handle(incoming_request=request)
|
2023-08-28 00:58:32 +02:00
|
|
|
return res
|