Open Hyralc opened 2 years ago
Pour implémenter un middleware de maintenance dans votre application web basée sur FastAPI, vous pouvez suivre ces étapes :
abort()
de FastAPI pour renvoyer une réponse HTTP 503 (Service Unavailable) avec un message approprié..middleware()
Voici un exemple de code qui implémente cette fonctionnalité :
from fastapi import FastAPI, HTTPException
app = FastAPI()
MAINTENANCE_MODE = True
@app.middleware("http")
async def maintenance_middleware(request: Request, call_next):
if MAINTENANCE_MODE:
raise HTTPException(status_code=503, detail="We're under maintenance. Please come back later.")
response = await call_next(request)
return response
En utilisant cette méthode, toutes les requêtes entrantes passeront par ce middleware avant d'atteindre les routes de l'application, ce qui permet de vérifier l'état de maintenance avant de traiter la requête.
In the AntaREST application, we setup the middleware functions/classes in the antarest.main.fastapi_app
function. The maintenance middleware can be inserted anywhere but it is better to put it in the first ones to block the requests as soon as possible.
This middleware must use the get_maintenance_status
method which is accessible from the MaintenanceService
instance created when calling the create_services
utility function. The status is True
when in maintenance and False
otherwise.
When in maintenance, an error message must be returned. We can use the MaintenanceService.get_message_info
method to get the message indicating the reason for the maintenance. Be careful, the operator performing the maintenance can express himself in French.
Currently the API can be used even if the server is in maintenance mode. We should add checks in all the endpoints to verify the API is not in maintenance mode.
Warning: the
/core/maintenance
endpoint must not be locked.