Skip to content

Commit

Permalink
Переделал на flask_sqlalch
Browse files Browse the repository at this point in the history
  • Loading branch information
OopsWoopsssss committed Nov 9, 2021
1 parent 3b01577 commit 529b9a3
Show file tree
Hide file tree
Showing 4 changed files with 90 additions and 100 deletions.
55 changes: 30 additions & 25 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import os
from flask import Flask, flash, request, render_template, redirect, url_for, Response, session
from flask import Flask, flash, request, render_template, redirect, url_for, Response, current_app
from flask_login import (
LoginManager,
login_user,
Expand All @@ -8,22 +8,27 @@
current_user,
)
from werkzeug.utils import secure_filename
from .forms import ProductForm, CategoryForm, get_category
from .forms import ProductForm, CategoryForm, get_category, LoginForm, RegisterForm
# Удалить потом flask_bcrypt
from .db import db_session
from .models import Product, Category, User, PosterImage, ShotsImage, category_product, Cart, ProductCart
from .forms import LoginForm, RegisterForm
from .models import Product, Category, User, PosterImage, ShotsImage, category_product, Cart, ProductCart, db


# Заводим Фласк


def create_app():
app = Flask(__name__)
app.config.from_pyfile('config.py')
app.secret_key = os.urandom(512)
login_manager = LoginManager()
login_manager.init_app(app)
# Присваиваем функцию для работы с логином.
login_manager.login_view = "login"

with app.app_context():
db.init_app(app)
db.create_all()

@login_manager.user_loader
def load_user(user_id):
return User.query.get(user_id)
Expand All @@ -35,8 +40,8 @@ def add_category():
form = CategoryForm(request.form)
if request.method == 'POST' and form.validate():
category = Category(name=form.name.data)
db_session.add(category)
db_session.commit()
db.session.add(category)
db.session.commit()
flash('Категория успешно добавлена')
return redirect(url_for("add_category"))
return render_template('add_category.html', form=form)
Expand Down Expand Up @@ -69,8 +74,8 @@ def add_product():
for name in form.category.data:
category = Category.query.filter_by(name=name).all()
product.category.append(category[0])
db_session.add(product)
db_session.commit()
db.session.add(product)
db.session.commit()
flash('Товар успешно добавлен')
return redirect('/admin/add-product/')
return render_template('add_product.html', form=form)
Expand Down Expand Up @@ -110,8 +115,8 @@ def product_delete(product_id):
if product is None:
flash('Товар не найдена')
return redirect('/admin/')
db_session.delete(product)
db_session.commit()
db.session.delete(product)
db.session.commit()
flash('Товар успешно удален')
return redirect('/admin/')

Expand Down Expand Up @@ -146,8 +151,8 @@ def registration() -> str:
if form.validate_on_submit():
new_user = User(username=form.username.data, role="user")
new_user.set_password(form.password.data)
db_session.add(new_user)
db_session.commit()
db.session.add(new_user)
db.session.commit()
return redirect(url_for("all_product"))

return render_template("register.html", form=form)
Expand Down Expand Up @@ -204,15 +209,15 @@ def update_product(product_id):
if poster_name:
for image in product.image_poster:
image_poster_delete = PosterImage.query.filter(PosterImage.id.contains(image.id)).first()
db_session.delete(image_poster_delete)
db.session.delete(image_poster_delete)
mimetype_poster = poster.mimetype
img_poster = PosterImage(img=poster.read(), name=poster_name, mimetype=mimetype_poster)
product.image_poster.append(img_poster)
shots_all = request.files.getlist(form.image_shots.name)
if shots_all[0].filename:
for shot in product.image_shots:
image_shots_delete = ShotsImage.query.filter(ShotsImage.id.contains(shot.id)).first()
db_session.delete(image_shots_delete)
db.session.delete(image_shots_delete)
for shots in shots_all:
shot_name = secure_filename(shots.filename)
mimetype_poster = shots.mimetype
Expand All @@ -223,7 +228,7 @@ def update_product(product_id):
for name in form.category.data:
category = Category.query.filter_by(name=name).all()
product.category.append(category[0])
db_session.commit()
db.session.commit()
flash('Товар успешно изменен')
return redirect(f'/admin/update-product/{product_id}')
elif request.method == 'GET':
Expand All @@ -245,14 +250,14 @@ def cart():
if product_cart:
cart_user.total_product = sum([product.qty for product in cart_user.product])
cart_user.total_price = sum([product.qty * product.add_product_cart.price for product in cart_user.product])
db_session.commit()
db.session.commit()

return render_template('cart.html', cart=cart_user)

def create_cart(user_id):
user_cart = Cart(user_id=user_id)
db_session.add(user_cart)
db_session.commit()
db.session.add(user_cart)
db.session.commit()

@app.route('/add-cart/<int:product_id>', methods=['GET', 'POST'])
def add_cart(product_id):
Expand All @@ -269,15 +274,15 @@ def add_cart(product_id):
product_cart = ProductCart.query.filter_by(product_cart=product_id, user_id=user_id).first()
if not product_cart:
add_product_cart = ProductCart(product_cart=product_id, qty=1, user_id=user_id)
db_session.add(add_product_cart)
db_session.commit()
db.session.add(add_product_cart)
db.session.commit()
product_cart = ProductCart.query.filter_by(product_cart=product_id, user_id=user_id).first()
else:
product_cart.qty += 1
db_session.commit()
db.session.commit()
product_cart = ProductCart.query.filter_by(product_cart=product_id, user_id=user_id).first()
cart_user.product.append(product_cart)
db_session.commit()
db.session.commit()
return redirect(url_for("all_product"))

@app.route('/delete_product_cart/<int:product_id>', methods=['GET', 'POST'])
Expand All @@ -291,7 +296,7 @@ def delete_product_cart(product_id):
cart_user.total_product -= product_cart.qty
cart_user.total_price -= product_cart.add_product_cart.price * product_cart.qty
cart_user.product.remove(product_cart)
db_session.commit()
db.session.commit()
return redirect('/cart')

@app.route('/change-quantity/<int:product_id>/<minusplus>', methods=['GET', 'POST'])
Expand All @@ -304,7 +309,7 @@ def change_quantity(product_id, minusplus):
product_cart.qty -= 1
elif minusplus == 'plus':
product_cart.qty += 1
db_session.commit()
db.session.commit()
return redirect('/cart')

return app
4 changes: 4 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import os
basedir = os.path.abspath(os.path.dirname(__file__))

SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, '..', 'shop.db')
9 changes: 0 additions & 9 deletions src/db.py

This file was deleted.

122 changes: 56 additions & 66 deletions src/models.py
Original file line number Diff line number Diff line change
@@ -1,78 +1,71 @@
from sqlalchemy import (
Column,
Integer,
String,
Text,
Boolean,
ForeignKey,
Table,
BLOB,
)
from sqlalchemy.orm import relationship, backref
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from .db import BDConnector, engine
from flask_sqlalchemy import SQLAlchemy


db = SQLAlchemy()

""" Дополнительная страница для связи Многие-ко-Многим (Категории - Продукт) """
category_product = Table(
category_product = db.Table(
"category_product",
BDConnector.metadata,
Column("category_id", Integer, ForeignKey("category.id")),
Column("product_id", Integer, ForeignKey("product.id")),
db.metadata,
db.Column("category_id", db.Integer, db.ForeignKey("category.id")),
db.Column("product_id", db.Integer, db.ForeignKey("product.id")),
)

poster_product = Table(
poster_product = db.Table(
"poster_product",
BDConnector.metadata,
Column("poster_id", Integer, ForeignKey("poster.id")),
Column("product_id", Integer, ForeignKey("product.id")),
db.metadata,
db.Column("poster_id", db.Integer, db.ForeignKey("poster.id")),
db.Column("product_id", db.Integer, db.ForeignKey("product.id")),
)

shots_product = Table(
shots_product = db.Table(
"shots_product",
BDConnector.metadata,
Column("shots_id", Integer, ForeignKey("shots.id")),
Column("product_id", Integer, ForeignKey("product.id")),
db.metadata,
db.Column("shots_id", db.Integer, db.ForeignKey("shots.id")),
db.Column("product_id", db.Integer, db.ForeignKey("product.id")),
)

product_cart = Table('product_cart',
BDConnector.metadata,
Column('productcart_id', Integer, ForeignKey('productcart.id')),
Column('cart_id', Integer, ForeignKey('cart.id'))
product_cart = db.Table('product_cart',
db.metadata,
db.Column('productcart_id', db.Integer, db.ForeignKey('productcart.id')),
db.Column('cart_id', db.Integer, db.ForeignKey('cart.id'))
)


class Category(BDConnector):
class Category(db.Model):
"""Категории"""

__tablename__ = "category"

id = Column(Integer, primary_key=True)
name = Column(String(length=60), unique=True)
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(length=60), unique=True)

def __repr__(self):
return f"Категория: {self.name}"


class Product(BDConnector):
class Product(db.Model):
"""Настольная игра"""

__tablename__ = "product"

id = Column(Integer, primary_key=True)
name = Column(String(length=120), unique=True)
title = Column(String(length=240), unique=True)
price = Column(Integer())
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(length=120), unique=True)
title = db.Column(db.String(length=240), unique=True)
price = db.Column(db.Integer())
category = relationship(
"Category", secondary=category_product, backref=backref("products", lazy=True)
)
description = Column(Text(), unique=True)
description = db.Column(db.Text(), unique=True)
image_poster = relationship('PosterImage', secondary=poster_product, cascade='all, delete-orphan',
single_parent=True,
backref=backref('products', lazy=True))
image_shots = relationship('ShotsImage', secondary=shots_product, cascade='all, delete-orphan', single_parent=True,
backref=backref('products', lazy=True, ))
stock = Column(Boolean())
stock = db.Column(db.Boolean())

product_cart = relationship('ProductCart', backref='add_product_cart', lazy='dynamic')

Expand All @@ -81,15 +74,15 @@ def __repr__(self):


# Работа с пользователем.
class User(BDConnector, UserMixin):
class User(db.Model, UserMixin):
"""Пользователи"""

__tablename__ = "users"

id = Column(Integer, primary_key=True)
username = Column(String(64), nullable=False, index=True, unique=True)
password = Column(String(255), nullable=False)
role = Column(String(40), index=True)
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), nullable=False, index=True, unique=True)
password = db.Column(db.String(255), nullable=False)
role = db.Column(db.String(40), index=True)

def set_password(self, password):
"""Хеширование пароля"""
Expand All @@ -107,44 +100,41 @@ def __repr__(self):
return f"<Пользователь {self.username}, Роль: {self.role}>"


class PosterImage(BDConnector):
class PosterImage(db.Model):
__tablename__ = "poster"

id = Column(Integer, primary_key=True)
img = Column(BLOB, unique=True, nullable=False)
name = Column(Text, nullable=False)
mimetype = Column(Text, nullable=False)
id = db.Column(db.Integer, primary_key=True)
img = db.Column(db.BLOB, unique=True, nullable=False)
name = db.Column(db.Text, nullable=False)
mimetype = db.Column(db.Text, nullable=False)


class ShotsImage(BDConnector):
class ShotsImage(db.Model):
__tablename__ = "shots"

id = Column(Integer, primary_key=True)
img = Column(BLOB, unique=True, nullable=False)
name = Column(Text, nullable=False)
mimetype = Column(Text, nullable=False)
id = db.Column(db.Integer, primary_key=True)
img = db.Column(db.BLOB, unique=True, nullable=False)
name = db.Column(db.Text, nullable=False)
mimetype = db.Column(db.Text, nullable=False)


class Cart(BDConnector):
class Cart(db.Model):
__tablename__ = 'cart'

id = Column(Integer, primary_key=True)
user_id = Column(Integer())
total_product = Column(Integer(), default=0)
total_price = Column(Integer(), default=0)
in_oder = Column(Boolean(), default=True)
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer())
total_product = db.Column(db.Integer(), default=0)
total_price = db.Column(db.Integer(), default=0)
in_oder = db.Column(db.Boolean(), default=True)
product = relationship('ProductCart', secondary=product_cart, cascade='all, delete-orphan',
single_parent=True,
backref=backref('cart', lazy=True))


class ProductCart(BDConnector):
class ProductCart(db.Model):
__tablename__ = 'productcart'
id = Column(Integer, primary_key=True)
user_id = Column(Integer())
product_cart = Column(Integer, ForeignKey('product.id'))
qty = Column(Integer(), default=0)

id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer())
product_cart = db.Column(db.Integer, db.ForeignKey('product.id'))
qty = db.Column(db.Integer(), default=0)

# Создание БД
BDConnector.metadata.create_all(bind=engine)

0 comments on commit 529b9a3

Please sign in to comment.