forked from mtusi2026/mtusi2026lab3
перенос 2 лабы
This commit is contained in:
+148
@@ -0,0 +1,148 @@
|
||||
"""HTTP-адреса, определение пользователя и обработка запросов"""
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
import json
|
||||
import logging
|
||||
from time import perf_counter
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from src import auth, db, migrate, passwords, storage
|
||||
from src.errors import ApiError, error_response
|
||||
from src.models import CreateChat, CreateMessage, CreateUser
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
await run_in_threadpool(db.pool.open, wait=True, timeout=15)
|
||||
try:
|
||||
await run_in_threadpool(migrate.apply)
|
||||
yield
|
||||
finally:
|
||||
await run_in_threadpool(db.pool.close)
|
||||
|
||||
|
||||
app = FastAPI(title="Учебный мессенджер", redirect_slashes=False, lifespan=lifespan)
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def handle_request(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
started = perf_counter()
|
||||
path = request.url.path
|
||||
try:
|
||||
is_registration = request.method == "POST" and path == "/api/v1/users"
|
||||
is_login = request.method == "POST" and path == "/api/v1/auth/sessions"
|
||||
if is_login:
|
||||
request.state.user = await run_in_threadpool(auth.basic_user, request.headers.get("Authorization"))
|
||||
if await request.body():
|
||||
raise ApiError(400, "invalid_request", "Вход через Basic не принимает тело запроса")
|
||||
elif path.startswith("/api/v1/") and not is_registration:
|
||||
request.state.user = await run_in_threadpool(auth.current_user, request.headers.get("Authorization"))
|
||||
if request.method == "POST" and path.startswith("/api/v1/") and not is_login:
|
||||
content_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
||||
try:
|
||||
json.loads((await request.body()).decode("utf-8"))
|
||||
except (ValueError, RecursionError):
|
||||
raise ApiError(400, "invalid_request", "Ожидается корректный JSON в UTF-8")
|
||||
response = await call_next(request)
|
||||
except ApiError as error:
|
||||
response = error_response(request, error)
|
||||
except Exception as error:
|
||||
# Не печатаем тело запроса или текст исключения: там могут быть сообщения.
|
||||
logger.error("%s request_id=%s", type(error).__name__, request.state.request_id)
|
||||
response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка сервера"))
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
logger.info(
|
||||
"%s %s status=%s duration_ms=%.2f request_id=%s",
|
||||
request.method, path, response.status_code,
|
||||
(perf_counter() - started) * 1000, request.state.request_id,
|
||||
)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
def handle_api_error(request: Request, error: ApiError):
|
||||
return error_response(request, error)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
def handle_validation_error(request: Request, error: RequestValidationError):
|
||||
# Контракт требует 400 и наш формат ошибки, а не стандартный ответ FastAPI.
|
||||
return error_response(request, ApiError(400, "invalid_request", "Неверные поля или параметры запроса"))
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
def handle_http_error(request: Request, error: HTTPException):
|
||||
code = "not_found" if error.status_code == 404 else "invalid_request"
|
||||
message = "Адрес не найден" if error.status_code == 404 else "Недопустимый HTTP-запрос"
|
||||
response = error_response(request, ApiError(error.status_code, code, message))
|
||||
if error.headers:
|
||||
response.headers.update(error.headers)
|
||||
return response
|
||||
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
db.ready()
|
||||
auth.ready()
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def create_user(data: CreateUser):
|
||||
return storage.create_user(data.username, data.display_name, passwords.hash_password(data.password))
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def current_user(request: Request):
|
||||
return request.state.user
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(request: Request, data: CreateChat):
|
||||
return storage.create_chat(request.state.user["id"], data.title, data.member_ids)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(request: Request, limit: str = "50", cursor: str | None = None):
|
||||
user_id = request.state.user["id"]
|
||||
return storage.list_chats(user_id, limit, cursor)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(request: Request, chat_id: UUID):
|
||||
return storage.get_chat(request.state.user["id"], str(chat_id))
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(request: Request, chat_id: UUID, data: CreateMessage):
|
||||
return storage.create_message(request.state.user["id"], str(chat_id), data.text)
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(request: Request, chat_id: UUID, limit: str = "50", cursor: str | None = None):
|
||||
return storage.list_messages(request.state.user["id"], str(chat_id), limit, cursor)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
def create_session(request: Request):
|
||||
return auth.create_session(request.state.user)
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def delete_session(request: Request):
|
||||
auth.logout(request.headers.get("Authorization"))
|
||||
return Response(status_code=204)
|
||||
Reference in New Issue
Block a user