Skip to content

Commit 344c54f

Browse files
committed
Updated
1 parent 4e5b3dc commit 344c54f

File tree

5 files changed

+120
-50
lines changed

5 files changed

+120
-50
lines changed
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
uvicorn market.main:app --reload --app-dir src/
1+
uvicorn market.main:app --reload --app-dir=src/ -port=7777
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
C:\Users\ipetrash\AppData\Local\Programs\Python\Python312\python.exe -m uvicorn market.main:app --reload --app-dir=src/ --port=7777

fastapi__examples/-market_from_stepic/src/market/db.py

+83-29
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,22 @@
1111
from market.models import User, Product, ShoppingCart, UserRole
1212

1313

14+
class NotFoundException(Exception):
15+
pass
16+
17+
1418
class DB:
1519
KEY_USERS: str = "users"
1620
KEY_PRODUCTS: str = "products"
1721
KEY_SHOPPING_CARTS: str = "shopping_carts"
1822

1923
db_name: str = str(DB_FILE_NAME)
2024

25+
def _generate_id(self) -> str:
26+
return str(uuid4())
27+
2128
def _do_init_db_objects(self):
2229
with self.get_shelve() as db:
23-
print(dict(db))
24-
2530
if self.KEY_USERS not in db:
2631
db[self.KEY_USERS] = dict()
2732

@@ -31,18 +36,18 @@ def _do_init_db_objects(self):
3136
if self.KEY_SHOPPING_CARTS not in db:
3237
db[self.KEY_SHOPPING_CARTS] = dict()
3338

34-
if not db[self.KEY_USERS]:
35-
admin = User(
36-
# Это uuid4 – уникальный идентификатор пользователя
37-
id="29ae7ebf-4445-42f2-9548-a3a54f095220",
38-
role=UserRole.ADMIN,
39-
username="admin",
40-
password="Admin_4321!",
41-
)
42-
db[self.KEY_USERS][admin.id] = admin
43-
39+
has_key_users = bool(db[self.KEY_USERS])
4440
has_key_products = bool(db[self.KEY_PRODUCTS])
4541

42+
# В create_user и так открывается get_shelve
43+
if not has_key_users:
44+
self.create_user(
45+
role=UserRole.ADMIN,
46+
username="admin",
47+
password="Admin_4321!",
48+
id="29ae7ebf-4445-42f2-9548-a3a54f095220",
49+
)
50+
4651
# В create_product и так открывается get_shelve
4752
if not has_key_products:
4853
self.create_product(
@@ -96,28 +101,59 @@ def get_users(
96101

97102
return filtered_users
98103

99-
def create_user(self, user: User):
104+
def create_user(
105+
self,
106+
role: UserRole,
107+
username: str,
108+
password: str,
109+
id: str | None = None,
110+
) -> User:
100111
with self.get_shelve() as db:
101-
db[self.KEY_USERS][user.id] = user
112+
obj = User(
113+
id=id if id else self._generate_id(),
114+
role=role,
115+
username=username,
116+
password=password,
117+
)
118+
db[self.KEY_USERS][obj.id] = obj
119+
return obj
102120

103-
def create_product(self, name: str, price_minor: int, description: str):
121+
def create_product(self, name: str, price_minor: int, description: str) -> Product:
104122
with self.get_shelve() as db:
105123
obj = Product(
106-
id=str(uuid4()),
124+
id=self._generate_id(),
107125
name=name,
108126
price_minor=price_minor,
109127
description=description,
110128
)
111-
112129
db[self.KEY_PRODUCTS][obj.id] = obj
130+
return obj
113131

114132
def get_products(self) -> list[Product]:
115133
with self.get_shelve() as db:
116134
return list(db[self.KEY_PRODUCTS].values())
117135

118-
def create_shopping_cart(self, shopping_cart: ShoppingCart):
136+
def create_shopping_cart(self, product_ids: list[str]) -> ShoppingCart:
137+
with self.get_shelve() as db:
138+
obj = ShoppingCart(
139+
id=self._generate_id(),
140+
product_ids=product_ids,
141+
)
142+
db[self.KEY_SHOPPING_CARTS][obj.id] = obj
143+
return obj
144+
145+
def update_shopping_cart(
146+
self,
147+
shopping_cart_id: str,
148+
product_ids: list[str],
149+
):
150+
# TODO: дублирует
119151
with self.get_shelve() as db:
120-
db[self.KEY_SHOPPING_CARTS][shopping_cart.id] = shopping_cart
152+
shopping_cart: ShoppingCart | None = self.get_shopping_cart(shopping_cart_id)
153+
if not shopping_cart:
154+
raise NotFoundException(f"Shopping cart #{shopping_cart_id} not found!")
155+
156+
shopping_cart.product_ids = product_ids
121157

122158
def get_shopping_carts(self) -> list[ShoppingCart]:
123159
with self.get_shelve() as db:
@@ -127,21 +163,39 @@ def get_shopping_cart(self, id: str) -> ShoppingCart | None:
127163
with self.get_shelve() as db:
128164
return db[self.KEY_SHOPPING_CARTS].get(id)
129165

130-
# TODO: Для добавления продукта нужен только id
131166
def add_product_in_shopping_cart(
132-
self, product: Product, shopping_cart: ShoppingCart
167+
self,
168+
shopping_cart_id: str,
169+
product_id: str,
133170
):
134-
shopping_cart.products.append(product)
135-
# TODO: ?
136-
self.create_shopping_cart(shopping_cart)
171+
# TODO: дублирует
172+
with self.get_shelve() as db:
173+
if product_id not in db[self.KEY_PRODUCTS]:
174+
raise NotFoundException(f"Product #{product_id} not found!")
175+
176+
shopping_cart: ShoppingCart | None = self.get_shopping_cart(shopping_cart_id)
177+
if not shopping_cart:
178+
raise NotFoundException(f"Shopping cart #{shopping_cart_id} not found!")
179+
180+
shopping_cart.product_ids.append(product_id)
181+
self.update_shopping_cart(shopping_cart_id, shopping_cart.product_ids)
137182

138-
# TODO: Для удаления продукта нужен только id
139183
def remove_product_from_shopping_cart(
140-
self, product: Product, shopping_cart: ShoppingCart
184+
self,
185+
shopping_cart_id: str,
186+
product_id: str,
141187
):
142-
shopping_cart.products.remove(product)
143-
# TODO: ?
144-
self.create_shopping_cart(shopping_cart)
188+
# TODO: дублирует
189+
with self.get_shelve() as db:
190+
if product_id not in db[self.KEY_PRODUCTS]:
191+
raise NotFoundException(f"Product #{product_id} not found!")
192+
193+
shopping_cart: ShoppingCart | None = self.get_shopping_cart(shopping_cart_id)
194+
if not shopping_cart:
195+
raise NotFoundException(f"Shopping cart #{shopping_cart_id} not found!")
196+
197+
shopping_cart.product_ids.remove(product_id)
198+
self.update_shopping_cart(shopping_cart_id, shopping_cart.product_ids)
145199

146200

147201
db = DB()

fastapi__examples/-market_from_stepic/src/market/models.py

+3-13
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@
55

66

77
import enum
8-
9-
# TODO: Мб использовать pydantic? Разве это не про одно и тоже в schemas.py
108
from dataclasses import dataclass
119

1210

@@ -41,22 +39,14 @@ class ShoppingCart:
4139
"""Корзина с товарами"""
4240

4341
id: str
44-
# # TODO: А откуда взять, если не будет аутентификации
45-
# # т.е. клиенты сами должны помнить id корзин, иначе корзины потеряются
46-
# # TODO: Мб еще время создания корзины добавить?
47-
# user_id: str
48-
products: list[Product]
42+
product_ids: list[str]
4943

5044

5145
@dataclass
5246
class Order:
5347
"""Заказ"""
5448

49+
# TODO: Статус заказа - создан, в обработке, завершен, отменен
5550
id: str
5651
email: str
57-
# user_id: str # TODO: ?
58-
# TODO: Мб еще время создания заказа добавить?
59-
# TODO: Мб еще статус заказа добавить
60-
# + Enum
61-
shopping_cart: ShoppingCart
62-
52+
shopping_cart_id: str

fastapi__examples/-market_from_stepic/src/market/services.py

+32-7
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,6 @@
44
__author__ = "ipetrash"
55

66

7-
# TODO:
8-
from uuid import uuid4
9-
107
from market.models import User, Product, ShoppingCart
118
from market.db import db
129

@@ -20,11 +17,39 @@ def get_products() -> list[Product]:
2017

2118

2219
def create_product(
23-
name: str,
24-
price_minor: int, # Копейки
25-
description: str,
20+
name: str,
21+
price_minor: int, # Копейки
22+
description: str,
2623
) -> Product:
27-
return db.create_product(name=name, price_minor=price_minor, description=description)
24+
return db.create_product(
25+
name=name, price_minor=price_minor, description=description
26+
)
27+
28+
29+
def create_shopping_cart() -> ShoppingCart:
30+
return db.create_shopping_cart(
31+
product_ids=[],
32+
)
33+
34+
35+
def add_product_in_shopping_cart(
36+
shopping_cart_id: str,
37+
product_id: str,
38+
):
39+
return db.add_product_in_shopping_cart(
40+
shopping_cart_id=shopping_cart_id,
41+
product_id=product_id,
42+
)
43+
44+
45+
def remove_product_from_shopping_cart(
46+
shopping_cart_id: str,
47+
product_id: str,
48+
):
49+
return db.remove_product_from_shopping_cart(
50+
shopping_cart_id=shopping_cart_id,
51+
product_id=product_id,
52+
)
2853

2954

3055
def get_shopping_carts() -> list[ShoppingCart]:

0 commit comments

Comments
 (0)