Spaces:
Paused
Paused
| from flask import Flask, render_template_string, request, redirect, url_for | |
| import json | |
| import os | |
| import logging | |
| import threading | |
| import time | |
| from datetime import datetime | |
| from huggingface_hub import HfApi, hf_hub_download | |
| from huggingface_hub.utils import RepositoryNotFoundError | |
| from werkzeug.utils import secure_filename | |
| app = Flask(__name__) | |
| DATA_FILE = 'products.json' | |
| # Настройки Hugging Face | |
| REPO_ID = "flpolprojects/Clients" | |
| HF_TOKEN_WRITE = os.getenv("HF_TOKEN") | |
| HF_TOKEN_READ = os.getenv("HF_TOKEN_READ") | |
| # Настройка логирования | |
| logging.basicConfig(level=logging.DEBUG) | |
| def load_data(): | |
| try: | |
| download_db_from_hf() | |
| with open(DATA_FILE, 'r', encoding='utf-8') as file: | |
| data = json.load(file) | |
| logging.info("Данные успешно загружены из JSON") | |
| return data | |
| except FileNotFoundError: | |
| logging.warning("Локальный файл базы данных не найден после скачивания.") | |
| return [] | |
| except json.JSONDecodeError: | |
| logging.error("Ошибка: Невозможно декодировать JSON файл.") | |
| return [] | |
| except RepositoryNotFoundError: | |
| logging.error("Репозиторий не найден. Создание локальной базы данных.") | |
| return [] | |
| except Exception as e: | |
| logging.error(f"Произошла ошибка при загрузке данных: {e}") | |
| return [] | |
| def save_data(data): | |
| try: | |
| with open(DATA_FILE, 'w', encoding='utf-8') as file: | |
| json.dump(data, file, ensure_ascii=False, indent=4) | |
| logging.info("Данные успешно сохранены в JSON") | |
| upload_db_to_hf() # Синхронизация с Hugging Face после сохранения | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении данных: {e}") | |
| raise | |
| def upload_db_to_hf(): | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=DATA_FILE, | |
| path_in_repo=DATA_FILE, | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Автоматическое резервное копирование базы данных {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}" | |
| ) | |
| logging.info("Резервная копия JSON базы успешно загружена на Hugging Face.") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке резервной копии: {e}") | |
| def download_db_from_hf(): | |
| try: | |
| hf_hub_download( | |
| repo_id=REPO_ID, | |
| filename=DATA_FILE, | |
| repo_type="dataset", | |
| token=HF_TOKEN_READ, | |
| local_dir=".", | |
| local_dir_use_symlinks=False | |
| ) | |
| logging.info("JSON база успешно скачана из Hugging Face.") | |
| except RepositoryNotFoundError as e: | |
| logging.error(f"Репозиторий не найден: {e}") | |
| raise | |
| except Exception as e: | |
| logging.error(f"Ошибка при скачивании JSON базы: {e}") | |
| raise | |
| def periodic_backup(): | |
| while True: | |
| upload_db_to_hf() | |
| time.sleep(15) | |
| def catalog(): | |
| products = load_data() | |
| catalog_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Каталог</title> | |
| <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> | |
| <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.css"> | |
| <style> | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; | |
| background-color: #f5f5f5; | |
| color: #333; | |
| line-height: 1.6; | |
| padding: 20px; | |
| } | |
| .container { | |
| max-width: 1200px; | |
| margin: 0 auto; | |
| } | |
| h1 { | |
| text-align: center; | |
| color: #2c3e50; | |
| margin-bottom: 40px; | |
| font-size: 2.5em; | |
| font-weight: 700; | |
| } | |
| .products-grid { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); | |
| gap: 20px; | |
| padding: 0 15px; | |
| } | |
| .product { | |
| background: #ffffff; | |
| border-radius: 12px; | |
| padding: 20px; | |
| transition: transform 0.3s ease, box-shadow 0.3s ease; | |
| display: flex; | |
| flex-direction: column; | |
| box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1); | |
| } | |
| .product:hover { | |
| transform: translateY(-5px); | |
| box-shadow: 0 5px 25px rgba(0, 0, 0, 0.15); | |
| } | |
| .product-image { | |
| width: 200px; | |
| height: 200px; | |
| background-color: #fff; | |
| border-radius: 8px; | |
| margin: 0 auto 15px; | |
| overflow: hidden; | |
| position: relative; | |
| display: flex; | |
| justify-content: center; | |
| align-items: center; | |
| } | |
| .product-image img { | |
| max-width: 200px; | |
| max-height: 200px; | |
| width: auto; | |
| height: auto; | |
| object-fit: contain; | |
| transition: transform 0.3s ease; | |
| } | |
| .product-image img:hover { | |
| transform: scale(1.05); | |
| } | |
| .product h2 { | |
| font-size: 1.2em; | |
| color: #2c3e50; | |
| margin-bottom: 10px; | |
| font-weight: 600; | |
| text-align: center; | |
| } | |
| .product-price { | |
| font-size: 1.3em; | |
| color: #e74c3c; | |
| font-weight: 700; | |
| margin: 10px 0; | |
| text-align: center; | |
| } | |
| .product-description { | |
| color: #7f8c8d; | |
| font-size: 0.9em; | |
| flex-grow: 1; | |
| margin-bottom: 15px; | |
| text-align: center; | |
| } | |
| .product-button { | |
| background-color: #3498db; | |
| color: white; | |
| padding: 10px 20px; | |
| border: none; | |
| border-radius: 5px; | |
| cursor: pointer; | |
| transition: background-color 0.3s ease; | |
| text-align: center; | |
| text-decoration: none; | |
| display: block; | |
| margin: 5px auto; | |
| font-weight: 500; | |
| } | |
| .product-button:hover { | |
| background-color: #2980b9; | |
| } | |
| .add-to-cart { | |
| background-color: #27ae60; | |
| } | |
| .add-to-cart:hover { | |
| background-color: #219653; | |
| } | |
| #cart-button { | |
| position: fixed; | |
| bottom: 20px; | |
| right: 20px; | |
| background-color: #e74c3c; | |
| color: white; | |
| border: none; | |
| border-radius: 50%; | |
| width: 60px; | |
| height: 60px; | |
| font-size: 20px; | |
| cursor: pointer; | |
| display: none; | |
| box-shadow: 0 2px 10px rgba(0,0,0,0.2); | |
| z-index: 1000; | |
| } | |
| #cart-button:hover { | |
| background-color: #c0392b; | |
| } | |
| .modal { | |
| display: none; | |
| position: fixed; | |
| z-index: 1001; | |
| left: 0; | |
| top: 0; | |
| width: 100%; | |
| height: 100%; | |
| overflow: auto; | |
| background-color: rgba(0,0,0,0.4); | |
| } | |
| .modal-content { | |
| position: relative; | |
| background-color: #fefefe; | |
| margin: 10% auto; | |
| padding: 20px; | |
| border: 1px solid #888; | |
| width: 80%; | |
| max-width: 600px; | |
| box-shadow: 0 4px 8px rgba(0,0,0,0.2); | |
| animation: animatetop 0.4s; | |
| } | |
| @keyframes animatetop { | |
| from {top: -300px; opacity: 0} | |
| to {top: 10%; opacity: 1} | |
| } | |
| .close { | |
| color: #aaa; | |
| float: right; | |
| font-size: 28px; | |
| font-weight: bold; | |
| cursor: pointer; | |
| } | |
| .close:hover { | |
| color: black; | |
| } | |
| .cart-item { | |
| display: flex; | |
| justify-content: space-between; | |
| align-items: center; | |
| padding: 10px 0; | |
| border-bottom: 1px solid #eee; | |
| } | |
| .cart-item img { | |
| width: 50px; | |
| height: 50px; | |
| object-fit: contain; | |
| background-color: #fff; | |
| margin-right: 10px; | |
| } | |
| .quantity-input { | |
| width: 60px; | |
| padding: 5px; | |
| margin: 10px 0; | |
| } | |
| .clear-cart { | |
| background-color: #e74c3c; | |
| margin-top: 10px; | |
| float: right; | |
| } | |
| .clear-cart:hover { | |
| background-color: #c0392b; | |
| } | |
| @media (max-width: 768px) { | |
| body { | |
| padding: 10px; | |
| } | |
| .products-grid { | |
| grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); | |
| gap: 15px; | |
| padding: 0 10px; | |
| } | |
| .product { | |
| padding: 15px; | |
| } | |
| .product-image { | |
| width: 150px; | |
| height: 150px; | |
| } | |
| .product-image img { | |
| max-width: 150px; | |
| max-height: 150px; | |
| } | |
| .product h2 { | |
| font-size: 1em; | |
| } | |
| .product-price { | |
| font-size: 1.1em; | |
| } | |
| .product-description { | |
| font-size: 0.85em; | |
| } | |
| .product-button { | |
| padding: 8px 15px; | |
| font-size: 0.9em; | |
| } | |
| #cart-button { | |
| width: 50px; | |
| height: 50px; | |
| font-size: 18px; | |
| bottom: 15px; | |
| right: 15px; | |
| } | |
| } | |
| @media (max-width: 480px) { | |
| .products-grid { | |
| grid-template-columns: 1fr; | |
| gap: 10px; | |
| } | |
| .product { | |
| padding: 10px; | |
| margin: 0 auto; | |
| max-width: 300px; | |
| } | |
| .product-image { | |
| width: 120px; | |
| height: 120px; | |
| } | |
| .product-image img { | |
| max-width: 120px; | |
| max-height: 120px; | |
| } | |
| h1 { | |
| font-size: 1.8em; | |
| margin-bottom: 20px; | |
| } | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <h1>Каталог товаров</h1> | |
| <div class="products-grid"> | |
| {% for product in products %} | |
| <div class="product"> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <div class="product-image"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| loading="lazy"> | |
| </div> | |
| {% endif %} | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="product-price">{{ product['price'] }} ₽</div> | |
| <p class="product-description">{{ product['description'][:100] }}{% if product['description']|length > 100 %}...{% endif %}</p> | |
| <button class="product-button" onclick="openModal({{ loop.index0 }})">Подробнее</button> | |
| <button class="product-button add-to-cart" onclick="openQuantityModal({{ loop.index0 }})">В корзину</button> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| </div> | |
| <!-- Product Modal --> | |
| <div id="productModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('productModal')">×</span> | |
| <div id="modalContent"></div> | |
| </div> | |
| </div> | |
| <!-- Quantity Modal --> | |
| <div id="quantityModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('quantityModal')">×</span> | |
| <h2>Укажите количество</h2> | |
| <input type="number" id="quantityInput" class="quantity-input" min="1" value="1"> | |
| <button class="product-button" onclick="confirmAddToCart()">Добавить</button> | |
| </div> | |
| </div> | |
| <!-- Cart Modal --> | |
| <div id="cartModal" class="modal"> | |
| <div class="modal-content"> | |
| <span class="close" onclick="closeModal('cartModal')">×</span> | |
| <h2>Корзина</h2> | |
| <div id="cartContent"></div> | |
| <div style="margin-top: 20px; text-align: right;"> | |
| <strong>Итого: <span id="cartTotal">0</span> ₽</strong> | |
| <button class="product-button clear-cart" onclick="clearCart()">Очистить корзину</button> | |
| </div> | |
| </div> | |
| </div> | |
| <button id="cart-button" onclick="openCartModal()">🛒</button> | |
| <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script> | |
| <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.5.3/dist/umd/popper.min.js"></script> | |
| <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/Swiper/10.2.0/swiper-bundle.min.js"></script> | |
| <script> | |
| const products = {{ products|tojson }}; | |
| let selectedProductIndex = null; | |
| function openModal(index) { | |
| console.log("Открытие модального окна для товара:", index); | |
| loadProductDetails(index); | |
| document.getElementById('productModal').style.display = "block"; | |
| } | |
| function closeModal(modalId) { | |
| console.log("Закрытие модального окна:", modalId); | |
| document.getElementById(modalId).style.display = "none"; | |
| } | |
| function loadProductDetails(index) { | |
| fetch('/product/' + index) | |
| .then(response => response.text()) | |
| .then(data => { | |
| document.getElementById('modalContent').innerHTML = data; | |
| initializeSwiper(); | |
| }) | |
| .catch(error => console.error('Ошибка загрузки деталей:', error)); | |
| } | |
| function initializeSwiper() { | |
| new Swiper('.swiper-container', { | |
| slidesPerView: 1, | |
| spaceBetween: 30, | |
| loop: true, | |
| grabCursor: true, | |
| pagination: { | |
| el: '.swiper-pagination', | |
| clickable: true, | |
| }, | |
| navigation: { | |
| nextEl: '.swiper-button-next', | |
| prevEl: '.swiper-button-prev', | |
| }, | |
| }); | |
| } | |
| function openQuantityModal(index) { | |
| console.log("Открытие окна количества для товара:", index); | |
| selectedProductIndex = index; | |
| document.getElementById('quantityModal').style.display = 'block'; | |
| document.getElementById('quantityInput').value = 1; | |
| } | |
| function confirmAddToCart() { | |
| console.log("Подтверждение добавления в корзину, индекс:", selectedProductIndex); | |
| if (selectedProductIndex === null || selectedProductIndex === undefined) { | |
| console.error("Товар не выбран!"); | |
| alert("Ошибка: Товар не выбран"); | |
| return; | |
| } | |
| const quantityInput = document.getElementById('quantityInput'); | |
| const quantity = parseInt(quantityInput.value) || 1; | |
| if (quantity <= 0) { | |
| console.warn("Некорректное количество:", quantity); | |
| alert("Пожалуйста, укажите количество больше 0"); | |
| return; | |
| } | |
| let cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const product = products[selectedProductIndex]; | |
| if (!product) { | |
| console.error("Продукт не найден по индексу:", selectedProductIndex); | |
| alert("Ошибка: Товар не найден"); | |
| return; | |
| } | |
| const existingItem = cart.find(item => item.name === product.name); | |
| if (existingItem) { | |
| existingItem.quantity += quantity; | |
| console.log("Увеличено количество существующего товара:", product.name, "на", quantity); | |
| } else { | |
| const newItem = { | |
| name: product.name, | |
| price: product.price, | |
| photo: product.photos && product.photos.length > 0 ? product.photos[0] : '', | |
| quantity: quantity | |
| }; | |
| cart.push(newItem); | |
| console.log("Добавлен новый товар в корзину:", newItem); | |
| } | |
| localStorage.setItem('cart', JSON.stringify(cart)); | |
| console.log("Корзина обновлена:", cart); | |
| closeModal('quantityModal'); | |
| updateCartButton(); | |
| } | |
| function updateCartButton() { | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartButton = document.getElementById('cart-button'); | |
| cartButton.style.display = cart.length > 0 ? 'block' : 'none'; | |
| console.log("Обновление кнопки корзины, элементов в корзине:", cart.length); | |
| } | |
| function openCartModal() { | |
| console.log("Открытие корзины"); | |
| const cart = JSON.parse(localStorage.getItem('cart') || '[]'); | |
| const cartContent = document.getElementById('cartContent'); | |
| let total = 0; | |
| if (cart.length === 0) { | |
| cartContent.innerHTML = '<p>Корзина пуста</p>'; | |
| } else { | |
| cartContent.innerHTML = cart.map(item => { | |
| const itemTotal = item.price * item.quantity; | |
| total += itemTotal; | |
| return ` | |
| <div class="cart-item"> | |
| <div style="display: flex; align-items: center;"> | |
| ${item.photo ? ` | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/${item.photo}" | |
| alt="${item.name}"> | |
| ` : ''} | |
| <div> | |
| <strong>${item.name}</strong> | |
| <p>${item.price} ₽ × ${item.quantity}</p> | |
| </div> | |
| </div> | |
| <span>${itemTotal} ₽</span> | |
| </div> | |
| `; | |
| }).join(''); | |
| } | |
| document.getElementById('cartTotal').textContent = total; | |
| document.getElementById('cartModal').style.display = 'block'; | |
| } | |
| function clearCart() { | |
| console.log("Очистка корзины"); | |
| localStorage.removeItem('cart'); | |
| closeModal('cartModal'); | |
| updateCartButton(); | |
| } | |
| window.onclick = function(event) { | |
| if (event.target.className === 'modal') { | |
| console.log("Закрытие модального окна по клику вне области"); | |
| event.target.style.display = "none"; | |
| } | |
| } | |
| console.log("Инициализация страницы, товары:", products); | |
| updateCartButton(); | |
| </script> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string(catalog_html, products=products, repo_id=REPO_ID) | |
| def product_detail(index): | |
| products = load_data() | |
| try: | |
| product = products[index] | |
| except IndexError: | |
| return "Продукт не найден", 404 | |
| detail_html = ''' | |
| <div class="container"> | |
| <h2>{{ product['name'] }}</h2> | |
| <div class="swiper-container"> | |
| <div class="swiper-wrapper"> | |
| {% if product.get('photos') %} | |
| {% for photo in product['photos'] %} | |
| <div class="swiper-slide" style="background-color: #fff; display: flex; justify-content: center; align-items: center;"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" | |
| alt="{{ product['name'] }}" | |
| style="max-width: 200px; max-height: 200px; width: auto; height: auto; object-fit: contain;"> | |
| </div> | |
| {% endfor %} | |
| {% else %} | |
| <div class="swiper-slide"> | |
| <img src="https://via.placeholder.com/200" alt="No Image"> | |
| </div> | |
| {% endif %} | |
| </div> | |
| <div class="swiper-pagination"></div> | |
| <div class="swiper-button-next"></div> | |
| <div class="swiper-button-prev"></div> | |
| </div> | |
| <p><strong>Цена:</strong> {{ product['price'] }} ₽</p> | |
| <p><strong>Описание:</strong> {{ product['description'] }}</p> | |
| </div> | |
| ''' | |
| return render_template_string(detail_html, product=product, repo_id=REPO_ID) | |
| def admin(): | |
| products = load_data() | |
| if request.method == 'POST': | |
| action = request.form.get('action') | |
| if action == 'add': | |
| name = request.form.get('name') | |
| price = request.form.get('price') | |
| description = request.form.get('description') | |
| photos_files = request.files.getlist('photos') | |
| photos_list = [] | |
| logging.info(f"Добавление нового товара: name={name}, price={price}, description={description}") | |
| if photos_files: | |
| for i, photo in enumerate(photos_files[:2]): # Ограничение до 2 фото | |
| if photo and photo.filename: | |
| photo_filename = secure_filename(photo.filename) | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| photo.save(temp_path) | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Добавлено фото для товара {name}" | |
| ) | |
| photos_list.append(photo_filename) | |
| logging.info(f"Фото успешно загружено: {photo_filename}") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото: {e}") | |
| return f"Ошибка при загрузке фото: {e}", 500 | |
| finally: | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| if not name or not price or not description: | |
| logging.error("Ошибка: Не все обязательные поля заполнены") | |
| return "Ошибка: Заполните все обязательные поля", 400 | |
| try: | |
| price = float(price.replace(',', '.')) | |
| except ValueError: | |
| logging.error("Ошибка: Цена должна быть числом") | |
| return "Ошибка: Цена должна быть числом", 400 | |
| new_product = { | |
| 'name': name, | |
| 'price': price, | |
| 'description': description, | |
| 'photos': photos_list | |
| } | |
| products.append(new_product) | |
| logging.info(f"Новый товар добавлен в список: {new_product}") | |
| try: | |
| save_data(products) | |
| logging.info("Товар успешно сохранен в базе данных") | |
| return redirect(url_for('admin')) | |
| except Exception as e: | |
| logging.error(f"Ошибка при сохранении товара: {e}") | |
| return f"Ошибка при сохранении товара: {e}", 500 | |
| elif action == 'edit': | |
| index = int(request.form.get('index')) | |
| name = request.form.get('name') | |
| price = request.form.get('price') | |
| description = request.form.get('description') | |
| photos_files = request.files.getlist('photos') | |
| logging.info(f"Редактирование товара с индексом {index}") | |
| if photos_files and any(photo.filename for photo in photos_files): | |
| new_photos_list = [] | |
| for i, photo in enumerate(photos_files[:2]): | |
| if photo and photo.filename: | |
| photo_filename = secure_filename(photo.filename) | |
| uploads_dir = 'uploads' | |
| os.makedirs(uploads_dir, exist_ok=True) | |
| temp_path = os.path.join(uploads_dir, photo_filename) | |
| photo.save(temp_path) | |
| try: | |
| api = HfApi() | |
| api.upload_file( | |
| path_or_fileobj=temp_path, | |
| path_in_repo=f"photos/{photo_filename}", | |
| repo_id=REPO_ID, | |
| repo_type="dataset", | |
| token=HF_TOKEN_WRITE, | |
| commit_message=f"Обновлено фото для товара {name}" | |
| ) | |
| new_photos_list.append(photo_filename) | |
| logging.info(f"Фото обновлено: {photo_filename}") | |
| except Exception as e: | |
| logging.error(f"Ошибка при загрузке фото: {e}") | |
| return f"Ошибка при загрузке фото: {e}", 500 | |
| finally: | |
| if os.path.exists(temp_path): | |
| os.remove(temp_path) | |
| products[index]['photos'] = new_photos_list | |
| products[index]['name'] = name | |
| try: | |
| products[index]['price'] = float(price.replace(',', '.')) | |
| except ValueError: | |
| logging.error("Ошибка: Цена должна быть числом") | |
| return "Ошибка: Цена должна быть числом", 400 | |
| products[index]['description'] = description | |
| save_data(products) | |
| logging.info(f"Товар с индексом {index} успешно отредактирован") | |
| return redirect(url_for('admin')) | |
| elif action == 'delete': | |
| index = int(request.form.get('index')) | |
| logging.info(f"Удаление товара с индексом {index}") | |
| del products[index] | |
| save_data(products) | |
| logging.info("Товар успешно удален") | |
| return redirect(url_for('admin')) | |
| admin_html = ''' | |
| <!DOCTYPE html> | |
| <html lang="ru"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Админ-панель</title> | |
| <style> | |
| body { | |
| font-family: Arial, sans-serif; | |
| margin: 20px; | |
| background-color: #f9f9f9; | |
| } | |
| h1 { | |
| color: #333; | |
| } | |
| form { | |
| background-color: #fff; | |
| padding: 20px; | |
| border: 1px solid #ddd; | |
| border-radius: 5px; | |
| max-width: 100%; | |
| margin-bottom: 20px; | |
| } | |
| label { | |
| display: block; | |
| margin-top: 10px; | |
| color: #555; | |
| } | |
| input, textarea { | |
| width: 100%; | |
| padding: 8px; | |
| margin-top: 5px; | |
| border: 1px solid #ddd; | |
| border-radius: 4px; | |
| box-sizing: border-box; | |
| } | |
| button { | |
| margin-top: 15px; | |
| padding: 10px 15px; | |
| background-color: #28a745; | |
| color: white; | |
| border: none; | |
| border-radius: 4px; | |
| cursor: pointer; | |
| } | |
| button:hover { | |
| background-color: #218838; | |
| } | |
| .product-list { | |
| margin-top: 20px; | |
| } | |
| .product-item { | |
| background-color: #fff; | |
| border: 1px solid #ddd; | |
| padding: 15px; | |
| margin-bottom: 10px; | |
| border-radius: 5px; | |
| } | |
| .edit-form { | |
| margin-top: 10px; | |
| padding: 10px; | |
| border: 1px solid #ddd; | |
| border-radius: 5px; | |
| background-color: #f9f9f9; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Добавление товара</h1> | |
| <form method="POST" enctype="multipart/form-data"> | |
| <input type="hidden" name="action" value="add"> | |
| <label for="name">Название товара:</label> | |
| <input type="text" id="name" name="name" required> | |
| <label for="price">Цена:</label> | |
| <input type="number" id="price" name="price" step="0.01" required> | |
| <label for="description">Описание:</label> | |
| <textarea id="description" name="description" rows="4" required></textarea> | |
| <label for="photos">Фотографии товара (максимум 2):</label> | |
| <input type="file" id="photos" name="photos" accept="image/*" multiple> | |
| <button type="submit">Добавить товар</button> | |
| </form> | |
| <h2>Управление базой данных</h2> | |
| <form method="POST" action="{{ url_for('backup') }}"> | |
| <button type="submit">Создать резервную копию</button> | |
| </form> | |
| <form method="GET" action="{{ url_for('download') }}"> | |
| <button type="submit">Скачать базу данных</button> | |
| </form> | |
| <h2>Список товаров</h2> | |
| <div class="product-list"> | |
| {% for product in products %} | |
| <div class="product-item"> | |
| <h3>{{ product['name'] }}</h3> | |
| <p><strong>Цена:</strong> {{ product['price'] }} руб.</p> | |
| <p><strong>Описание:</strong> {{ product['description'] }}</p> | |
| {% if product.get('photos') and product['photos']|length > 0 %} | |
| <div style="background-color: #fff; width: 100px; height: 100px; display: flex; justify-content: center; align-items: center;"> | |
| <img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}" | |
| alt="{{ product['name'] }}" | |
| style="max-width: 100px; max-height: 100px; width: auto; height: auto; object-fit: contain;"> | |
| </div> | |
| {% endif %} | |
| <details> | |
| <summary>Редактировать</summary> | |
| <form method="POST" enctype="multipart/form-data" class="edit-form"> | |
| <input type="hidden" name="action" value="edit"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <label for="name">Название товара:</label> | |
| <input type="text" id="name" name="name" value="{{ product['name'] }}" required> | |
| <label for="price">Цена:</label> | |
| <input type="number" id="price" name="price" step="0.01" value="{{ product['price'] }}" required> | |
| <label for="description">Описание:</label> | |
| <textarea id="description" name="description" rows="4" required>{{ product['description'] }}</textarea> | |
| <label for="photos">Фотографии товара (максимум 2):</label> | |
| <input type="file" id="photos" name="photos" accept="image/*" multiple> | |
| <button type="submit">Сохранить изменения</button> | |
| </form> | |
| </details> | |
| <form method="POST"> | |
| <input type="hidden" name="action" value="delete"> | |
| <input type="hidden" name="index" value="{{ loop.index0 }}"> | |
| <button type="submit">Удалить</button> | |
| </form> | |
| </div> | |
| {% endfor %} | |
| </div> | |
| </body> | |
| </html> | |
| ''' | |
| return render_template_string(admin_html, products=products, repo_id=REPO_ID) | |
| def backup(): | |
| upload_db_to_hf() | |
| return "Резервная копия успешно создана.", 200 | |
| def download(): | |
| download_db_from_hf() | |
| return "База данных успешно скачана.", 200 | |
| if __name__ == '__main__': | |
| backup_thread = threading.Thread(target=periodic_backup, daemon=True) | |
| backup_thread.start() | |
| try: | |
| load_data() | |
| except Exception as e: | |
| logging.error(f"Не удалось загрузить базу данных при запуске: {e}") | |
| app.run(debug=True, host='0.0.0.0', port=7860) |