diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json new file mode 100644 index 0000000..cb20623 --- /dev/null +++ b/.devcontainer/devcontainer.json @@ -0,0 +1,30 @@ +// 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": { + "vscode": { + "extensions": [ + "ms-python.python", + "ms-python.vscode-pylance", + "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/.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" diff --git a/.github/test-application.yml b/.github/test-application.yml new file mode 100644 index 0000000..d02cbb6 --- /dev/null +++ b/.github/test-application.yml @@ -0,0 +1,24 @@ +name: Test Application + +on: [push, pull_request] + +jobs: + test: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v2 + + - name: Set up Python + uses: actions/setup-python@v2 + with: + python-version: '3.11' + + - 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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..8345bbe --- /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/LICENSE b/LICENSE index 9e841e7..62f454e 100644 --- a/LICENSE +++ b/LICENSE @@ -1,21 +1,21 @@ - MIT License - - Copyright (c) Microsoft Corporation. - - 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 5cd7cec..7c991dd 100644 --- a/README.md +++ b/README.md @@ -1,33 +1,48 @@ -# Project - -> This repo has been populated by an initial template to help get you started. Please -> make sure to update the content to build a great experience for community-building. - -As the maintainer of this project, please make a few updates: - -- Improving this README.MD file to provide a great experience -- Updating SUPPORT.MD with content about this project's support experience -- Understanding the security reporting process in SECURITY.MD -- Remove this section from the README - -## Contributing - -This project welcomes contributions and suggestions. 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.opensource.microsoft.com. - -When you submit a pull request, a CLA bot will automatically determine whether you need to provide -a CLA and decorate the PR appropriately (e.g., status check, comment). Simply follow the instructions -provided by the bot. You will only need to do this once across all repos using our CLA. - -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. - -## Trademarks - -This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft -trademarks or logos is subject to and must follow -[Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). -Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. -Any use of third-party trademarks or logos are subject to those third-party's policies. +# 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 +[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 +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. + +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. 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 new file mode 100644 index 0000000..fe4a78e --- /dev/null +++ b/main.py @@ -0,0 +1,126 @@ +import os + +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) + + +@app.get("/") +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 +@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_name) + + if item_id_str is not None: + item_id = int(item_id_str) + redis_client.hincrby(f"item_id:{item_id}", "quantity", quantity) + else: + # Generate an id for the item + item_id: int = redis_client.incr("item_ids") + redis_client.hset( + f"item_id:{item_id}", + mapping={ + "item_id": item_id, + "item_name": item_name, + "quantity": quantity, + }, + ) + # 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) + } + + +# Route to list a specific item by id but using Redis +@app.get("/items/{item_id}") +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: + 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.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) -> dict[str, str]: + 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.delete(f"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 new file mode 100644 index 0000000..bba7954 --- /dev/null +++ b/models.py @@ -0,0 +1,9 @@ +from typing import Optional + +from pydantic import BaseModel + + +class ItemPayload(BaseModel): + item_id: Optional[int] + item_name: str + quantity: int diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b5ab0b0 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,24 @@ +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 +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