Skip to content

Commit 46be84d

Browse files
committed
Class methods instead of queries and code changes
1 parent 5b4931a commit 46be84d

File tree

7 files changed

+55
-40
lines changed

7 files changed

+55
-40
lines changed

project_files/admin.py

Lines changed: 9 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def admin():
4343
@captcha('admin_user')
4444
def admin_user():
4545

46-
users = Users.query.all()
46+
users = Users().all_rows
4747

4848
if request.method == 'POST':
4949
searching = request.form['search']
@@ -128,8 +128,8 @@ def admin_user():
128128

129129
if selected_action == 'test email':
130130
users_emails = []
131-
for id in data:
132-
user = Users.query.filter_by(id=id).first()
131+
for user_id in data:
132+
user = Users.query.filter_by(id=user_id).first()
133133
users_emails.append(user.email)
134134

135135
task = queue.enqueue(
@@ -161,7 +161,7 @@ def admin_user():
161161
# @captcha('admin_blocked')
162162
def admin_blocked():
163163

164-
blocked = BlockedUsers.query.all()
164+
blocked = BlockedUsers().all_rows
165165

166166
if request.method == 'POST':
167167
searching = request.form['search']
@@ -212,7 +212,7 @@ def admin_blocked():
212212
@captcha('admin_product')
213213
def admin_product():
214214

215-
products = Products.query.all()
215+
products = Products().all_rows
216216

217217
if request.method == 'POST':
218218
searching = request.form['search']
@@ -474,14 +474,10 @@ def add_blocked():
474474
def update_blocked(id):
475475

476476
blocked = BlockedUsers.query.get_or_404(id)
477-
477+
478478
if request.method == 'POST':
479-
blocked.username = not_null(request.form['username'])
480-
blocked.ip = not_null( request.form['ip'])
481-
blocked.date = not_null( request.form['date'])
482-
483479
try:
484-
db.session.commit()
480+
blocked.update_row(**dict(request.form))
485481
return redirect(url_for('admin_blocked'))
486482

487483
except Exception as e:
@@ -562,16 +558,10 @@ def update_product(id):
562558
product = Products.query.get_or_404(id)
563559

564560
if request.method == 'POST':
565-
product.name = not_null(request.form['name'])
566-
product.category = not_null(request.form['category'])
567-
product.company = not_null(request.form['company'])
568-
product.price = not_null(request.form['price'])
569-
product.old_price = not_null(request.form['old_price'])
570-
product.date = not_null(request.form['date'])
571561

572562
try:
573-
db.session.commit()
574-
save_price(data=[product])
563+
product.update_row(**dict(request.form))
564+
save_price(product=product)
575565
return redirect( url_for('admin_product'))
576566

577567
except Exception as e:

project_files/database.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
class Base():
99

1010
@property
11-
def show_all_rows(self):
11+
def all_rows(self):
1212
return self.query.all()
1313

1414

15-
def show_one_row(self, column, value):
15+
def show_row(self, column, value):
1616
filter_condition = {column: value}
1717
return self.query.filter_by(**filter_condition).first()
1818

@@ -24,6 +24,8 @@ def add_row_to_db(self):
2424

2525
def update_row(self, **kwargs):
2626
for key, value in kwargs.items():
27+
if value == '' or value == None:
28+
return ValueError('Field can not be empty')
2729
setattr(self, key, value)
2830
db.session.commit()
2931

@@ -33,7 +35,8 @@ def delete_row(self):
3335
db.session.commit()
3436

3537

36-
class Users(UserMixin, db.Model, Base):
38+
39+
class Users(db.Model, UserMixin, Base):
3740
id = db.Column(db.Integer, primary_key=True)
3841
username = db.Column(db.String(30), unique=True, nullable=False)
3942
first_name = db.Column(db.String(30),unique=False, nullable=False)
@@ -51,15 +54,18 @@ class Users(UserMixin, db.Model, Base):
5154
nullable=False,
5255
default=datetime.now().strftime('%d-%m-%Y %H:%M:%S')
5356
)
54-
product = db.relationship('UsersProducts', backref=db.backref('users', lazy=True))
57+
product = db.relationship(
58+
'UsersProducts',
59+
backref=db.backref('users', lazy=True)
60+
)
5561

5662

5763
def __repr__(self):
5864
return f'Users(id={self.id}, username={self.username})'
5965

6066

6167

62-
class BlockedUsers(db.Model, Base):
68+
class BlockedUsers(Base, db.Model):
6369
id = db.Column(db.Integer, primary_key=True)
6470
username = db.Column(db.String(30), unique=False, nullable=False)
6571
ip = db.Column(db.String(30), unique=False, nullable=False)
@@ -77,7 +83,7 @@ def __repr__(self):
7783

7884

7985

80-
class Products(db.Model, Base):
86+
class Products(Base, db.Model):
8187
id = db.Column(db.Integer, primary_key=True)
8288
name = db.Column(db.String(30), unique=False, nullable=False)
8389
category = db.Column(db.String(30), unique=False, nullable=False)
@@ -90,19 +96,30 @@ class Products(db.Model, Base):
9096
nullable=False,
9197
default=datetime.now().strftime('%d-%m-%Y %H:%M:%S')
9298
)
93-
user = db.relationship('UsersProducts', backref=db.backref('products', lazy=True))
99+
user = db.relationship(
100+
'UsersProducts',
101+
backref=db.backref('products', lazy=True)
102+
)
94103

95104

96105
def __repr__(self):
97-
return f'Products(id={self.id}, username={self.name})'
106+
return f'Products(id={self.id}, name={self.name})'
98107

99108

100109

101110

102-
class UsersProducts(db.Model, Base):
111+
class UsersProducts(Base, db.Model):
103112
id = db.Column(db.Integer, primary_key=True)
104-
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
105-
product_id = db.Column(db.Integer, db.ForeignKey('products.id'), nullable=False)
113+
user_id = db.Column(
114+
db.Integer,
115+
db.ForeignKey('users.id'),
116+
nullable=False
117+
)
118+
product_id = db.Column(
119+
db.Integer,
120+
db.ForeignKey('products.id'),
121+
nullable=False
122+
)
106123
date = db.Column(
107124
db.String,
108125
nullable=False,

project_files/scripts/actions.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,13 +48,13 @@ def backup(model):
4848
path = USERS
4949
elif model == Products:
5050
path = PRODUCTS
51-
else:
51+
elif model == BlockedUsers:
5252
path = BLOCKED_USERS
5353

5454
data_from_file = open_json(file_path=path)
5555
objects_list = []
5656
columns = tuple([m.key for m in model.__table__.columns])
57-
model_data = model.query.all()
57+
model_data = model().all_rows
5858

5959
for row in model_data:
6060
data = {}
@@ -82,7 +82,8 @@ def restore_database(model):
8282
account_type=data['account_type'],
8383
active=data['active'],
8484
points=data['points'],
85-
newsletter=data['newsletter']
85+
newsletter=data['newsletter'],
86+
date=data['date']
8687
)
8788
whether_exist = model.query.filter_by(username=data['username']).first()
8889

@@ -167,7 +168,7 @@ def account_deactivation(model, data):
167168
def delete_inactive_accounts():
168169
time.sleep(60)
169170
app.app_context().push()
170-
users = Users.query.all()
171+
users = Users().all_rows
171172

172173
for user in users:
173174
if user.active == False:
@@ -219,7 +220,7 @@ def send_newsletter():
219220

220221
if users := Users.query.filter_by(newsletter=True).all():
221222

222-
if products := Products.query.all():
223+
if products := Products().all_rows:
223224
products = products[-5:]
224225
mails = [user.email for user in users]
225226

project_files/scripts/functions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ def generator(answer, obstacle):
241241

242242
def unblock():
243243
app.app_context().push()
244-
blocked_users = BlockedUsers.query.all()
244+
blocked_users = BlockedUsers().all_rows
245245

246246
for blocked in blocked_users:
247247
if (datetime.now() > string_to_date(blocked.date)):
@@ -288,7 +288,7 @@ def similar_products_to_queries(username):
288288
queries = open_json(file_path=DATA)
289289
user_queries = [query for query in queries if query['username'] == username]
290290

291-
if products := Products.query.all():
291+
if products := Products().all_rows:
292292

293293
if len(user_queries) == 0:
294294
random_products = []

project_files/templates/admin/update_blocked.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11

22

33
<form action="/update-blocked/{{blocked.id}}" method="post">
4-
4+
<label for="id">id:</label>
5+
<input type="text" name="id" value="{{id.username}}"/>
6+
<br>
57
<label for="username">username:</label>
68
<input type="text" name="username" value="{{blocked.username}}"/>
79
<br>

project_files/templates/admin/update_product.html

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11

22

33
<form action="/update-product/{{product.id}}" method="post">
4-
4+
5+
<label for="id">id</label>
6+
<input type="number" name="id" value="{{product.id}}"/>
7+
<br>
58
<label for="name">name</label>
69
<input type="text" name="name" value="{{product.name}}"/>
710
<br>

project_files/templates/admin/update_user.html

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11

22

33
<form action="/update-user/{{user.id}}" method="post">
4-
4+
<label for="id">id</label>
5+
<input type="text" name="id" value="{{user.id}}"/>
6+
<br>
57
<label for="username">username</label>
68
<input type="text" name="username" value="{{user.username}}"/>
79
<br>

0 commit comments

Comments
 (0)