68 lines
1.9 KiB
Python
68 lines
1.9 KiB
Python
import datetime
|
|
import time
|
|
import json
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI, Depends, Body
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.encoders import jsonable_encoder
|
|
from pydantic import BaseModel
|
|
from sqlalchemy.exc import DBAPIError
|
|
from starlette.requests import Request
|
|
from starlette.responses import JSONResponse
|
|
|
|
from device.router import router, websocket_router
|
|
|
|
app = FastAPI(
|
|
title="Smart lock",
|
|
root_path="/devices"
|
|
)
|
|
|
|
@app.get("/docs", include_in_schema=False)
|
|
async def custom_swagger_ui_html(req: Request):
|
|
root_path = req.scope.get("root_path", "").rstrip("/")
|
|
openapi_url = root_path + app.openapi_url
|
|
return get_swagger_ui_html(
|
|
openapi_url=openapi_url,
|
|
title="API",
|
|
)
|
|
|
|
app.include_router(router)
|
|
app.include_router(websocket_router)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def add_process_time_header(request: Request, call_next):
|
|
start_time = time.perf_counter()
|
|
response = await call_next(request)
|
|
process_time = time.perf_counter() - start_time
|
|
print(f"Finished in {process_time:.3f}")
|
|
response.headers["X-Process-Time"] = str(process_time)
|
|
return response
|
|
|
|
|
|
@app.exception_handler(DBAPIError)
|
|
def authjwt_exception_handler(request: Request, exc: DBAPIError):
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content={"detail": jsonable_encoder(exc) | {"args": jsonable_encoder(exc.args)}}
|
|
)
|
|
|
|
|
|
# @app.exception_handler(Exception)
|
|
# def authjwt_exception_handler(request: Request, exc: Exception):
|
|
# print(exc.with_traceback(None))
|
|
# return JSONResponse(
|
|
# status_code=500,
|
|
# content={
|
|
# "name_exception": exc.__class__.__name__,
|
|
# "args": getattr(exc, "args", []),
|
|
# "detail": jsonable_encoder(exc)
|
|
# }
|
|
# )
|
|
|
|
|
|
if __name__ == '__main__':
|
|
uvicorn.run(app=app, host="0.0.0.0", port=8001)
|
|
# uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)
|