57 lines
2.2 KiB
Python
57 lines
2.2 KiB
Python
import os
|
|
from fastapi import FastAPI, Depends, HTTPException
|
|
from fastapi.security import HTTPBasic, HTTPBasicCredentials
|
|
from fastapi.openapi.docs import get_swagger_ui_html, get_redoc_html
|
|
from fastapi.openapi.utils import get_openapi
|
|
from router import router
|
|
from dotenv import load_dotenv
|
|
|
|
# Загрузите переменные окружения из файла .env
|
|
load_dotenv()
|
|
|
|
app = FastAPI(title="api-data-base")
|
|
|
|
security = HTTPBasic()
|
|
|
|
# Создайте функцию для проверки доступа
|
|
def authenticate(credentials: HTTPBasicCredentials = Depends(security)):
|
|
correct_username = os.getenv("DOCS_USERNAME", "admin") # Укажите имя пользователя
|
|
correct_password = os.getenv("DOCS_PASSWORD", "admin") # Укажите пароль
|
|
if credentials.username == correct_username and credentials.password == correct_password:
|
|
return True
|
|
raise HTTPException(
|
|
status_code=401,
|
|
detail="Неверное имя пользователя или пароль",
|
|
headers={"WWW-Authenticate": "Basic"},
|
|
)
|
|
|
|
# Переопределите маршруты для документации
|
|
@app.get("/docs", include_in_schema=False)
|
|
def custom_swagger_ui(credentials: HTTPBasicCredentials = Depends(authenticate)):
|
|
return get_swagger_ui_html(openapi_url=app.openapi_url, title="Документация API")
|
|
|
|
@app.get("/redoc", include_in_schema=False)
|
|
def custom_redoc_html(credentials: HTTPBasicCredentials = Depends(authenticate)):
|
|
return get_redoc_html(openapi_url=app.openapi_url, title="Документация API")
|
|
|
|
# Настройте кастомный OpenAPI (если требуется)
|
|
def custom_openapi():
|
|
if app.openapi_schema:
|
|
return app.openapi_schema
|
|
openapi_schema = get_openapi(
|
|
title="Пример API",
|
|
version="1.0.0",
|
|
description="Документация защищена паролем",
|
|
routes=app.routes,
|
|
)
|
|
app.openapi_schema = openapi_schema
|
|
return app.openapi_schema
|
|
|
|
app.openapi = custom_openapi
|
|
|
|
|
|
app.include_router(router)
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=8001) |