Добавлен роутер загрузки изображений

This commit is contained in:
urec56 2024-02-12 15:06:52 +03:00
parent 633f628d44
commit d090e5d85c
4 changed files with 32 additions and 1 deletions

View file

@ -19,6 +19,8 @@ class Settings(BaseSettings):
SMTP_USER: str SMTP_USER: str
SMTP_PASS: str SMTP_PASS: str
IMAGE_UPLOAD_SERVER: str
class Config: class Config:
env_file = ".env" env_file = ".env"

View file

@ -0,0 +1,27 @@
from fastapi import APIRouter, UploadFile, HTTPException
import httpx
from app.config import settings
router = APIRouter(
prefix="/images",
tags=["Загрузка картинок"]
)
@router.post('')
async def upload_image(file: UploadFile):
remote_server_url = settings.IMAGE_UPLOAD_SERVER + "images"
async with httpx.AsyncClient() as client:
try:
file_content = await file.read()
response = await client.post(remote_server_url, files={"file": file_content})
if response.status_code != 200:
raise HTTPException(status_code=response.status_code,
detail="Ошибка при загрузке файла на удаленный сервер")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
image_name = response.json()['image_url']
image_url = '/'.join(image_name.split('/')[1:])
image_url = settings.IMAGE_UPLOAD_SERVER + image_url
return image_url

View file

@ -11,6 +11,7 @@ from app.users.chat.router import router as chat_router
from app.users.router import router as user_router from app.users.router import router as user_router
from app.pages.router import router as pages_router from app.pages.router import router as pages_router
from app.users.chat.websocket import router as websocket_router from app.users.chat.websocket import router as websocket_router
from app.images.router import router as image_router
app = FastAPI( app = FastAPI(
title="Чат BP", title="Чат BP",
@ -21,6 +22,7 @@ app.include_router(websocket_router)
# app.include_router(chat_router) # app.include_router(chat_router)
app.include_router(user_router) app.include_router(user_router)
app.include_router(pages_router) app.include_router(pages_router)
app.include_router(image_router)
origins = ["http://localhost:5173"] origins = ["http://localhost:5173"]

View file

@ -26,7 +26,7 @@ class ConnectionManager(WebSocket):
async def broadcast(self, user_id: int, chat_id: int, message: str): async def broadcast(self, user_id: int, chat_id: int, message: str):
await self.add_message_to_database(user_id=user_id, chat_id=chat_id, message=message) await self.add_message_to_database(user_id=user_id, chat_id=chat_id, message=message)
for websocket in self.active_connections[chat_id]: for websocket in self.active_connections[chat_id]:
await websocket.send_text(parse_obj_as(SMessageSchema, {"message": message})) await websocket.send_text('{"message": ' + message + "}")
@staticmethod @staticmethod
async def add_message_to_database(user_id: int, chat_id: int, message: str): async def add_message_to_database(user_id: int, chat_id: int, message: str):