nova-api/api/main.py

67 lines
1.6 KiB
Python
Raw Normal View History

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,
key_func=network.get_ip_sync, default_limits=[
'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():
"""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
"""
Returns general information about the API.
2023-08-13 17:12:35 +02:00
"""
2023-06-23 02:18:28 +02:00
return {
'hi': 'Welcome to the Nova API!',
'learn_more_here': 'https://nova-oss.com',
'github': 'https://github.com/novaoss/nova-api',
'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):
return await handler.handle(request)