refactor: оптимизация обработки статических файлов

This commit is contained in:
Vlad 2025-05-03 00:14:49 +03:00
parent c2acd9a6ca
commit 010e5817dc

43
app.py
View File

@ -786,26 +786,51 @@ def swagger_yaml():
@app.route('/static/<path:filename>') @app.route('/static/<path:filename>')
def serve_static(filename): def serve_static(filename):
try: try:
# Check file extension # Проверка расширения файла
allowed_extensions = {'.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg'} allowed_extensions = {'.css', '.js', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.svg', '.json'}
file_ext = os.path.splitext(filename)[1].lower() file_ext = os.path.splitext(filename)[1].lower()
if file_ext not in allowed_extensions: if file_ext not in allowed_extensions:
app.logger.warning(f'Attempt to access forbidden file type: {filename}') app.logger.warning(f'Попытка доступа к запрещенному типу файла: {filename}')
return 'Access denied', 403 return 'Access denied', 403
# Check path for directory traversal attempts # Проверка пути на directory traversal
safe_path = os.path.normpath(os.path.join('static', filename)) safe_path = os.path.normpath(os.path.join('static', filename))
if not safe_path.startswith('static'): if not safe_path.startswith('static'):
app.logger.warning(f'Attempt to access file outside static directory: {filename}') app.logger.warning(f'Попытка доступа к файлу вне директории static: {filename}')
return 'Access denied', 403 return 'Access denied', 403
# Log file access # Определение MIME-типа
app.logger.info(f'Access to static file: {filename}') mime_types = {
'.css': 'text/css',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.ico': 'image/x-icon',
'.svg': 'image/svg+xml'
}
mime_type = mime_types.get(file_ext, 'application/octet-stream')
# Логирование доступа
app.logger.info(f'Доступ к статическому файлу: {filename}')
response = make_response(send_from_directory('static', filename))
response.headers['Content-Type'] = mime_type
# Специальные заголовки для PWA файлов
if filename == 'manifest.json':
response.headers['Content-Type'] = 'application/manifest+json'
elif filename == 'sw.js':
response.headers['Service-Worker-Allowed'] = '/'
return response
return send_from_directory('static', filename)
except Exception as e: except Exception as e:
app.logger.error(f'Error accessing file {filename}: {str(e)}') app.logger.error(f'Ошибка доступа к файлу {filename}: {str(e)}')
return 'File not found', 404 return 'File not found', 404
if __name__ == '__main__': if __name__ == '__main__':