diff --git a/.github/dependabot.yaml b/.github/dependabot.yaml new file mode 100644 index 0000000..dc94875 --- /dev/null +++ b/.github/dependabot.yaml @@ -0,0 +1,32 @@ +version: 2 +updates: +- package-ecosystem: "pip" + directory: / + schedule: + interval: "weekly" + day: wednesday + time: "11:30" + timezone: Asia/Kolkata + # Assignees to set on pull requests + assignees: + - "githubofkrishnadhas" + # prefix specifies a prefix for all commit messages. When you specify a prefix for commit messages, + # GitHub will automatically add a colon between the defined prefix and the commit message provided the + # defined prefix ends with a letter, number, closing parenthesis, or closing bracket. + commit-message: + prefix: "dependabot python package" + # Use reviewers to specify individual reviewers or teams of reviewers for all pull requests raised for a package manager. + reviewers: + - "devwithkrishna/admin" + # Raise pull requests for version updates to pip against the `main` branch + target-branch: "main" + # Labels on pull requests for version updates only + labels: + - "pip" + - "dependencies" + # Increase the version requirements for Composer only when required + versioning-strategy: increase-if-necessary + # Dependabot opens a maximum of five pull requests for version updates. Once there are five open pull requests from Dependabot, + # Dependabot will not open any new requests until some of those open requests are merged or closed. + # Use open-pull-requests-limit to change this limit. + open-pull-requests-limit: 10 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..7407d6e --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,33 @@ +name: create release on example python application + +on: + pull_request: + types: + - closed + branches: + - main +run-name: create release from pr number ${{ github.event.number }} +jobs: + create-release: + runs-on: ubuntu-latest + + steps: + + - name: Token generator + uses: githubofkrishnadhas/github-access-using-githubapp@v2 + id: token-generation + with: + github_app_id: ${{ secrets.TOKEN_GENERATOR_APPID }} + github_app_private_key: ${{ secrets.TOKEN_GENERATOR_PRIVATE_KEY }} + + - name: Checkout Repository + uses: actions/checkout@v4 + with: + token: ${{ steps.token-generation.outputs.token }} + + - name: create-release + uses: devwithkrishna/devwithkrishna-create-release-action@v1.0.1 + with: + token: ${{ steps.token-generation.outputs.token }} + pr_number: ${{ github.event.number }} + generate_release_notes: true diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..f0e0ad4 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,26 @@ +# Use the official Python image as the base image +FROM python:3.11-slim + +# Set the working directory in the container +WORKDIR /app + +# Copy the Poetry configuration files to the container +COPY pyproject.toml /app/ + +# Copy the README.md file to the container +COPY README.md /app/ + +# Install Poetry +RUN pip install poetry + +# Install the application dependencies using Poetry +RUN poetry config virtualenvs.create false && poetry install --no-interaction --no-ansi --no-root + +# Copy the application code to the container +COPY app /app/app + +# Expose the port that the FastAPI application will run on +EXPOSE 8000 + +# Command to run the application +CMD ["poetry", "run", "uvicorn", "app.quickapi:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file diff --git a/README.md b/README.md index 0569c42..0f9e4ff 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,81 @@ -# example-python-application -Sample python application +# Example Python Application + +This is a sample Python application built using **FastAPI**. The application allows users to submit their name and favorite color, and provides endpoints to retrieve the submitted data. It also includes logging functionality with JSON formatting. + +## Features + +- **FastAPI** for building RESTful APIs. +- **Pydantic** for data validation and serialization. +- **Logging** with JSON formatting using `python-json-logger`. +- In-memory storage for demonstration purposes. + +## Endpoints + +### Root Endpoint +- **GET** `/` + - Returns a welcome message. + +### Healthcheck +- **GET** `/healthcheck` + - Verifies if the service is running. + +### Submit User Color +- **POST** `/usercolour/` + - Accepts a user's name and favorite color. + - **Request Body**: + ```json + { + "name": "John Doe", + "favorite_color": "Blue" + } + ``` + - **Response**: + ```json + { + "name": "John Doe", + "favorite_color": "Blue" + } + ``` + +### Get All User Colors +- **GET** `/allusercolour/` + - Returns all submitted user-color mappings. + +## Installation + +* Clone the repository: + ```bash + git clone https://github.com/githubofkrishnadhas/example-python-application.git + cd example-python-application + ``` + +* Install dependencies using Poetry: + +``` +poetry install +``` + +Run the application: + +``` +poetry run uvicorn app.quickapi:app --reload +``` +Access the API documentation at http://127.0.0.1:8000/docs. + +## Project Structure +```yaml +example-python-application/ +├── app/ +│ ├── data_model.py # Defines the Pydantic models +│ ├── logging_config.py # Configures logging for the application +│ ├── quickapi.py # Main FastAPI application +├── README.md # Project documentation +├── pyproject.toml # Poetry configuration +``` + +## Dependencies +* Python: 3.11+ +* FastAPI: For building APIs. +* Uvicorn: ASGI server for running the application. +* Pydantic: Data validation and settings management. +* python-json-logger: JSON formatting for logs. \ No newline at end of file diff --git a/app/data_model.py b/app/data_model.py new file mode 100644 index 0000000..169c129 --- /dev/null +++ b/app/data_model.py @@ -0,0 +1,19 @@ +""" +This module defines the data models used in the application. + +Classes: + UserColorEntry: A Pydantic model representing a user's name and their favorite color. +""" + +from pydantic import BaseModel + +class UserColorEntry(BaseModel): + """ + Represents a user's name and their favorite color. + + Attributes: + name (str): The name of the user. + favorite_color (str): The user's favorite color. + """ + name: str + favorite_color: str diff --git a/app/main.py b/app/main.py deleted file mode 100644 index e69de29..0000000 diff --git a/app/quickapi.py b/app/quickapi.py index bfa60f4..875a312 100644 --- a/app/quickapi.py +++ b/app/quickapi.py @@ -1,6 +1,6 @@ from fastapi import FastAPI -# from pylogs import get_logger -from logging_config import setup_logging +from app.logging_config import setup_logging +from app.data_model import UserColorEntry # Setup logging logger = setup_logging() @@ -15,11 +15,13 @@ description="Submit your name and favorite color", version="1.0.0" ) +# In-memory database (for demonstration purposes) +user_colour = [] @app.get("/") async def root(): + """Default end point.Serves welcome message for the API""" logger.info("Root endpoint accessed") - # logger = logging.getLogger("myapp") logger.info("Root endpoint was accessed!") return {"message": "Hello World"} @@ -32,12 +34,19 @@ async def healthcheck(): logger.info("Healthcheck endpoint accessed") return {"status": "ok"} -# @app.middleware("http") -# async def log_requests(request: Request, call_next): -# logger = logging.getLogger("myapp") -# logger.info(f"Received request: {request.method} {request.url}") -# response = await call_next(request) -# logger.info(f"Response status: {response.status_code}") -# return response - - +# Create an user_colour mapping +@app.post("/usercolour/", response_model=UserColorEntry) +async def create_item(item: UserColorEntry): + """Create an item with a username and users favourite colour and return it.""" + user_colour.append(item) + print(user_colour) + logger.info(item) + return item + +# List all user_colour mappings +@app.get("/allusercolour/") +async def get_all_user_colour(): + """Get all user_colour mappings.""" + logger.info("All user_colour mappings accessed") + logger.info(user_colour) + return user_colour diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..be78784 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,17 @@ +[tool.poetry] +name = "example-python-application" +version = "0.1.0" +description = "Sample Python Application" +authors = ["githubofkrishnadhas "] +readme = "README.md" + +[tool.poetry.dependencies] +python = "^3.11" +fastapi = {extras = ["standard"], version = "*"} +uvicorn = "*" +python-json-logger = "*" +pydantic = "^2.11.3" + +[build-system] +requires = ["poetry-core"] +build-backend = "poetry.core.masonry.api"