| 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: |
| return [] |
|
|
| def save_products(products): |
| with open(DB_FILE, 'w') as f: |
| json.dump(products, f) |
|
|
| 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']}"> |
| <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) |