Repository navigation
HWs #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
StarostinLF
wants to merge
10
commits into
L1mple:main
Choose a base branch
from
StarostinLF:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+823
−3
Open
HWs #4
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
56371ba
Implement ASGI application with fibonacci, factorial, and mean endpoints
StarostinLF 28864f0
Merge branch 'L1mple:main' into main
StarostinLF 65d5995
Реализован REST API интернет-магазина
StarostinLF 66f0d08
Merge branch 'L1mple:main' into main
StarostinLF a4ba993
Настроена сборка образов Docker и мониторинг с помощью Prometheus и G…
StarostinLF 784429a
Merge branch 'L1mple:main' into main
StarostinLF 9fdf1a8
Добавлен сервис MySQL в docker-compose
StarostinLF fe4e037
Переписан магазин на хранение данных в БД
StarostinLF a6874bf
Добавлен скрипт с демонстрацией уровней изоляции транзакций
StarostinLF 32c068d
Merge branch 'L1mple:main' into main
StarostinLF File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,193 @@ | ||
| from fastapi import FastAPI | ||
| from http import HTTPStatus | ||
| from itertools import count | ||
|
|
||
| from fastapi import FastAPI, HTTPException, Query, Response | ||
| from pydantic import BaseModel, ConfigDict | ||
|
|
||
| app = FastAPI(title="Shop API") | ||
|
|
||
| items_db: dict[int, "Item"] = {} | ||
| carts_db: dict[int, dict[int, int]] = {} | ||
|
|
||
| item_id_seq = count(1) | ||
| cart_id_seq = count(1) | ||
|
|
||
|
|
||
| class Item(BaseModel): | ||
| id: int | ||
| name: str | ||
| price: float | ||
| deleted: bool = False | ||
|
|
||
|
|
||
| class ItemCreate(BaseModel): | ||
| name: str | ||
| price: float | ||
|
|
||
|
|
||
| class ItemPatch(BaseModel): | ||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| name: str | None = None | ||
| price: float | None = None | ||
|
|
||
|
|
||
| class CartItem(BaseModel): | ||
| id: int | ||
| name: str | ||
| quantity: int | ||
| available: bool | ||
|
|
||
|
|
||
| class Cart(BaseModel): | ||
| id: int | ||
| items: list[CartItem] | ||
| price: float | ||
|
|
||
|
|
||
| def build_cart(cart_id: int) -> Cart: | ||
| cart_items = [] | ||
| price = 0.0 | ||
|
|
||
| for item_id, quantity in carts_db[cart_id].items(): | ||
| item = items_db[item_id] | ||
| price += item.price * quantity | ||
| cart_items.append( | ||
| CartItem( | ||
| id=item.id, | ||
| name=item.name, | ||
| quantity=quantity, | ||
| available=not item.deleted, | ||
| ) | ||
| ) | ||
|
|
||
| return Cart(id=cart_id, items=cart_items, price=price) | ||
|
|
||
|
|
||
| @app.post("/cart", status_code=HTTPStatus.CREATED) | ||
| def create_cart(response: Response): | ||
| cart_id = next(cart_id_seq) | ||
| carts_db[cart_id] = {} | ||
| response.headers["location"] = f"/cart/{cart_id}" | ||
| return {"id": cart_id} | ||
|
|
||
|
|
||
| @app.get("/cart/{cart_id}") | ||
| def get_cart(cart_id: int) -> Cart: | ||
| if cart_id not in carts_db: | ||
| raise HTTPException(HTTPStatus.NOT_FOUND) | ||
|
|
||
| return build_cart(cart_id) | ||
|
|
||
|
|
||
| @app.get("/cart") | ||
| def get_cart_list( | ||
| offset: int = Query(0, ge=0), | ||
| limit: int = Query(10, gt=0), | ||
| min_price: float | None = Query(None, ge=0), | ||
| max_price: float | None = Query(None, ge=0), | ||
| min_quantity: int | None = Query(None, ge=0), | ||
| max_quantity: int | None = Query(None, ge=0), | ||
| ) -> list[Cart]: | ||
| carts = [build_cart(cart_id) for cart_id in carts_db] | ||
|
|
||
| if min_price is not None: | ||
| carts = [c for c in carts if c.price >= min_price] | ||
| if max_price is not None: | ||
| carts = [c for c in carts if c.price <= max_price] | ||
|
|
||
| if min_quantity is not None: | ||
| carts = [c for c in carts if sum(i.quantity for i in c.items) >= min_quantity] | ||
| if max_quantity is not None: | ||
| carts = [c for c in carts if sum(i.quantity for i in c.items) <= max_quantity] | ||
|
|
||
| return carts[offset : offset + limit] | ||
|
|
||
|
|
||
| @app.post("/cart/{cart_id}/add/{item_id}") | ||
| def add_item_to_cart(cart_id: int, item_id: int) -> Cart: | ||
| if cart_id not in carts_db or item_id not in items_db: | ||
| raise HTTPException(HTTPStatus.NOT_FOUND) | ||
|
|
||
| cart = carts_db[cart_id] | ||
| cart[item_id] = cart.get(item_id, 0) + 1 | ||
|
|
||
| return build_cart(cart_id) | ||
|
|
||
|
|
||
| @app.post("/item", status_code=HTTPStatus.CREATED) | ||
| def create_item(body: ItemCreate) -> Item: | ||
| item_id = next(item_id_seq) | ||
| item = Item(id=item_id, name=body.name, price=body.price) | ||
| items_db[item_id] = item | ||
|
|
||
| return item | ||
|
|
||
|
|
||
| @app.get("/item/{item_id}") | ||
| def get_item(item_id: int) -> Item: | ||
| item = items_db.get(item_id) | ||
|
|
||
| if item is None or item.deleted: | ||
| raise HTTPException(HTTPStatus.NOT_FOUND) | ||
|
|
||
| return item | ||
|
|
||
|
|
||
| @app.get("/item") | ||
| def get_item_list( | ||
| offset: int = Query(0, ge=0), | ||
| limit: int = Query(10, gt=0), | ||
| min_price: float | None = Query(None, ge=0), | ||
| max_price: float | None = Query(None, ge=0), | ||
| show_deleted: bool = False, | ||
| ) -> list[Item]: | ||
| items = list(items_db.values()) | ||
|
|
||
| if not show_deleted: | ||
| items = [i for i in items if not i.deleted] | ||
|
|
||
| if min_price is not None: | ||
| items = [i for i in items if i.price >= min_price] | ||
| if max_price is not None: | ||
| items = [i for i in items if i.price <= max_price] | ||
|
|
||
| return items[offset : offset + limit] | ||
|
|
||
|
|
||
| @app.put("/item/{item_id}") | ||
| def put_item(item_id: int, body: ItemCreate) -> Item: | ||
| if item_id not in items_db: | ||
| raise HTTPException(HTTPStatus.NOT_FOUND) | ||
|
|
||
| item = items_db[item_id] | ||
| item.name = body.name | ||
| item.price = body.price | ||
|
|
||
| return item | ||
|
|
||
|
|
||
| @app.patch("/item/{item_id}") | ||
| def patch_item(item_id: int, body: ItemPatch): | ||
| if item_id not in items_db: | ||
| raise HTTPException(HTTPStatus.NOT_FOUND) | ||
|
|
||
| item = items_db[item_id] | ||
|
|
||
| if item.deleted: | ||
| return Response(status_code=HTTPStatus.NOT_MODIFIED) | ||
|
|
||
| for field, value in body.model_dump(exclude_unset=True).items(): | ||
| setattr(item, field, value) | ||
|
|
||
| return item | ||
|
|
||
|
|
||
| @app.delete("/item/{item_id}") | ||
| def delete_item(item_id: int): | ||
| item = items_db.get(item_id) | ||
|
|
||
| if item is not None: | ||
| item.deleted = True | ||
|
|
||
| return {"id": item_id, "deleted": True} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
вход может прийти в несколько пакетов с more_body=True, в рамках этого дз некритично