#!/usr/bin/env python3 import os, tempfile from flask import Flask, request, jsonify import boto3 from botocore.client import Config from botocore.exceptions import ClientError import pillow_heif from PIL import Image pillow_heif.register_heif_opener() app = Flask(__name__) app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 # 50MB S3_CONFIG = dict( endpoint_url='https://s3.regru.cloud', aws_access_key_id='TXBN3MRO1YCC2Y593URD', aws_secret_access_key='GIMA9lJetvXgMtl8GCO4dNSpJDGHvKgGBVfiA9zV', region_name='ru-1', config=Config(signature_version='s3v4') ) BUCKET = 'sleeptrip-dev' PREFIX = 'images/' ALLOWED = {'jpg', 'jpeg', 'png', 'gif', 'webp', 'mp4', 'mov', 'heic', 'heif'} MIME = { 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'png': 'image/png', 'gif': 'image/gif', 'webp': 'image/webp', 'mp4': 'video/mp4', 'mov': 'video/quicktime', 'heic': 'image/jpeg', 'heif': 'image/jpeg' } PAGE = """ Upload to S3

Upload → S3

sleeptrip-dev · s3.regru.cloud/images/

Перетащи или выбери файл
Загружаем...
Нажми чтобы скопировать

История

""" @app.route('/upload/') def index(): return PAGE @app.route('/upload/api', methods=['POST']) def upload_file(): if 'file' not in request.files: return jsonify({'error': 'Нет файла'}), 400 f = request.files['file'] if not f.filename: return jsonify({'error': 'Пустое имя файла'}), 400 ext = f.filename.rsplit('.', 1)[-1].lower() if '.' in f.filename else '' if ext not in ALLOWED: return jsonify({'error': 'Формат .{} не поддерживается'.format(ext)}), 400 original_name = os.path.splitext(f.filename)[0] # HEIC/HEIF → конвертируем в JPG is_heic = ext in ('heic', 'heif') out_ext = 'jpg' if is_heic else ext s3_key = '{}{}.{}'.format(PREFIX, original_name, out_ext) tmp_path = None try: with tempfile.NamedTemporaryFile(delete=False, suffix='.{}'.format(ext)) as tmp: f.save(tmp.name) tmp_path = tmp.name if is_heic: img = Image.open(tmp_path) converted = tmp_path.replace('.{}'.format(ext), '.jpg') img.convert('RGB').save(converted, 'JPEG', quality=92) os.unlink(tmp_path) tmp_path = converted import urllib3 urllib3.disable_warnings() s3 = boto3.client('s3', verify=False, **S3_CONFIG) s3.upload_file( tmp_path, BUCKET, s3_key, ExtraArgs={ 'ContentType': MIME.get(ext, 'application/octet-stream'), 'CacheControl': 'max-age=31536000' } ) url = 'https://s3.regru.cloud/{}/{}'.format(BUCKET, s3_key) # hint: HEIC was converted to JPG return jsonify({'url': url}) except Exception as e: return jsonify({'error': str(e)}), 500 finally: if tmp_path and os.path.exists(tmp_path): os.unlink(tmp_path) if __name__ == '__main__': app.run(host='127.0.0.1', port=9001, debug=False)