
Refactoring your Python App with 12-Factor Methodology
Streamlined refactoring with Amazon Q Developer and /dev agent
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# app.py
from flask import Flask, request, jsonify
app = Flask(__name__)
# In-memory storage for tasks
tasks = []
def hello():
return "Welcome to the Task Management App!"
def get_tasks():
return jsonify(tasks)
def add_task():
task = request.json.get("task")
if task:
new_task = {"id": len(tasks) + 1, "task": task, "completed": False}
tasks.append(new_task)
return jsonify(new_task), 201
return jsonify({"error": "Invalid task"}), 400
def update_task(task_id):
task = next((task for task in tasks if task["id"] == task_id), None)
if task:
task["completed"] = request.json.get("completed", task["completed"])
return jsonify(task)
return jsonify({"error": "Task not found"}), 404
def delete_task(task_id):
global tasks
tasks = [task for task in tasks if task["id"] != task_id]
return "", 204
if __name__ == "__main__":
app.run(debug=True)
Explain what the application coded in app.py does and mention briefly on how it can be refactored with the 12 factor app methodology
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
The application in app.py is a simple Flask-based task management API. Here's a breakdown of its functionality:
1. It creates a Flask application instance.
2. It uses an in-memory list to store tasks (as a temporary solution).
3. It defines several routes:
- A root route ("/") that returns a welcome message.
- A GET route ("/tasks") to retrieve all tasks.
- A POST route ("/tasks") to add a new task.
- A PUT route ("/tasks/<task_id>") to update a task's completion status.
- A DELETE route ("/tasks/<task_id>") to remove a task.
4. Each route handles its respective HTTP method and performs operations on the tasks list.
5. The application runs in debug mode when executed directly.
Regarding refactoring with the 12-factor app methodology, here are some brief suggestions: [1]
1. Codebase: The application is already in a single codebase, which is good.
2. Dependencies: Create a requirements.txt file to explicitly declare and isolate dependencies.
3. Config: Move configuration settings (like debug mode) into environment variables.
4. Backing Services: Replace the in-memory list with a proper database, treated as an attached resource.
5. Build, release, run: Separate these stages clearly in your deployment process.
6. Processes: Ensure the app is stateless, moving the task storage to a backing service.
7. Port binding: The app is already designed to be self-contained, which is good.
8. Concurrency: Ensure the app can scale horizontally by running multiple instances.
9. Disposability: Implement graceful shutdown and startup processes.
10. Dev/prod parity: Keep development, staging, and production environments as similar as possible.
11. Logs: Implement proper logging instead of using print statements.
12. Admin processes: Any admin or management tasks should be run as one-off processes in identical environments.
Implementing these factors would make the application more robust, scalable, and easier to maintain, especially in a cloud environment.
Sources
[1] The 12-Factor App Methodology
blog.mikaeels.comtwelve-factor-app-methodology
- Iterating through each step in the 12 factor app roach manually updating the code or asking Amazon Q Developer to suggest code changes and us taking it into consideration.
- Or, we leverage the /dev agent and let it do the work for us!
/dev
command activates the Amazon Q Developer agent.Transform the following project using the 12 factor app approach and also generate a step-by-step instruction in a README.md file after refactoring is complete.
Proc
file that can be used as part of deployment to a Heroku account.I'm not using Heroku so can you make an alternative implementation of the Procfile with Docker and Docker Swarm? Update the README.md accordingly.
1
docker-compose up --build
Give me some sample payloads for the flask API I can test with on http://127.0.0.1:5000
The table is not created in the database. add the required scripts to do this after checking if the table exists or not.
- Faster identification of issues: Amazon Q Developer quickly pinpointed areas for improvement.
- Efficient refactoring: The /dev agent allowed us to make significant changes with minimal manual intervention.
- Improved maintainability and scalability: The refactor enhanced the app's flexibility and stability, making it easier to scale.
- Educational insights: The AI tools provided clear explanations of best practices, enhancing our understanding of the principles behind the 12-factor methodology.
Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.