-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
132 lines (113 loc) · 3.95 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import argparse
from datetime import datetime
import logging
from typing import List
from models.product import Product
from requests.exceptions import MissingSchema
from services.price import PriceHandler
from services.product import ProductOperations, MultipleProductsManager
from sqlalchemy.exc import IntegrityError
from database import session, Base, engine
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(name)-12s \
%(levelname)-8s %(message)s',
datefmt='%d-%m %H:%M',
filename='app.log',
filemode='a')
console = logging.StreamHandler()
console.setLevel(logging.INFO)
console_format = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s'
)
console.setFormatter(console_format)
logger = logging.getLogger('app')
logger.addHandler(console)
logger.info('Программа запущена')
Base.metadata.create_all(engine)
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
usage="%(prog)s [OPTION] [URL]...",
description="Проверка изменения цены на товары в магазине citilink.ru"
)
parser.add_argument(
"-m", "--menu",
action='store_true'
)
parser.add_argument(
"-u", "--update",
action='store_true'
)
parser.add_argument('urls', nargs='*')
return parser
def add_product(urls: List):
for url in urls:
try:
product = Product(url=url, update_date=datetime.now())
session.add(product)
session.flush()
except IntegrityError as e:
session.rollback()
logger.info(e.args)
else:
product_handler = ProductOperations(product)
try:
price = product_handler.get_name_and_price()['price']
except MissingSchema as e:
logger.info(f'Неправильный формат URL. {e.args}')
return
else:
price_handler = PriceHandler(product=product)
price_handler.append_new_price(price)
session.commit()
def update_products():
products_list = ProductOperations.get_all_products()
products_list_manager = MultipleProductsManager(products_list)
products_list_manager.check_for_price_updates()
session.commit()
def print_all_products():
products_list = ProductOperations.get_all_products()
[print(product, sep="\n") for product in products_list]
def show_price_history():
products_list = ProductOperations.get_all_products()
products_list_manager = MultipleProductsManager(products_list)
return products_list_manager.get_price_history_for_products_list()
def menu():
while True:
option = input(
"""Выберите действие:
1 - Добавить товар для отслеживания
2 - Показать все товары
3 - Обновить цены
4 - Показать историю цен
q - Выход
"""
)
if option == 'q':
break
elif option == '1':
url = input("Введите url товара для отлсеживания: ")
add_product(urls=[url])
elif option == '2':
print_all_products()
elif option == '3':
update_products()
elif option == '4':
print("\n-----\n".join(show_price_history()))
else:
print("Вы ввели неправильный символ")
logger.info('Завершение работы...')
def main():
parser = init_argparse()
args = parser.parse_args()
# if args.menu:
# menu()
if args.update:
update_products()
return
if args.urls:
add_product(args.urls)
return
else:
menu()
if __name__ == "__main__":
main()