Skip to content

Commit

Permalink
docs: Add documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
juliocastillo committed Mar 18, 2024
1 parent 9b1db90 commit 204f10e
Show file tree
Hide file tree
Showing 16 changed files with 567 additions and 25 deletions.
7 changes: 6 additions & 1 deletion 00_HelloWorld/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ def running_in_docker():

@app.route("/")
def hello_world():
"""Root endpoint that provides MongoDB server version.
Returns:
str: A message indicating connection to MongoDB with its version.
"""

# This will set the mongo host as localhost by default if variable is not set
# NOTE! localhost won't work with containers, this is setting "mongodb-server" as default,
# otherwise this can be set by "docker run" + "-e MONGODB_HOST=<mongodb_server_name> ... etc"
Expand All @@ -30,7 +36,6 @@ def hello_world():
client = MongoClient(f"mongodb://{mongodb_host}:27017/")
db = client.test_db
return "Connected to MongoDB version: " + str(db.command("serverStatus")["version"])
# return "Hello World"


if __name__ == "__main__":
Expand Down
43 changes: 40 additions & 3 deletions 00_HelloWorld/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,19 @@


def create_network(client, network_name):
"""Ensure the Docker network exists or create it if it doesn't."""
"""Ensure a Docker network exists or create it if it doesn't.
This function checks if the specified Docker network exists. If it doesn't,
it attempts to create a new network with the given name using the bridge driver.
Args:
client: A Docker client object created with docker.from_env() or similar.
network_name: The name of the Docker network to check or create.
Raises:
APIError: An error occurred when attempting to communicate with Docker API
during network creation.
"""
try:
network = client.networks.get(network_name)
print(f"Network '{network_name}' already exists.")
Expand All @@ -16,7 +28,21 @@ def create_network(client, network_name):


def build_image(client, tag, path="."):
"""Build a Docker image from a Dockerfile."""
"""Build a Docker image from a Dockerfile.
This function builds a Docker image based on the Dockerfile located at the specified path.
It tags the resulting image with the provided tag. It prints the build logs to the console
and indicates success or failure.
Args:
client: A Docker client object.
tag: The tag to assign to the built image.
path: The path to the directory containing the Dockerfile. Defaults to the current directory.
Raises:
BuildError: An error occurred during the build process.
APIError: An error occurred when attempting to communicate with Docker API.
"""
try:
_, build_log = client.images.build(path=path, tag=tag, rm=True)
for line in build_log:
Expand All @@ -30,7 +56,18 @@ def build_image(client, tag, path="."):


def check_and_pull_image(client, image_name):
"""Check for an image locally and pull it if not found."""
"""Check for an image locally and pull it from Docker Hub if not found.
This function checks if the specified Docker image is available locally. If it's not found,
it attempts to pull the image from Docker Hub.
Args:
client: A Docker client object.
image_name: The name of the image to check and potentially pull.
Raises:
ImageNotFound: The specified image is not found locally and an attempt is made to pull it.
"""
try:
client.images.get(image_name)
print(f"Image '{image_name}' is already available.")
Expand Down
27 changes: 25 additions & 2 deletions 00_HelloWorld/clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,19 @@


def stop_and_remove_container(client, container_name):
"""Stop and remove a Docker container by its name."""
"""Stops and removes a specified Docker container.
This function attempts to stop and forcibly remove a Docker container by its name. It handles
cases where the container might not exist (either already stopped or removed) and logs appropriate
messages to the console.
Args:
client: A Docker client object created with docker.from_env() or similar.
container_name: The name of the Docker container to stop and remove.
Raises:
docker.errors.APIError: An error occurred when attempting to stop or remove the container due to issues with Docker API.
"""
try:
container = client.containers.get(container_name)
container.stop() # Stops the container
Expand All @@ -18,7 +30,18 @@ def stop_and_remove_container(client, container_name):


def remove_network(client, network_name):
"""Remove a Docker network by its name."""
"""Removes a specified Docker network.
This function tries to remove a Docker network by its name. It deals with cases where the network
may not be found (potentially already removed) and logs appropriate messages to the console.
Args:
client: A Docker client object.
network_name: The name of the Docker network to remove.
Raises:
docker.errors.APIError: An error occurred when attempting to remove the network due to issues with Docker API.
"""
try:
network = client.networks.get(network_name)
network.remove()
Expand Down
29 changes: 28 additions & 1 deletion 00_HelloWorld/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,34 @@ def run_container(
remove=False,
working_dir=None,
):
"""Attempts to start a Docker container with the specified configuration."""
"""
Starts a Docker container based on the specified parameters.
This function attempts to run a Docker container using the provided image and configuration. It
supports setting the container's name, ports, network, environment variables, and working directory.
The function handles exceptions related to image availability, container errors, and API issues, logging
appropriate messages. It can optionally remove the container upon exit.
Args:
client: A Docker client object created with docker.from_env() or similar.
name: A string specifying the name of the container.
image: A string specifying the Docker image to use for the container.
ports: A dictionary mapping container ports to host ports, e.g., {"container_port/tcp": host_port}.
command: Optional; the command to run in the container.
network: Optional; the network to connect the container to.
environment: Optional; a dictionary of environment variables to set in the container.
remove: Optional; a boolean indicating whether to automatically remove the container when it exits.
working_dir: Optional; the working directory to set for the command to run in.
Returns:
A Docker container object if the container starts successfully. None if an error occurs.
Raises:
ImageNotFound: Raised when the specified Docker image is not available.
ContainerError: Raised when there's an error in container execution.
APIError: Raised when the Docker API encounters an error.
Exception: Catches and logs unexpected errors during container run.
"""
try:
container = client.containers.run(
image,
Expand Down
70 changes: 68 additions & 2 deletions 01_CRUD/app.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import os

from flask import Flask, jsonify, request
from pymongo import MongoClient

import os

app = Flask(__name__)

Expand All @@ -21,12 +20,24 @@

@app.route("/")
def index():
"""Root endpoint that provides MongoDB server version.
Returns:
str: A message indicating connection to MongoDB with its version.
"""
return "Connected to MongoDB version: " + str(db.command("serverStatus")["version"])


# CREATE
@app.route("/products", methods=["POST"])
def add_product():
"""Creates a new product in the database.
The product data is expected in JSON format in the request body.
Returns:
tuple: JSON response with the creation message and the new product ID, along with the HTTP status code 201.
"""
product_data = request.get_json()
result = db.products.insert_one(product_data)
return (
Expand All @@ -39,6 +50,13 @@ def add_product():

@app.route("/users", methods=["POST"])
def add_user():
"""Creates a new user in the database.
The user data is expected in JSON format in the request body.
Returns:
tuple: JSON response with the creation message and the new user ID, along with the HTTP status code 201.
"""
user_data = request.get_json()
result = db.users.insert_one(user_data)
return (
Expand All @@ -52,6 +70,14 @@ def add_user():
# READ
@app.route("/products/<product_id>", methods=["GET"])
def get_product(product_id):
"""Fetches a single product from the database by its product_id.
Args:
product_id (str): The ID of the product to retrieve.
Returns:
tuple: JSON response with the product data if found, along with the HTTP status code. 404 if not found.
"""
product = db.products.find_one({"product_id": product_id})
if product:
product["_id"] = str(product["_id"])
Expand All @@ -62,6 +88,14 @@ def get_product(product_id):

@app.route("/users/<username>", methods=["GET"])
def get_user(username):
"""Fetches a single user from the database by username.
Args:
username (str): The username of the user to retrieve.
Returns:
tuple: JSON response with the user data if found, along with the HTTP status code. 404 if not found.
"""
user = db.users.find_one({"username": username})
if user:
user["_id"] = str(
Expand All @@ -75,6 +109,14 @@ def get_user(username):
# UPDATE
@app.route("/products/<product_id>", methods=["PUT"])
def update_product(product_id):
"""Updates a product in the database identified by its product_id.
Args:
product_id (str): The ID of the product to update.
Returns:
tuple: JSON response with an update success message, along with the HTTP status code. 404 if not found.
"""
update_data = request.get_json()
result = db.products.update_one({"product_id": product_id}, {"$set": update_data})

Expand All @@ -86,6 +128,14 @@ def update_product(product_id):

@app.route("/users/<username>", methods=["PUT"])
def update_user(username):
"""Updates a user in the database identified by username.
Args:
username (str): The username of the user to update.
Returns:
tuple: JSON response with an update success message, along with the HTTP status code. 404 if not found.
"""
update_data = request.get_json()
result = db.users.update_one({"username": username}, {"$set": update_data})

Expand All @@ -98,6 +148,14 @@ def update_user(username):
# DELETE
@app.route("/products/<product_id>", methods=["DELETE"])
def delete_product(product_id):
"""Deletes a product from the database by its product_id.
Args:
product_id (str): The ID of the product to delete.
Returns:
tuple: JSON response with a deletion success message, along with the HTTP status code. 404 if not found.
"""
result = db.products.delete_one({"product_id": product_id})

if result.deleted_count:
Expand All @@ -108,6 +166,14 @@ def delete_product(product_id):

@app.route("/users/<username>", methods=["DELETE"])
def delete_user(username):
"""Deletes a user from the database by username.
Args:
username (str): The username of the user to delete.
Returns:
tuple: JSON response with a deletion success message, along with the HTTP status code. 404 if not found.
"""
result = db.users.delete_one({"username": username})

if result.deleted_count:
Expand Down
43 changes: 40 additions & 3 deletions 01_CRUD/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,19 @@


def create_network(client, network_name):
"""Ensure the Docker network exists or create it if it doesn't."""
"""Ensure a Docker network exists or create it if it doesn't.
This function checks if the specified Docker network exists. If it doesn't,
it attempts to create a new network with the given name using the bridge driver.
Args:
client: A Docker client object created with docker.from_env() or similar.
network_name: The name of the Docker network to check or create.
Raises:
APIError: An error occurred when attempting to communicate with Docker API
during network creation.
"""
try:
network = client.networks.get(network_name)
print(f"Network '{network_name}' already exists.")
Expand All @@ -16,7 +28,21 @@ def create_network(client, network_name):


def build_image(client, tag, path="."):
"""Build a Docker image from a Dockerfile."""
"""Build a Docker image from a Dockerfile.
This function builds a Docker image based on the Dockerfile located at the specified path.
It tags the resulting image with the provided tag. It prints the build logs to the console
and indicates success or failure.
Args:
client: A Docker client object.
tag: The tag to assign to the built image.
path: The path to the directory containing the Dockerfile. Defaults to the current directory.
Raises:
BuildError: An error occurred during the build process.
APIError: An error occurred when attempting to communicate with Docker API.
"""
try:
_, build_log = client.images.build(path=path, tag=tag, rm=True)
for line in build_log:
Expand All @@ -30,7 +56,18 @@ def build_image(client, tag, path="."):


def check_and_pull_image(client, image_name):
"""Check for an image locally and pull it if not found."""
"""Check for an image locally and pull it from Docker Hub if not found.
This function checks if the specified Docker image is available locally. If it's not found,
it attempts to pull the image from Docker Hub.
Args:
client: A Docker client object.
image_name: The name of the image to check and potentially pull.
Raises:
ImageNotFound: The specified image is not found locally and an attempt is made to pull it.
"""
try:
client.images.get(image_name)
print(f"Image '{image_name}' is already available.")
Expand Down
Loading

0 comments on commit 204f10e

Please sign in to comment.