Baseflask / app.py
Aleksmorshen's picture
Update app.py
9509b14 verified
raw
history blame
2.96 kB
from flask import Flask, request, redirect import json import os
app = Flask(name) DB_FILE = 'data.json'
def load_products(): # Создаём файл, если его нет if not os.path.exists(DB_FILE): with open(DB_FILE, 'w') as f: json.dump([], f)
try:
with open(DB_FILE, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
return [] # Если файл пустой или повреждён, возвращаем пустой список
except Exception as e:
print(f"Ошибка при загрузке данных: {e}")
return []
def save_products(products): try: with open(DB_FILE, 'w') as f: json.dump(products, f, indent=4, ensure_ascii=False) except Exception as e: print(f"Ошибка при сохранении данных: {e}")
def html_wrapper(content): return f''' <!DOCTYPE html> <html> <head> <title>Каталог</title> <style> body {{ font-family: Arial, sans-serif; margin: 20px; }} .header {{ font-size: 24px; margin-bottom: 20px; }} .products {{ display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; }} .product {{ border: 1px solid #ddd; padding: 15px; border-radius: 5px; }} .product img {{ max-width: 200px; max-height: 200px; }} form {{ max-width: 500px; margin: 20px auto; }} input, textarea {{ width: 100%; margin: 5px 0; padding: 8px; }} button {{ background: #4CAF50; color: white; padding: 10px; border: none; cursor: pointer; }} nav {{ margin-bottom: 20px; }} a {{ margin-right: 15px; text-decoration: none; color: #333; }} </style> </head> <body> <nav> <a href="/">Каталог</a> <a href="/admin">Админка</a> </nav> {content} </body> </html> '''
@app.route('/') def catalog(): products = load_products() products_html = ''.join([ f'''<div class="product"> <h3>{p['name']}</h3> <img src="{p['image']}" alt="{p['name']}"> <p>{p['description']}</p> <p>Цена: {p['price']} руб.</p> </div>''' for p in products ]) return html_wrapper(f''' <div class="header">Каталог товаров</div> <div class="products">{products_html}</div> ''')
@app.route('/admin', methods=['GET', 'POST']) def admin(): if request.method == 'POST': products = load_products() products.append({ 'name': request.form['name'], 'description': request.form['description'], 'price': request.form['price'], 'image': request.form['image'] }) save_products(products) return redirect('/admin')
return html_wrapper('''
<div class="header">Админ-панель</div>
<form method="POST">
<input type="text" name="name" placeholder="Название" required>
<textarea name="description" placeholder="Описание" required></textarea>
<input type="number" name="price" placeholder="Цена" required>
<input type="url" name="image" placeholder="URL изображения" required>
<button type="submit">Добавить товар</button>
</form>
''')
if name == 'main': app.run(host='0.0.0.0', port=7860)