360 lines
11 KiB
Python
360 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
Phone Store — интернет-магазин мобильных телефонов
|
||
Flask-приложение с SQLite
|
||
"""
|
||
|
||
from flask import (Flask, render_template, request, redirect, url_for,
|
||
session, flash, jsonify)
|
||
import sqlite3
|
||
import os
|
||
from dotenv import load_dotenv
|
||
from datetime import datetime
|
||
from urllib.parse import urlsplit
|
||
|
||
app = Flask(__name__)
|
||
|
||
# Путь к базе данных и настройкам
|
||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||
load_dotenv(os.path.join(BASE_DIR, '.env'))
|
||
|
||
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
|
||
if not app.config['SECRET_KEY']:
|
||
raise RuntimeError("Не задан SECRET_KEY. Создайте файл .env.")
|
||
|
||
DB_PATH = os.path.join(BASE_DIR, 'database.db')
|
||
|
||
def is_safe_redirect_url(target):
|
||
"""Разрешает перенаправление только внутри текущего сайта."""
|
||
if not target or '\\' in target:
|
||
return False
|
||
|
||
try:
|
||
parsed = urlsplit(target)
|
||
except ValueError:
|
||
return False
|
||
|
||
if parsed.scheme or parsed.netloc:
|
||
return (
|
||
parsed.scheme in ('http', 'https')
|
||
and parsed.netloc == request.host
|
||
)
|
||
|
||
return target.startswith('/') and not target.startswith('//')
|
||
|
||
|
||
def get_db_connection():
|
||
"""Создаёт соединение с базой данных"""
|
||
conn = sqlite3.connect(DB_PATH)
|
||
conn.row_factory = sqlite3.Row # доступ к колонкам по имени
|
||
return conn
|
||
|
||
|
||
def get_cart():
|
||
# Корзина хранит только ID товаров и количество.
|
||
raw_cart = session.get('cart', {})
|
||
if not isinstance(raw_cart, dict):
|
||
raw_cart = {}
|
||
|
||
cart = {}
|
||
|
||
for product_id, value in raw_cart.items():
|
||
try:
|
||
pid = str(int(product_id))
|
||
if int(pid) <= 0:
|
||
continue
|
||
|
||
# Поддержка старого формата сессии.
|
||
quantity = value.get('quantity') if isinstance(value, dict) else value
|
||
quantity = int(quantity)
|
||
except (TypeError, ValueError, AttributeError):
|
||
continue
|
||
|
||
if quantity > 0:
|
||
cart[pid] = min(quantity, 99)
|
||
|
||
if cart != raw_cart:
|
||
session['cart'] = cart
|
||
session.modified = True
|
||
|
||
return cart
|
||
|
||
|
||
def save_cart(cart):
|
||
session['cart'] = cart
|
||
session.modified = True
|
||
|
||
|
||
def get_cart_items():
|
||
# Загружаем актуальные данные товаров из базы.
|
||
cart = get_cart()
|
||
if not cart:
|
||
return []
|
||
|
||
conn = get_db_connection()
|
||
try:
|
||
placeholders = ','.join('?' for _ in cart)
|
||
rows = conn.execute(
|
||
f'SELECT id, name, price, image FROM products '
|
||
f'WHERE id IN ({placeholders})',
|
||
tuple(int(pid) for pid in cart)
|
||
).fetchall()
|
||
finally:
|
||
conn.close()
|
||
|
||
products = {str(row['id']): dict(row) for row in rows}
|
||
items = []
|
||
valid_cart = {}
|
||
|
||
for pid, quantity in cart.items():
|
||
product = products.get(pid)
|
||
if product is None:
|
||
continue
|
||
|
||
product['quantity'] = quantity
|
||
items.append(product)
|
||
valid_cart[pid] = quantity
|
||
|
||
if valid_cart != cart:
|
||
save_cart(valid_cart)
|
||
|
||
return items
|
||
|
||
|
||
def get_cart_count():
|
||
return sum(get_cart().values())
|
||
|
||
|
||
def get_cart_total():
|
||
return sum(
|
||
item['price'] * item['quantity']
|
||
for item in get_cart_items()
|
||
)
|
||
|
||
|
||
@app.context_processor
|
||
def inject_cart_info():
|
||
"""Добавляет актуальную информацию о корзине во все шаблоны."""
|
||
items = get_cart_items()
|
||
return {
|
||
'cart_count': sum(item['quantity'] for item in items),
|
||
'cart_total': sum(
|
||
item['price'] * item['quantity'] for item in items
|
||
)
|
||
}
|
||
|
||
|
||
@app.route('/')
|
||
def index():
|
||
"""Главная страница с каталогом"""
|
||
search = request.args.get('search', '').strip()
|
||
brand = request.args.get('brand', '').strip()
|
||
sort = request.args.get('sort', '')
|
||
|
||
conn = get_db_connection()
|
||
query = 'SELECT * FROM products WHERE 1=1'
|
||
params = []
|
||
|
||
if search:
|
||
query += ' AND (name LIKE ? OR brand LIKE ?)'
|
||
params.extend([f'%{search}%', f'%{search}%'])
|
||
|
||
if brand:
|
||
query += ' AND brand = ?'
|
||
params.append(brand)
|
||
|
||
if sort == 'price_asc':
|
||
query += ' ORDER BY price ASC'
|
||
elif sort == 'price_desc':
|
||
query += ' ORDER BY price DESC'
|
||
else:
|
||
query += ' ORDER BY id ASC'
|
||
|
||
products = conn.execute(query, params).fetchall()
|
||
|
||
# Список брендов для фильтра
|
||
brands = conn.execute(
|
||
'SELECT DISTINCT brand FROM products ORDER BY brand'
|
||
).fetchall()
|
||
conn.close()
|
||
|
||
return render_template(
|
||
'index.html',
|
||
products=products,
|
||
brands=brands,
|
||
search=search,
|
||
selected_brand=brand,
|
||
sort=sort
|
||
)
|
||
|
||
|
||
@app.route('/product/<int:product_id>')
|
||
def product_detail(product_id):
|
||
"""Страница подробной информации о товаре"""
|
||
conn = get_db_connection()
|
||
product = conn.execute(
|
||
'SELECT * FROM products WHERE id = ?', (product_id,)
|
||
).fetchone()
|
||
conn.close()
|
||
|
||
if product is None:
|
||
flash('Товар не найден', 'error')
|
||
return redirect(url_for('index'))
|
||
|
||
return render_template('product.html', product=product)
|
||
|
||
|
||
@app.route('/add_to_cart/<int:product_id>', methods=['POST'])
|
||
def add_to_cart(product_id):
|
||
"""Добавление товара в корзину"""
|
||
conn = get_db_connection()
|
||
product = conn.execute(
|
||
'SELECT * FROM products WHERE id = ?', (product_id,)
|
||
).fetchone()
|
||
conn.close()
|
||
|
||
if product is None:
|
||
flash('Товар не найден', 'error')
|
||
return redirect(url_for('index'))
|
||
|
||
cart = get_cart()
|
||
pid = str(product_id)
|
||
|
||
if cart.get(pid, 0) >= 99:
|
||
flash('Достигнуто максимальное количество товара в корзине (99)', 'error')
|
||
else:
|
||
cart[pid] = cart.get(pid, 0) + 1
|
||
save_cart(cart)
|
||
flash(f'«{product["name"]}» добавлен в корзину', 'success')
|
||
|
||
# Возврат только на безопасный адрес внутри сайта.
|
||
next_url = request.form.get('next') or request.referrer
|
||
if not is_safe_redirect_url(next_url):
|
||
next_url = url_for('index')
|
||
|
||
return redirect(next_url)
|
||
|
||
|
||
@app.route('/cart')
|
||
def cart():
|
||
"""Страница корзины"""
|
||
items = get_cart_items()
|
||
total = sum(item['price'] * item['quantity'] for item in items)
|
||
return render_template('cart.html', items=items, total=total)
|
||
|
||
|
||
@app.route('/update_cart/<int:product_id>', methods=['POST'])
|
||
def update_cart(product_id):
|
||
"""Изменение количества товара в корзине"""
|
||
action = request.form.get('action')
|
||
cart = get_cart()
|
||
pid = str(product_id)
|
||
|
||
if pid in cart:
|
||
if action == 'increase':
|
||
if cart[pid] < 99:
|
||
cart[pid] += 1
|
||
else:
|
||
flash('Достигнуто максимальное количество товара в корзине (99)', 'error')
|
||
elif action == 'decrease':
|
||
cart[pid] -= 1
|
||
if cart[pid] <= 0:
|
||
del cart[pid]
|
||
flash('Товар удалён из корзины', 'info')
|
||
elif action == 'remove':
|
||
del cart[pid]
|
||
flash('Товар удалён из корзины', 'info')
|
||
|
||
save_cart(cart)
|
||
|
||
return redirect(url_for('cart'))
|
||
|
||
|
||
@app.route('/clear_cart', methods=['POST'])
|
||
def clear_cart():
|
||
"""Очистка корзины"""
|
||
session.pop('cart', None)
|
||
flash('Корзина очищена', 'info')
|
||
return redirect(url_for('cart'))
|
||
|
||
|
||
@app.route('/checkout', methods=['GET', 'POST'])
|
||
def checkout():
|
||
# Загружаем товары и актуальные цены из базы.
|
||
items = get_cart_items()
|
||
if not items:
|
||
flash('Корзина пуста', 'error')
|
||
return redirect(url_for('cart'))
|
||
|
||
total = sum(item['price'] * item['quantity'] for item in items)
|
||
|
||
if request.method == 'POST':
|
||
name = request.form.get('name', '').strip()
|
||
phone = request.form.get('phone', '').strip()
|
||
address = request.form.get('address', '').strip()
|
||
|
||
errors = []
|
||
if not name or len(name) < 2:
|
||
errors.append('Укажите корректное имя')
|
||
if not phone or len(phone) < 10:
|
||
errors.append('Укажите корректный номер телефона')
|
||
if not address or len(address) < 5:
|
||
errors.append('Укажите адрес доставки')
|
||
|
||
if errors:
|
||
for err in errors:
|
||
flash(err, 'error')
|
||
return render_template(
|
||
'checkout.html', items=items, total=total,
|
||
name=name, phone=phone, address=address
|
||
)
|
||
|
||
# Повторно загружаем товары перед сохранением заказа.
|
||
items = get_cart_items()
|
||
if not items:
|
||
flash('Товары в корзине больше недоступны', 'error')
|
||
return redirect(url_for('cart'))
|
||
|
||
total = sum(item['price'] * item['quantity'] for item in items)
|
||
|
||
items_str = '; '.join(
|
||
f"{item['name']} x{item['quantity']}" for item in items
|
||
)
|
||
|
||
conn = get_db_connection()
|
||
try:
|
||
conn.execute(
|
||
'INSERT INTO orders (customer_name, phone, address, total, items) '
|
||
'VALUES (?, ?, ?, ?, ?)',
|
||
(name, phone, address, total, items_str)
|
||
)
|
||
conn.commit()
|
||
finally:
|
||
conn.close()
|
||
|
||
session.pop('cart', None)
|
||
flash('Заказ успешно оформлен! Мы свяжемся с вами в ближайшее время.', 'success')
|
||
return redirect(url_for('index'))
|
||
|
||
return render_template('checkout.html', items=items, total=total)
|
||
|
||
|
||
@app.route('/api/cart_count')
|
||
def api_cart_count():
|
||
"""API для получения количества товаров в корзине (для JS)"""
|
||
return jsonify({'count': get_cart_count()})
|
||
|
||
|
||
if __name__ == '__main__':
|
||
# Инициализация БД при первом локальном запуске.
|
||
if not os.path.exists(DB_PATH):
|
||
from init_db import init_db
|
||
init_db()
|
||
|
||
print('=' * 50)
|
||
print('Phone Store — интернет-магазин мобильных телефонов')
|
||
print('Запуск сервера: http://127.0.0.1:5000')
|
||
print('=' * 50)
|
||
port = int(os.environ.get('PORT', 5000))
|
||
app.run(host='0.0.0.0', port=port, debug=False)
|