Baseflask8 / app.py
flpolprojects's picture
Update app.py
daa7bba verified
raw
history blame
27 kB
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:
return json.load(file)
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)
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_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)
@app.route('/')
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">
<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: 100%;
height: 200px;
overflow: hidden;
border-radius: 8px;
margin-bottom: 15px;
}
.product-image img {
width: 100%;
height: 100%;
object-fit: cover;
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;
}
.product-price {
font-size: 1.3em;
color: #e74c3c;
font-weight: 700;
margin: 10px 0;
}
.product-description {
color: #7f8c8d;
font-size: 0.9em;
flex-grow: 1;
margin-bottom: 15px;
}
.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: inline-block;
font-weight: 500;
}
.product-button:hover {
background-color: #2980b9;
}
@media (max-width: 768px) {
.products-grid {
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 10px;
}
body {
padding: 10px;
}
h1 {
font-size: 1.8em;
margin-bottom: 20px;
}
.product {
padding: 10px;
}
.product-image {
height: 120px;
}
.product h2 {
font-size: 1em;
}
.product-price {
font-size: 1.1em;
}
.product-description {
font-size: 0.8em;
}
.product-button {
padding: 8px 15px;
font-size: 0.9em;
}
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.product {
animation: fadeIn 0.5s ease-out forwards;
}
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Modal Styles */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
.modal-content {
position: relative;
background-color: #fefefe;
margin: 10% auto; /* 15% from the top and centered */
padding: 20px;
border: 1px solid #888;
width: 80%;
max-width: 600px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
@keyframes animatetop {
from {top: -300px; opacity: 0}
to {top: 10%; opacity: 1}
}
/* The Close Button */
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
/* Image Carousel Styles */
.carousel-inner > .carousel-item > img {
margin: 0 auto;
}
</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>
</div>
{% endfor %}
</div>
</div>
<!-- The Modal -->
<div id="productModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">&times;</span>
<div id="modalContent">
<!-- Product details will be loaded here -->
</div>
</div>
</div>
<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>
// Function to open the modal
function openModal(index) {
loadProductDetails(index);
document.getElementById('productModal').style.display = "block";
}
// Function to close the modal
function closeModal() {
document.getElementById('productModal').style.display = "none";
}
// Function to load product details into the modal
function loadProductDetails(index) {
fetch('/product/' + index)
.then(response => response.text())
.then(data => {
document.getElementById('modalContent').innerHTML = data;
});
}
// Close the modal if the user clicks outside of it
window.onclick = function(event) {
if (event.target == document.getElementById('productModal')) {
closeModal();
}
}
</script>
</body>
</html>
'''
return render_template_string(catalog_html, products=products, repo_id=REPO_ID)
@app.route('/product/<int:index>')
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 id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<ol class="carousel-indicators">
{% if product.get('photos') %}
{% for photo in product['photos'] %}
<li data-target="#carouselExampleIndicators" data-slide-to="{{ loop.index0 }}" {% if loop.first %}class="active"{% endif %}></li>
{% endfor %}
{% endif %}
</ol>
<div class="carousel-inner">
{% if product.get('photos') %}
{% for photo in product['photos'] %}
<div class="carousel-item {% if loop.first %}active{% endif %}">
<img class="d-block w-100" src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ photo }}" alt="{{ product['name'] }}">
</div>
{% endfor %}
{% else %}
<div class="carousel-item active">
<img class="d-block w-100" src="https://via.placeholder.com/300" alt="No Image">
</div>
{% endif %}
</div>
<a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carouselExampleIndicators" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</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)
@app.route('/admin', methods=['GET', 'POST'])
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 = []
if photos_files:
if len(photos_files) > 5:
photos_files = photos_files[:5]
for photo in photos_files:
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)
except Exception as e:
logging.error(f"Ошибка при загрузке фото: {e}")
return f"Ошибка при загрузке фото: {e}", 500
finally:
os.remove(temp_path)
if name and price and description:
try:
price = float(price.replace(',', '.'))
except ValueError:
return "Ошибка: Цена должна быть числом.", 400
product = {
'name': name,
'price': price,
'description': description,
'photos': photos_list
}
products.append(product)
save_data(products)
return redirect(url_for('admin'))
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')
# Если загружены новые фото, обновляем список фотографий товара
if photos_files and any(photo.filename for photo in photos_files):
new_photos_list = []
if len(photos_files) > 5:
photos_files = photos_files[:5]
for photo in photos_files:
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)
except Exception as e:
logging.error(f"Ошибка при загрузке фото: {e}")
return f"Ошибка при загрузке фото: {e}", 500
finally:
os.remove(temp_path)
products[index]['photos'] = new_photos_list
products[index]['name'] = name
try:
price = float(price.replace(',', '.'))
except ValueError:
return "Ошибка: Цена должна быть числом.", 400
products[index]['price'] = price
products[index]['description'] = description
save_data(products)
return redirect(url_for('admin'))
elif action == 'delete':
index = int(request.form.get('index'))
del products[index]
save_data(products)
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;
}
@media (max-width: 600px) {
body {
margin: 10px;
}
h1 {
font-size: 24px;
}
form {
padding: 10px;
}
.product-item {
padding: 10px;
}
input[type="file"] {
margin-bottom: 10px;
}
}
</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">Фотографии товара (до 5):</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 %}
<img src="https://huggingface.co/datasets/{{ repo_id }}/resolve/main/photos/{{ product['photos'][0] }}"
alt="{{ product['name'] }}"
style="max-width: 100px;">
{% 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">Фотографии товара (до 5):</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)
@app.route('/backup', methods=['POST'])
def backup():
upload_db_to_hf()
return "Резервная копия успешно создана.", 200
@app.route('/download', methods=['GET'])
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)