Skip to content

Commit 204f10e

Browse files
author
juliocastillo
committed
docs: Add documentation
1 parent 9b1db90 commit 204f10e

File tree

16 files changed

+567
-25
lines changed

16 files changed

+567
-25
lines changed

00_HelloWorld/app.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,12 @@ def running_in_docker():
1717

1818
@app.route("/")
1919
def hello_world():
20+
"""Root endpoint that provides MongoDB server version.
21+
22+
Returns:
23+
str: A message indicating connection to MongoDB with its version.
24+
"""
25+
2026
# This will set the mongo host as localhost by default if variable is not set
2127
# NOTE! localhost won't work with containers, this is setting "mongodb-server" as default,
2228
# otherwise this can be set by "docker run" + "-e MONGODB_HOST=<mongodb_server_name> ... etc"
@@ -30,7 +36,6 @@ def hello_world():
3036
client = MongoClient(f"mongodb://{mongodb_host}:27017/")
3137
db = client.test_db
3238
return "Connected to MongoDB version: " + str(db.command("serverStatus")["version"])
33-
# return "Hello World"
3439

3540

3641
if __name__ == "__main__":

00_HelloWorld/build.py

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,19 @@
33

44

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

1729

1830
def build_image(client, tag, path="."):
19-
"""Build a Docker image from a Dockerfile."""
31+
"""Build a Docker image from a Dockerfile.
32+
33+
This function builds a Docker image based on the Dockerfile located at the specified path.
34+
It tags the resulting image with the provided tag. It prints the build logs to the console
35+
and indicates success or failure.
36+
37+
Args:
38+
client: A Docker client object.
39+
tag: The tag to assign to the built image.
40+
path: The path to the directory containing the Dockerfile. Defaults to the current directory.
41+
42+
Raises:
43+
BuildError: An error occurred during the build process.
44+
APIError: An error occurred when attempting to communicate with Docker API.
45+
"""
2046
try:
2147
_, build_log = client.images.build(path=path, tag=tag, rm=True)
2248
for line in build_log:
@@ -30,7 +56,18 @@ def build_image(client, tag, path="."):
3056

3157

3258
def check_and_pull_image(client, image_name):
33-
"""Check for an image locally and pull it if not found."""
59+
"""Check for an image locally and pull it from Docker Hub if not found.
60+
61+
This function checks if the specified Docker image is available locally. If it's not found,
62+
it attempts to pull the image from Docker Hub.
63+
64+
Args:
65+
client: A Docker client object.
66+
image_name: The name of the image to check and potentially pull.
67+
68+
Raises:
69+
ImageNotFound: The specified image is not found locally and an attempt is made to pull it.
70+
"""
3471
try:
3572
client.images.get(image_name)
3673
print(f"Image '{image_name}' is already available.")

00_HelloWorld/clean.py

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,19 @@
33

44

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

1931

2032
def remove_network(client, network_name):
21-
"""Remove a Docker network by its name."""
33+
"""Removes a specified Docker network.
34+
35+
This function tries to remove a Docker network by its name. It deals with cases where the network
36+
may not be found (potentially already removed) and logs appropriate messages to the console.
37+
38+
Args:
39+
client: A Docker client object.
40+
network_name: The name of the Docker network to remove.
41+
42+
Raises:
43+
docker.errors.APIError: An error occurred when attempting to remove the network due to issues with Docker API.
44+
"""
2245
try:
2346
network = client.networks.get(network_name)
2447
network.remove()

00_HelloWorld/run.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,34 @@ def run_container(
1515
remove=False,
1616
working_dir=None,
1717
):
18-
"""Attempts to start a Docker container with the specified configuration."""
18+
"""
19+
Starts a Docker container based on the specified parameters.
20+
21+
This function attempts to run a Docker container using the provided image and configuration. It
22+
supports setting the container's name, ports, network, environment variables, and working directory.
23+
The function handles exceptions related to image availability, container errors, and API issues, logging
24+
appropriate messages. It can optionally remove the container upon exit.
25+
26+
Args:
27+
client: A Docker client object created with docker.from_env() or similar.
28+
name: A string specifying the name of the container.
29+
image: A string specifying the Docker image to use for the container.
30+
ports: A dictionary mapping container ports to host ports, e.g., {"container_port/tcp": host_port}.
31+
command: Optional; the command to run in the container.
32+
network: Optional; the network to connect the container to.
33+
environment: Optional; a dictionary of environment variables to set in the container.
34+
remove: Optional; a boolean indicating whether to automatically remove the container when it exits.
35+
working_dir: Optional; the working directory to set for the command to run in.
36+
37+
Returns:
38+
A Docker container object if the container starts successfully. None if an error occurs.
39+
40+
Raises:
41+
ImageNotFound: Raised when the specified Docker image is not available.
42+
ContainerError: Raised when there's an error in container execution.
43+
APIError: Raised when the Docker API encounters an error.
44+
Exception: Catches and logs unexpected errors during container run.
45+
"""
1946
try:
2047
container = client.containers.run(
2148
image,

01_CRUD/app.py

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
1-
import os
2-
31
from flask import Flask, jsonify, request
42
from pymongo import MongoClient
53

4+
import os
65

76
app = Flask(__name__)
87

@@ -21,12 +20,24 @@
2120

2221
@app.route("/")
2322
def index():
23+
"""Root endpoint that provides MongoDB server version.
24+
25+
Returns:
26+
str: A message indicating connection to MongoDB with its version.
27+
"""
2428
return "Connected to MongoDB version: " + str(db.command("serverStatus")["version"])
2529

2630

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

4051
@app.route("/users", methods=["POST"])
4152
def add_user():
53+
"""Creates a new user in the database.
54+
55+
The user data is expected in JSON format in the request body.
56+
57+
Returns:
58+
tuple: JSON response with the creation message and the new user ID, along with the HTTP status code 201.
59+
"""
4260
user_data = request.get_json()
4361
result = db.users.insert_one(user_data)
4462
return (
@@ -52,6 +70,14 @@ def add_user():
5270
# READ
5371
@app.route("/products/<product_id>", methods=["GET"])
5472
def get_product(product_id):
73+
"""Fetches a single product from the database by its product_id.
74+
75+
Args:
76+
product_id (str): The ID of the product to retrieve.
77+
78+
Returns:
79+
tuple: JSON response with the product data if found, along with the HTTP status code. 404 if not found.
80+
"""
5581
product = db.products.find_one({"product_id": product_id})
5682
if product:
5783
product["_id"] = str(product["_id"])
@@ -62,6 +88,14 @@ def get_product(product_id):
6288

6389
@app.route("/users/<username>", methods=["GET"])
6490
def get_user(username):
91+
"""Fetches a single user from the database by username.
92+
93+
Args:
94+
username (str): The username of the user to retrieve.
95+
96+
Returns:
97+
tuple: JSON response with the user data if found, along with the HTTP status code. 404 if not found.
98+
"""
6599
user = db.users.find_one({"username": username})
66100
if user:
67101
user["_id"] = str(
@@ -75,6 +109,14 @@ def get_user(username):
75109
# UPDATE
76110
@app.route("/products/<product_id>", methods=["PUT"])
77111
def update_product(product_id):
112+
"""Updates a product in the database identified by its product_id.
113+
114+
Args:
115+
product_id (str): The ID of the product to update.
116+
117+
Returns:
118+
tuple: JSON response with an update success message, along with the HTTP status code. 404 if not found.
119+
"""
78120
update_data = request.get_json()
79121
result = db.products.update_one({"product_id": product_id}, {"$set": update_data})
80122

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

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

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

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

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

113179
if result.deleted_count:

01_CRUD/build.py

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,19 @@
33

44

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

1729

1830
def build_image(client, tag, path="."):
19-
"""Build a Docker image from a Dockerfile."""
31+
"""Build a Docker image from a Dockerfile.
32+
33+
This function builds a Docker image based on the Dockerfile located at the specified path.
34+
It tags the resulting image with the provided tag. It prints the build logs to the console
35+
and indicates success or failure.
36+
37+
Args:
38+
client: A Docker client object.
39+
tag: The tag to assign to the built image.
40+
path: The path to the directory containing the Dockerfile. Defaults to the current directory.
41+
42+
Raises:
43+
BuildError: An error occurred during the build process.
44+
APIError: An error occurred when attempting to communicate with Docker API.
45+
"""
2046
try:
2147
_, build_log = client.images.build(path=path, tag=tag, rm=True)
2248
for line in build_log:
@@ -30,7 +56,18 @@ def build_image(client, tag, path="."):
3056

3157

3258
def check_and_pull_image(client, image_name):
33-
"""Check for an image locally and pull it if not found."""
59+
"""Check for an image locally and pull it from Docker Hub if not found.
60+
61+
This function checks if the specified Docker image is available locally. If it's not found,
62+
it attempts to pull the image from Docker Hub.
63+
64+
Args:
65+
client: A Docker client object.
66+
image_name: The name of the image to check and potentially pull.
67+
68+
Raises:
69+
ImageNotFound: The specified image is not found locally and an attempt is made to pull it.
70+
"""
3471
try:
3572
client.images.get(image_name)
3673
print(f"Image '{image_name}' is already available.")

0 commit comments

Comments
 (0)