50 lines
1.2 KiB
Python
50 lines
1.2 KiB
Python
import random
|
|
import shutil
|
|
import string
|
|
|
|
from fastapi import FastAPI, UploadFile
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
|
|
def generate_random_string(length=16):
|
|
"""Генерирует случайную строку заданной длины."""
|
|
characters = string.ascii_letters + string.digits
|
|
return ''.join(random.choice(characters) for _ in range(length))
|
|
|
|
|
|
app = FastAPI(
|
|
prefix="/api",
|
|
tags=["Сервак для загрузки"],
|
|
)
|
|
|
|
origins = []
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=origins,
|
|
allow_credentials=True,
|
|
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],
|
|
allow_headers=[
|
|
"Content-Type",
|
|
"Set-Cookie",
|
|
"Access-Control-Allow-Headers",
|
|
"Authorization",
|
|
"Accept"
|
|
],
|
|
)
|
|
|
|
app.mount("/static", StaticFiles(directory="app/static"), name="static")
|
|
|
|
|
|
@app.post('/images', response_model=dict[str, str])
|
|
async def upload_images(file: UploadFile):
|
|
name = generate_random_string()
|
|
image_url = f'static/images/{name}_avatar.png'
|
|
with open('app/' + image_url, 'wb+') as file_object:
|
|
shutil.copyfileobj(file.file, file_object)
|
|
return {'image_url': image_url}
|
|
|
|
|
|
|
|
|