From d962f715250eab7f4ac47bda363b5c14d2588f74 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Sun, 17 Sep 2023 13:57:31 -0700 Subject: [PATCH 01/19] Add dictionary based grocery list app --- .gitignore | 107 +++++++++++++++++++++++++++++++++++++++++++++++ main.py | 61 +++++++++++++++++++++++++++ models.py | 7 ++++ requirements.txt | 6 +++ 4 files changed, 181 insertions(+) create mode 100644 .gitignore create mode 100644 main.py create mode 100644 models.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2253ce2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,107 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode/ +settings.json \ No newline at end of file diff --git a/main.py b/main.py new file mode 100644 index 0000000..3829af1 --- /dev/null +++ b/main.py @@ -0,0 +1,61 @@ +from typing import Dict +from fastapi import FastAPI, HTTPException + +from models import ItemPayload + +app = FastAPI() + +grocery_list: Dict[int, ItemPayload] = {} + +# Route to add an item +@app.post("/items/{item_name}/{quantity}") +def add_item(item_name: str, quantity: int) -> dict[str, ItemPayload]: + if quantity <= 0: + raise HTTPException(status_code=400, detail="Quantity must be greater than 0.") + # if item already exists, we'll just add the quantity. + # get all item names + items_names = [item.item_name for item in grocery_list.values()] + if item_name in items_names: + # get index of item.item_name in item_names, which is the item_id + item_id: int = items_names.index(item_name) + grocery_list[item_id].quantity += quantity + # otherwise, create a new item + else: + # generate an id for the item based on the highest ID in the grocery_list + item_id: int = max(grocery_list.keys()) + 1 if grocery_list else 0 + grocery_list[item_id] = ItemPayload(item_id=item_id, item_name=item_name, quantity=quantity) + + return {"item": grocery_list[item_id]} + +# Route to list a specific item by id +@app.get("/items/{item_id}") +def list_item(item_id: int) -> dict[str, ItemPayload]: + if item_id not in grocery_list: + raise HTTPException(status_code=404, detail="Item not found.") + return {"item": grocery_list[item_id]} + +# Route to list all items +@app.get("/items") +def list_items() -> dict[str, dict[int, ItemPayload]]: + return {"items": grocery_list} + +# Route to delete a specific item by id +@app.delete("/items/{item_id}") +def delete_item(item_id: int) -> dict[str, str]: + if item_id not in grocery_list: + raise HTTPException(status_code=404, detail="Item not found.") + del grocery_list[item_id] + return {"result": "Item deleted."} + +# Route to remove some quantity of a specific item by id +@app.delete("/items/{item_id}/{quantity}") +def remove_quantity(item_id: int, quantity: int) -> dict[str, str]: + if item_id not in grocery_list: + raise HTTPException(status_code=404, detail="Item not found.") + # if quantity to be removed is higher or equal to item's quantity, delete the item + if grocery_list[item_id].quantity <= quantity: + del grocery_list[item_id] + return {"result": "Item deleted."} + else: + grocery_list[item_id].quantity -= quantity + return {"result": f"{quantity} items removed."} diff --git a/models.py b/models.py new file mode 100644 index 0000000..c60f515 --- /dev/null +++ b/models.py @@ -0,0 +1,7 @@ +from typing import Optional +from pydantic import BaseModel + +class ItemPayload(BaseModel): + item_id: Optional[int] + item_name: str + quantity: int \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..559a0cc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +fastapi +redis +types-redis +uvicorn +pytest +httpx From 2ff64125d2defb72352f2186491b9ec213f1e9d5 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Fri, 13 Oct 2023 23:36:25 +0000 Subject: [PATCH 02/19] Use redis --- .devcontainer/devcontainer.json | 25 ++++ .gitignore | 212 ++++++++++++++++---------------- LICENSE | 42 +++---- README.md | 4 +- main.py | 173 +++++++++++++++++--------- models.py | 12 +- requirements.txt | 31 ++++- 7 files changed, 297 insertions(+), 202 deletions(-) create mode 100644 .devcontainer/devcontainer.json diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..7a61539 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,25 @@ +// For format details, see https://aka.ms/devcontainer.json. For config options, see the +// README at: https://github.com/devcontainers/templates/tree/main/src/python +{ + "name": "Python 3", + // Or use a Dockerfile or Docker Compose file. More info: https://containers.dev/guide/dockerfile + "image": "mcr.microsoft.com/devcontainers/python:1-3.11-bullseye", + "features": { + "ghcr.io/itsmechlark/features/redis-server:1": {} + }, + + // Features to add to the dev container. More info: https://containers.dev/features. + // "features": {}, + + // Use 'forwardPorts' to make a list of ports inside the container available locally. + // "forwardPorts": [], + + // Use 'postCreateCommand' to run commands after the container is created. + "postCreateCommand": "pip3 install --user -r requirements.txt" + + // Configure tool-specific properties. + // "customizations": {}, + + // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. + // "remoteUser": "root" +} diff --git a/.gitignore b/.gitignore index 2253ce2..8345bbe 100644 --- a/.gitignore +++ b/.gitignore @@ -1,107 +1,107 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -.hypothesis/ -.pytest_cache/ - -# Translations -*.mo -*.pot - -# Django stuff: -*.log -local_settings.py -db.sqlite3 - -# Flask stuff: -instance/ -.webassets-cache - -# Scrapy stuff: -.scrapy - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -# Jupyter Notebook -.ipynb_checkpoints - -# pyenv -.python-version - -# celery beat schedule file -celerybeat-schedule - -# SageMath parsed files -*.sage.py - -# Environments -.env -.venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ - -# Spyder project settings -.spyderproject -.spyproject - -# Rope project settings -.ropeproject - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ - -.vscode/ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ + +.vscode/ settings.json \ No newline at end of file diff --git a/LICENSE b/LICENSE index 115963d..62f454e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2023 Microsoft - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2023 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md index 2158e39..033aef6 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,2 @@ -# python-sample-vscode-fastapi-tutorial -Sample code for the FastAPI tutorial in the VS Code documentation +# python-sample-vscode-fastapi-tutorial +Sample code for the FastAPI tutorial in the VS Code documentation diff --git a/main.py b/main.py index 3829af1..b7cd32c 100644 --- a/main.py +++ b/main.py @@ -1,61 +1,112 @@ -from typing import Dict -from fastapi import FastAPI, HTTPException - -from models import ItemPayload - -app = FastAPI() - -grocery_list: Dict[int, ItemPayload] = {} - -# Route to add an item -@app.post("/items/{item_name}/{quantity}") -def add_item(item_name: str, quantity: int) -> dict[str, ItemPayload]: - if quantity <= 0: - raise HTTPException(status_code=400, detail="Quantity must be greater than 0.") - # if item already exists, we'll just add the quantity. - # get all item names - items_names = [item.item_name for item in grocery_list.values()] - if item_name in items_names: - # get index of item.item_name in item_names, which is the item_id - item_id: int = items_names.index(item_name) - grocery_list[item_id].quantity += quantity - # otherwise, create a new item - else: - # generate an id for the item based on the highest ID in the grocery_list - item_id: int = max(grocery_list.keys()) + 1 if grocery_list else 0 - grocery_list[item_id] = ItemPayload(item_id=item_id, item_name=item_name, quantity=quantity) - - return {"item": grocery_list[item_id]} - -# Route to list a specific item by id -@app.get("/items/{item_id}") -def list_item(item_id: int) -> dict[str, ItemPayload]: - if item_id not in grocery_list: - raise HTTPException(status_code=404, detail="Item not found.") - return {"item": grocery_list[item_id]} - -# Route to list all items -@app.get("/items") -def list_items() -> dict[str, dict[int, ItemPayload]]: - return {"items": grocery_list} - -# Route to delete a specific item by id -@app.delete("/items/{item_id}") -def delete_item(item_id: int) -> dict[str, str]: - if item_id not in grocery_list: - raise HTTPException(status_code=404, detail="Item not found.") - del grocery_list[item_id] - return {"result": "Item deleted."} - -# Route to remove some quantity of a specific item by id -@app.delete("/items/{item_id}/{quantity}") -def remove_quantity(item_id: int, quantity: int) -> dict[str, str]: - if item_id not in grocery_list: - raise HTTPException(status_code=404, detail="Item not found.") - # if quantity to be removed is higher or equal to item's quantity, delete the item - if grocery_list[item_id].quantity <= quantity: - del grocery_list[item_id] - return {"result": "Item deleted."} - else: - grocery_list[item_id].quantity -= quantity - return {"result": f"{quantity} items removed."} +from typing import Dict +from fastapi import FastAPI, HTTPException +import redis + +from models import ItemPayload + +app = FastAPI() + +redis_client = redis.StrictRedis(host='0.0.0.0', port=6379, db=0, decode_responses=True) + +# Route to add an item +@app.post("/items") +def add_item(item: ItemPayload) -> dict[str, ItemPayload]: + if item.quantity <= 0: + raise HTTPException(status_code=400, detail="Quantity must be greater than 0.") + + # Check if item already exists + item_id_str: str | None = redis_client.hget("item_name_to_id", "item_id") + + if item_id_str is not None: + item_id = int(item_id_str) + redis_client.hincrby(f"item_id:{item_id}", "quantity", item.quantity) + else: + # Generate an id for the item + item_id: int = redis_client.incr("item_id") + redis_client.hset( + f"item_id:{item_id}", + mapping={ + "item_id": item_id, + "item_name": item.item_name, + "quantity": item.quantity, + }, + ) + # Create a set so we can search by name too + redis_client.hset("item_name_to_id", item.item_name, item_id) + + return {"item": item} + + +# Route to list a specific item by id but using Redis +@app.get("/items/{item_id}") +def list_item(item_id: int): + if not redis_client.hexists(f"item_id:{item_id}", "item_id"): + raise HTTPException(status_code=404, detail="Item not found.") + else: + return {"item": redis_client.hgetall(f"item_id:{item_id}")} + + +@app.get("/items") +def list_items() -> dict[str, list[ItemPayload]]: + items: list[ItemPayload] = [] + stored_items: dict[str, str] = redis_client.hgetall("item_name_to_id") + + for name, id_str in stored_items.items(): + item_id: int = int(id_str) + + item_name_str: str | None = redis_client.hget( + f"item_id:{item_id}", "item_name" + ) + if item_name_str is not None: + item_name: str = item_name_str + else: + continue # skip this item if it has no name + + item_quantity_str: str | None = redis_client.hget( + f"item_id:{item_id}", "quantity" + ) + if item_quantity_str is not None: + item_quantity: int = int(item_quantity_str) + else: + item_quantity = 0 + + items.append( + ItemPayload(item_id=item_id, item_name=item_name, quantity=item_quantity) + ) + + return {"items": items} + + +# Route to delete a specific item by id but using Redis +@app.delete("/items/{item_id}") +def delete_item(item_id: int) -> dict[str, str]: + if not redis_client.hexists(f"item_id:{item_id}", "item_id"): + raise HTTPException(status_code=404, detail="Item not found.") + else: + item_name: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") + redis_client.hdel("item_name_to_id", f"{item_name}") + redis_client.hdel(f"item_id:{item_id}", "item_id") + return {"result": "Item deleted."} + + +# Route to remove some quantity of a specific item by id but using Redis +@app.delete("/items/{item_id}/{quantity}") +def remove_quantity(item_id: int, quantity: int): + if not redis_client.hexists(f"item_id:{item_id}", "item_id"): + raise HTTPException(status_code=404, detail="Item not found.") + + item_quantity: str | None = redis_client.hget(f"item_id:{item_id}", "quantity") + + # if quantity to be removed is higher or equal to item's quantity, delete the item + if item_quantity is None: + existing_quantity: int = 0 + else: + existing_quantity: int = int(item_quantity) + if existing_quantity <= quantity: + item_name: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") + redis_client.hdel("item_name_to_id", f"{item_name}") + redis_client.hdel(f"item_id:{item_id}", "item_id") + return {"result": "Item deleted."} + else: + redis_client.hincrby(f"item_id:{item_id}", "quantity", -quantity) + return {"result": f"{quantity} items removed."} diff --git a/models.py b/models.py index c60f515..53d5350 100644 --- a/models.py +++ b/models.py @@ -1,7 +1,7 @@ -from typing import Optional -from pydantic import BaseModel - -class ItemPayload(BaseModel): - item_id: Optional[int] - item_name: str +from typing import Optional +from pydantic import BaseModel + +class ItemPayload(BaseModel): + item_id: Optional[int] + item_name: str quantity: int \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 559a0cc..18518d2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,25 @@ -fastapi -redis -types-redis -uvicorn -pytest -httpx +annotated-types==0.6.0 +anyio==3.7.1 +certifi==2023.7.22 +cffi==1.16.0 +click==8.1.7 +cryptography==41.0.4 +fastapi==0.103.2 +h11==0.14.0 +httpcore==0.18.0 +httpx==0.25.0 +idna==3.4 +iniconfig==2.0.0 +packaging==23.2 +pluggy==1.3.0 +pycparser==2.21 +pydantic==2.4.2 +pydantic_core==2.10.1 +pytest==7.4.2 +redis==5.0.1 +sniffio==1.3.0 +starlette==0.27.0 +types-pyOpenSSL==23.2.0.2 +types-redis==4.6.0.7 +typing_extensions==4.8.0 +uvicorn==0.23.2 From c0063bc672b163b31d570375f81ce74778b40d05 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Fri, 13 Oct 2023 23:37:41 +0000 Subject: [PATCH 03/19] remove pytest --- requirements.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/requirements.txt b/requirements.txt index 18518d2..b5ab0b0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -15,7 +15,6 @@ pluggy==1.3.0 pycparser==2.21 pydantic==2.4.2 pydantic_core==2.10.1 -pytest==7.4.2 redis==5.0.1 sniffio==1.3.0 starlette==0.27.0 From b831528583ab078ca34daa1e52f813c0717a32d0 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Fri, 13 Oct 2023 23:56:29 +0000 Subject: [PATCH 04/19] Initial README --- README.md | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 033aef6..6438462 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,21 @@ -# python-sample-vscode-fastapi-tutorial -Sample code for the FastAPI tutorial in the VS Code documentation +# Python/FastAPI Tutorial for Visual Studio Code +This sample contains the completed program from the tutorial: [FastAPI in Visual Studio Code](https://code.visualstudio.com/docs/python/tutorial-fastapi). Immediate steps are not included. + +## Run the app using GitHub Codespaces + + +## Run the app locally in VS Code + + +## Contributing +Contributions to the sample are welcom! When submitting changes, also consider submitting matching changes to the tutorial, the source file for which is [tutorial-fastapi.md](https://github.com/Microsoft/vscode-docs/blob/master/docs/python/tutorial-fastapi.md). + +Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot automatically determines whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +## Additional details + +* This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +* For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or +* Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. \ No newline at end of file From a701f95d7f9228e3db4180beffd1ca970a4f6d47 Mon Sep 17 00:00:00 2001 From: Luciana Abud <45497113+luabud@users.noreply.github.com> Date: Sat, 14 Oct 2023 00:57:04 +0000 Subject: [PATCH 05/19] Add home and improve README --- README.md | 30 ++++++++++++++++++++++++++++++ main.py | 7 ++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 6438462..58d7486 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,39 @@ This sample contains the completed program from the tutorial: [FastAPI in Visual Studio Code](https://code.visualstudio.com/docs/python/tutorial-fastapi). Immediate steps are not included. ## Run the app using GitHub Codespaces +[GitHub Codespaces](https://github.com/features/codespaces) provides cloud-powered development environments that work how and where you want it to. To learn how to set up a GitHub Codespace for this repository, check the [documentation](https://docs.github.com/en/codespaces/developing-in-codespaces/creating-a-codespace-for-a-repository#creating-a-codespace-for-a-repository). +Once you open this repository in GitHub Codespaces, you can press **F5** to start the debugger and run the application. + +Once it's ready, you will see a notification with a button `Open in the Browser`. Clicking the button will open your application on the browser. You can then add `/docs` to the end of the URL to access the Swagger UI and interact with the application! ## Run the app locally in VS Code + +There are diffent ways you can run this app locally in VS Code depending on your operating system. To get started, first clone this project on your machine and then open it in VS Code (**File** > **Open Folder...**). + +### Windows +To run this app locally in VS Code on Windows, you can use either [WSL](https://learn.microsoft.com/en-us/windows/wsl/) (Windows Subsystem for Linux) or [Docker](https://www.docker.com/products/docker-desktop). + + + +#### Docker Containers +1. Make sure you have [Docker installed](https://www.docker.com/products/docker-desktop) +1. Install the [Dev Containers extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers) +1. Open the Command Palette in VS Code (**View** > **Command Palette...**) and run the "Dev Container: Reopen in Container" command. +1. Press **F5** to debug your application! + +#### WSL +1. Make sure you have [WSL installed](https://learn.microsoft.com/en-us/windows/wsl/) +1. Install the [WSL extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-wsl) for VS Code +1. Open the Command Palette in VS Code (**View** > **Command Palette...**) and run the "WSL: Reopen Folder in WSL" command +1. Follow the remaining steps for [macOS/Linux](#macos--linux) below. + +### macOS / Linux + +1. Install the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) for VS Code +1. Run the "Python: Create Environment" command in the Command Palette +1. Select `Venv`, the latest available version of Python and then the `requirements.txt` file to install the dependencies. +1. Press **F5** to run your application! ## Contributing diff --git a/main.py b/main.py index b7cd32c..c650d5a 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,5 @@ from typing import Dict -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request import redis from models import ItemPayload @@ -8,6 +8,11 @@ redis_client = redis.StrictRedis(host='0.0.0.0', port=6379, db=0, decode_responses=True) +@app.get("/") +def home(request: Request) -> dict[str, str]: + url = str(request.base_url) + return {"message": f"Add /docs to the end of the URL to access the Swagger UI."} + # Route to add an item @app.post("/items") def add_item(item: ItemPayload) -> dict[str, ItemPayload]: From 9225a8d50cea3b5ae8d655e556cc2eb7bc28e592 Mon Sep 17 00:00:00 2001 From: Luciana Abud <45497113+luabud@users.noreply.github.com> Date: Wed, 18 Oct 2023 16:21:28 -0700 Subject: [PATCH 06/19] Update README.md Co-authored-by: Courtney Webster <60238438+cwebster-99@users.noreply.github.com> --- README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 58d7486..0c53651 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,8 @@ To run this app locally in VS Code on Windows, you can use either [WSL](https:// ## Contributing -Contributions to the sample are welcom! When submitting changes, also consider submitting matching changes to the tutorial, the source file for which is [tutorial-fastapi.md](https://github.com/Microsoft/vscode-docs/blob/master/docs/python/tutorial-fastapi.md). +Contributions to the sample are welcome! When submitting changes, also consider submitting matching changes to the tutorial, the source file for which is [tutorial-fastapi.md](https://github.com/Microsoft/vscode-docs/blob/master/docs/python/tutorial-fastapi.md). + Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. From cd903f7d2aac39f044d7496642ff1ad54e4aa569 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Wed, 18 Oct 2023 23:25:54 +0000 Subject: [PATCH 07/19] Apply review comments and add extensions to devcontainer.json --- .devcontainer/devcontainer.json | 13 +++++++++++-- README.md | 3 +++ main.py | 17 ++++++++++------- models.py | 4 +++- 4 files changed, 27 insertions(+), 10 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 7a61539..e109d42 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -15,10 +15,19 @@ // "forwardPorts": [], // Use 'postCreateCommand' to run commands after the container is created. - "postCreateCommand": "pip3 install --user -r requirements.txt" + "postCreateCommand": "pip3 install --user -r requirements.txt", // Configure tool-specific properties. - // "customizations": {}, + "customizations": { + "vscode": { + "extensions": [ + "ms-python.python", + "esbenp.prettier-vscode", + "ms-python.black-formatter", + "charliermarsh.ruff" + ] + } + } // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. // "remoteUser": "root" diff --git a/README.md b/README.md index 6438462..ada17fc 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,9 @@ This sample contains the completed program from the tutorial: [FastAPI in Visual Studio Code](https://code.visualstudio.com/docs/python/tutorial-fastapi). Immediate steps are not included. ## Run the app using GitHub Codespaces +[GitHub Codespaces](https://github.com/features/codespaces) provides cloud-powered development environments that work how and where you want it to. To learn how to set up a GitHub Codespace for this repository, check the [documentation](https://docs.github.com/en/codespaces/developing-in-codespaces/creating-a-codespace-for-a-repository#creating-a-codespace-for-a-repository). + +Once you open this repository in GitHub Codespaces, you can press **F5** to start the debugger and run the application. ## Run the app locally in VS Code diff --git a/main.py b/main.py index b7cd32c..1cccd64 100644 --- a/main.py +++ b/main.py @@ -1,12 +1,17 @@ -from typing import Dict -from fastapi import FastAPI, HTTPException import redis +from fastapi import FastAPI, HTTPException, Request from models import ItemPayload app = FastAPI() -redis_client = redis.StrictRedis(host='0.0.0.0', port=6379, db=0, decode_responses=True) +redis_client = redis.StrictRedis(host="0.0.0.0", port=6379, db=0, decode_responses=True) + + +@app.get("/") +def home() -> dict[str, str]: + return {"message": "Add /docs to the end of the URL to access the Swagger UI."} + # Route to add an item @app.post("/items") @@ -15,7 +20,7 @@ def add_item(item: ItemPayload) -> dict[str, ItemPayload]: raise HTTPException(status_code=400, detail="Quantity must be greater than 0.") # Check if item already exists - item_id_str: str | None = redis_client.hget("item_name_to_id", "item_id") + item_id_str: str | None = redis_client.hget("item_name_to_id", item.item_name) if item_id_str is not None: item_id = int(item_id_str) @@ -54,9 +59,7 @@ def list_items() -> dict[str, list[ItemPayload]]: for name, id_str in stored_items.items(): item_id: int = int(id_str) - item_name_str: str | None = redis_client.hget( - f"item_id:{item_id}", "item_name" - ) + item_name_str: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") if item_name_str is not None: item_name: str = item_name_str else: diff --git a/models.py b/models.py index 53d5350..bba7954 100644 --- a/models.py +++ b/models.py @@ -1,7 +1,9 @@ from typing import Optional + from pydantic import BaseModel + class ItemPayload(BaseModel): item_id: Optional[int] item_name: str - quantity: int \ No newline at end of file + quantity: int From fa05e60dee82ad652143d102be10dabae0d769d0 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Wed, 18 Oct 2023 23:32:28 +0000 Subject: [PATCH 08/19] Remove unused imports --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 1cccd64..38d9cfd 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,5 @@ import redis -from fastapi import FastAPI, HTTPException, Request +from fastapi import FastAPI, HTTPException from models import ItemPayload From 6040fe50db6e4c5323a4503eb0f13c39bcb9ca71 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Thu, 19 Oct 2023 00:00:38 +0000 Subject: [PATCH 09/19] Add flushdb and use delete instead of hdel --- flushdb.py | 9 +++++++++ main.py | 8 ++++---- 2 files changed, 13 insertions(+), 4 deletions(-) create mode 100644 flushdb.py diff --git a/flushdb.py b/flushdb.py new file mode 100644 index 0000000..65442ad --- /dev/null +++ b/flushdb.py @@ -0,0 +1,9 @@ +""" +This module is used to interact with a Redis database. + +WARNING: This script will flush the entire Redis database. Use with caution. +""" +import redis + +redis_client = redis.StrictRedis(host="0.0.0.0", port=6379, db=0, decode_responses=True) +redis_client.flushdb() diff --git a/main.py b/main.py index 38d9cfd..0466116 100644 --- a/main.py +++ b/main.py @@ -44,7 +44,7 @@ def add_item(item: ItemPayload) -> dict[str, ItemPayload]: # Route to list a specific item by id but using Redis @app.get("/items/{item_id}") -def list_item(item_id: int): +def list_item(item_id: int) -> dict[str, dict[str, str]]: if not redis_client.hexists(f"item_id:{item_id}", "item_id"): raise HTTPException(status_code=404, detail="Item not found.") else: @@ -88,13 +88,13 @@ def delete_item(item_id: int) -> dict[str, str]: else: item_name: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") redis_client.hdel("item_name_to_id", f"{item_name}") - redis_client.hdel(f"item_id:{item_id}", "item_id") + redis_client.delete(f"item_id:{item_id}") return {"result": "Item deleted."} # Route to remove some quantity of a specific item by id but using Redis @app.delete("/items/{item_id}/{quantity}") -def remove_quantity(item_id: int, quantity: int): +def remove_quantity(item_id: int, quantity: int) -> dict[str, str]: if not redis_client.hexists(f"item_id:{item_id}", "item_id"): raise HTTPException(status_code=404, detail="Item not found.") @@ -108,7 +108,7 @@ def remove_quantity(item_id: int, quantity: int): if existing_quantity <= quantity: item_name: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") redis_client.hdel("item_name_to_id", f"{item_name}") - redis_client.hdel(f"item_id:{item_id}", "item_id") + redis_client.delete(f"item_id:{item_id}", "item_id") return {"result": "Item deleted."} else: redis_client.hincrby(f"item_id:{item_id}", "quantity", -quantity) From 9bedd2607ca80795599d9734fc13e8a5fba4a6a9 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Thu, 19 Oct 2023 00:14:31 +0000 Subject: [PATCH 10/19] Add url to home route --- main.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 0466116..8d23a0e 100644 --- a/main.py +++ b/main.py @@ -1,5 +1,7 @@ +import os + import redis -from fastapi import FastAPI, HTTPException +from fastapi import FastAPI, HTTPException, Request from models import ItemPayload @@ -9,8 +11,15 @@ @app.get("/") -def home() -> dict[str, str]: - return {"message": "Add /docs to the end of the URL to access the Swagger UI."} +def home(request: Request) -> dict[str, str]: + url: str = ( + f"https://{os.getenv('CODESPACE_NAME')}-8000.{os.getenv('GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN')}/" + if os.getenv("CODESPACE_NAME") + else str(request.base_url) + ) + return { + "message": f"Navigate to the following URL to access the Swagger UI: {url}docs" + } # Route to add an item From b94ab6192420e1a090a18635bda2da51bf56251d Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Thu, 19 Oct 2023 00:16:54 +0000 Subject: [PATCH 11/19] Fix ix delete call --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 8d23a0e..d0d6c0b 100644 --- a/main.py +++ b/main.py @@ -117,7 +117,7 @@ def remove_quantity(item_id: int, quantity: int) -> dict[str, str]: if existing_quantity <= quantity: item_name: str | None = redis_client.hget(f"item_id:{item_id}", "item_name") redis_client.hdel("item_name_to_id", f"{item_name}") - redis_client.delete(f"item_id:{item_id}", "item_id") + redis_client.delete(f"item_id:{item_id}") return {"result": "Item deleted."} else: redis_client.hincrby(f"item_id:{item_id}", "quantity", -quantity) From 14f364786e7c4a99b9b575c20ab958ba3741167b Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Fri, 20 Oct 2023 11:41:29 -0700 Subject: [PATCH 12/19] Add dependabot.yml --- .github/dependabot.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .github/dependabot.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..2f06dbc --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "pip" + directory: "/" # Location of package manifests + schedule: + interval: "weekly" From ec788257a2dd3f5efb83f4238002ac09d2b8a817 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 14:39:11 +0000 Subject: [PATCH 13/19] Change input for add_item --- main.py | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index d0d6c0b..31e3f49 100644 --- a/main.py +++ b/main.py @@ -23,17 +23,17 @@ def home(request: Request) -> dict[str, str]: # Route to add an item -@app.post("/items") -def add_item(item: ItemPayload) -> dict[str, ItemPayload]: - if item.quantity <= 0: +@app.post("/items/{item_name}/{quantity}") +def add_item(item_name: str, quantity: int) -> dict[str, ItemPayload]: + if quantity <= 0: raise HTTPException(status_code=400, detail="Quantity must be greater than 0.") # Check if item already exists - item_id_str: str | None = redis_client.hget("item_name_to_id", item.item_name) + item_id_str: str | None = redis_client.hget("item_name_to_id", item_name) if item_id_str is not None: item_id = int(item_id_str) - redis_client.hincrby(f"item_id:{item_id}", "quantity", item.quantity) + redis_client.hincrby(f"item_id:{item_id}", "quantity", quantity) else: # Generate an id for the item item_id: int = redis_client.incr("item_id") @@ -41,14 +41,14 @@ def add_item(item: ItemPayload) -> dict[str, ItemPayload]: f"item_id:{item_id}", mapping={ "item_id": item_id, - "item_name": item.item_name, - "quantity": item.quantity, + "item_name": item_name, + "quantity": quantity, }, ) # Create a set so we can search by name too - redis_client.hset("item_name_to_id", item.item_name, item_id) + redis_client.hset("item_name_to_id", item_name, item_id) - return {"item": item} + return {"item": ItemPayload(item_id=item_id, item_name=item_name, quantity=quantity)} # Route to list a specific item by id but using Redis From ac8acffe49f83777731d829719a1df54286912a6 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 15:25:14 +0000 Subject: [PATCH 14/19] Change hashname --- main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/main.py b/main.py index 31e3f49..2fb34f1 100644 --- a/main.py +++ b/main.py @@ -36,7 +36,7 @@ def add_item(item_name: str, quantity: int) -> dict[str, ItemPayload]: redis_client.hincrby(f"item_id:{item_id}", "quantity", quantity) else: # Generate an id for the item - item_id: int = redis_client.incr("item_id") + item_id: int = redis_client.incr("item_ids") redis_client.hset( f"item_id:{item_id}", mapping={ From efe738c0c20eb9aa43e97b140153dbe6d62ee509 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 13:40:38 -0700 Subject: [PATCH 15/19] Add pylance to devcontainer.json --- .devcontainer/devcontainer.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index e109d42..be4c565 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -22,6 +22,7 @@ "vscode": { "extensions": [ "ms-python.python", + "ms-python.vscode-pylance", "esbenp.prettier-vscode", "ms-python.black-formatter", "charliermarsh.ruff" From d5bfc83d87c90f54b5cf24bf50bb9cffe27e1841 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 13:43:36 -0700 Subject: [PATCH 16/19] Add GH action and add dependabot.yml --- .github/test-application.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 .github/test-application.yml diff --git a/.github/test-application.yml b/.github/test-application.yml new file mode 100644 index 0000000..52888dc --- /dev/null +++ b/.github/test-application.yml @@ -0,0 +1,26 @@ +name: Test Application + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + env: + PORT: 8000 + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.x' + + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -r requirements.txt + + - name: Start the app + run: uvicorn main:app --host 0.0.0.0 --port ${{ env.PORT }} \ No newline at end of file From 0b42206139e6a4ffc91a81a39b70614781486651 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 13:51:17 -0700 Subject: [PATCH 17/19] change Python version --- .github/test-application.yml | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.github/test-application.yml b/.github/test-application.yml index 52888dc..7dc593f 100644 --- a/.github/test-application.yml +++ b/.github/test-application.yml @@ -5,8 +5,6 @@ on: [push, pull_request] jobs: test: runs-on: ubuntu-latest - env: - PORT: 8000 steps: - name: Checkout code @@ -15,7 +13,7 @@ jobs: - name: Set up Python uses: actions/setup-python@v2 with: - python-version: '3.x' + python-version: '3.11' - name: Install dependencies run: | @@ -23,4 +21,4 @@ jobs: pip install -r requirements.txt - name: Start the app - run: uvicorn main:app --host 0.0.0.0 --port ${{ env.PORT }} \ No newline at end of file + run: python app.py \ No newline at end of file From 24e2ac670d8966b98475d4ab6ae7c4cab550d7af Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 13:53:50 -0700 Subject: [PATCH 18/19] Format docs --- .devcontainer/devcontainer.json | 17 ++++++----------- main.py | 4 +++- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index be4c565..cb20623 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -7,29 +7,24 @@ "features": { "ghcr.io/itsmechlark/features/redis-server:1": {} }, - // Features to add to the dev container. More info: https://containers.dev/features. // "features": {}, - // Use 'forwardPorts' to make a list of ports inside the container available locally. // "forwardPorts": [], - // Use 'postCreateCommand' to run commands after the container is created. "postCreateCommand": "pip3 install --user -r requirements.txt", - // Configure tool-specific properties. "customizations": { "vscode": { - "extensions": [ - "ms-python.python", + "extensions": [ + "ms-python.python", "ms-python.vscode-pylance", - "esbenp.prettier-vscode", + "esbenp.prettier-vscode", "ms-python.black-formatter", "charliermarsh.ruff" - ] - } + ] + } } - // Uncomment to connect as root instead. More info: https://aka.ms/dev-containers-non-root. // "remoteUser": "root" -} +} \ No newline at end of file diff --git a/main.py b/main.py index 2fb34f1..fe4a78e 100644 --- a/main.py +++ b/main.py @@ -48,7 +48,9 @@ def add_item(item_name: str, quantity: int) -> dict[str, ItemPayload]: # Create a set so we can search by name too redis_client.hset("item_name_to_id", item_name, item_id) - return {"item": ItemPayload(item_id=item_id, item_name=item_name, quantity=quantity)} + return { + "item": ItemPayload(item_id=item_id, item_name=item_name, quantity=quantity) + } # Route to list a specific item by id but using Redis From 8cbd4d803879b9b113b66a71656a038354c22d48 Mon Sep 17 00:00:00 2001 From: Luciana Abud Date: Mon, 23 Oct 2023 14:10:18 -0700 Subject: [PATCH 19/19] Fix typo --- .github/test-application.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/test-application.yml b/.github/test-application.yml index 7dc593f..d02cbb6 100644 --- a/.github/test-application.yml +++ b/.github/test-application.yml @@ -21,4 +21,4 @@ jobs: pip install -r requirements.txt - name: Start the app - run: python app.py \ No newline at end of file + run: uvicorn main:app --host 0.0.0.0 --port ${{ env.PORT }} \ No newline at end of file