Files
mtusi2026lab4/scripts/load-50.py
T

76 lines
2.2 KiB
Python

import io
import os
import time
import uuid
import requests
from PIL import Image
BASE_URL = "http://localhost:8080"
COUNT = 50
def make_png(width, height):
img = Image.frombytes("RGB", (width, height), os.urandom(width * height * 3))
buf = io.BytesIO()
img.save(buf, format="PNG", optimize=False)
return buf.getvalue()
def register_and_login(username):
requests.post(f"{BASE_URL}/api/v1/users", json={
"username": username, "display_name": "Test", "password": "valid_password_123"
})
resp = requests.post(f"{BASE_URL}/api/v1/auth/sessions",
auth=(username, "valid_password_123"))
return resp.json()["token"]
def create_chat(token):
headers = {"Authorization": f"Bearer {token}"}
me = requests.get(f"{BASE_URL}/api/v1/users/me", headers=headers).json()
resp = requests.post(f"{BASE_URL}/api/v1/chats", headers=headers, json={
"title": "Cost Test", "member_ids": [me["id"]]
})
return resp.json()["id"]
def upload(token, chat_id, content, filename):
headers = {"Authorization": f"Bearer {token}", "Content-Type": "image/png"}
resp = requests.post(
f"{BASE_URL}/api/v1/chats/{chat_id}/attachments?filename={filename}",
headers=headers, data=content, timeout=60,
)
return resp.status_code
def main():
print(f"Загружаем {COUNT} файлов (по ~1 МБ)...")
token = register_and_login("cost_tester")
chat_id = create_chat(token)
print(f"Chat ID: {chat_id}")
content = make_png(200, 200)
print(f"Размер файла: {len(content) / 1024:.1f} КБ")
success = 0
errors = 0
start = time.monotonic()
for i in range(COUNT):
status = upload(token, chat_id, content, f"cost-{i}-{uuid.uuid4().hex[:6]}.png")
if status == 201:
success += 1
else:
errors += 1
if (i + 1) % 10 == 0:
print(f" Загружено: {i + 1}/{COUNT}")
elapsed = time.monotonic() - start
print(f"\n=== Результаты ===")
print(f"Успешно: {success}")
print(f"Ошибок: {errors}")
print(f"Время: {elapsed:.2f}s")
if __name__ == "__main__":
main()