From 07dbd5154785b48bb6bd92609f5df602ebe1433b Mon Sep 17 00:00:00 2001 From: Nyako Date: Fri, 11 Sep 2026 16:39:17 +0300 Subject: [PATCH] first commit --- run.py | 27 +++++++++++++++++++-------- 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/run.py b/run.py index 9989a23..c66842e 100644 --- a/run.py +++ b/run.py @@ -1,23 +1,21 @@ +import mimetypes import os import requests from urllib.parse import unquote, urlparse -# Список URL для скачивания URL_LIST = [ "https://example.com/sample.pdf", "https://example.com/image.png", ] -# Папка для сохранения -SAVE_DIR = "/dw" +# Изменено назначение папки +SAVE_DIR = "/dws" -def download_files(urls, destination_folder): - # Создаем папку, если она не существует +def download_files_with_mimetype(urls, destination_folder): os.makedirs(destination_folder, exist_ok=True) for url in urls: - # Извлекаем имя файла из URL parsed_url = urlparse(url) filename = os.path.basename(unquote(parsed_url.path)) or "downloaded_file" save_path = os.path.join(destination_folder, filename) @@ -26,14 +24,27 @@ def download_files(urls, destination_folder): response = requests.get(url, stream=True, timeout=15) response.raise_for_status() + # 1. Детект MIME-type из заголовков ответа + content_type = response.headers.get("Content-Type") + + # 2. Если заголовок отсутствует/обобщен, определяем по расширению файла + if not content_type or "octet-stream" in content_type: + guessed_type, _ = mimetypes.guess_type(filename) + content_type = guessed_type or "unknown/octet-stream" + + # Выводим чистый MIME-type без дополнительных параметров (например, без charset) + clean_mime = content_type.split(";")[0].strip() + with open(save_path, "wb") as f: for chunk in response.iter_content(chunk_size=8192): f.write(chunk) - print(f"Сохранен: {save_path}") + # Вывод результата и MIME-типа в консоль + print(f"Сохранен: {save_path} | MIME-type: {clean_mime}") + except Exception as e: print(f"Ошибка при скачивании {url}: {e}") if __name__ == "__main__": - download_files(URL_LIST, SAVE_DIR) \ No newline at end of file + download_files_with_mimetype(URL_LIST, SAVE_DIR) \ No newline at end of file