Add file downloading

This commit is contained in:
2022-01-09 20:55:24 +03:00
parent cefc84af81
commit bb300daedd
5 changed files with 67 additions and 2 deletions

View File

@@ -0,0 +1,48 @@
from datetime import datetime
from typing import Optional
import httpx
from pydantic import BaseModel
from core.config import env_config
class UploadedFile(BaseModel):
id: int
backend: str
data: dict
upload_time: datetime
async def upload_file(content: bytes, filename: str, caption: str) -> UploadedFile:
headers = {"Authorization": env_config.FILES_SERVER_API_KEY}
async with httpx.AsyncClient() as client:
form = {"caption": caption}
files = {"file": (filename, content)}
response = await client.post(
f"{env_config.FILES_SERVER_URL}/api/v1/files/upload/",
data=form,
files=files,
headers=headers,
timeout=5 * 60,
)
return UploadedFile.parse_obj(response.json())
async def download_file(chat_id: int, message_id: int) -> Optional[bytes]:
headers = {"Authorization": env_config.FILES_SERVER_API_KEY}
async with httpx.AsyncClient(timeout=60) as client:
response = await client.get(
f"{env_config.FILES_SERVER_URL}"
f"/api/v1/files/download_by_message/{chat_id}/{message_id}",
headers=headers,
)
if response.status_code != 200:
return None
return response.content