Initializing the Flask application and MongoDB connection – Running Containers in AWS
- Blog
- Initializing the Flask application and MongoDB connection – Running Containers in AWS
We can use existing Python modules to interact with Flask and MongoDB. These dependencies have been defined in the requirements.txt file inside the application directory:
After importing the necessary modules, we initialize a DB client, database, and corresponding collection that will host our JSON documents in MongoDB.
Now, we can move on to defining the view functions and the related HTTP methods using Flask decorators:
The three HTTP endpoints we discussed previously can be seen in this code snippet. @app.post is just a shorthand syntax for @app.route(“/”, methods = (‘POST’)), which was added in newer versions of Flask.
Tip
HTML does not support the DELETE method type in form submissions yet, only POST and GET. That’s the reason we could not use the DELETE method type in the second use case –deletion of a task.
Preparing the static HTML template
Browsers only understand HTML, so that’s what we need to return from the Python view functions, but sprinkled with dynamic data. This can be done using therender_template(‘index. html’, all_todos = all_todos) call, where we pass the all_todos object data to theHTML template. But the important question is, what helps Flask identify the placeholders in the static HTML template where this data needs to be injected? The answer is Jinja templating.
Jinja templates allow us to use regular Python constructs in a static template. Upon expansion, you get raw data injected into the template, which makes it look like any other regular HTML data.
The relevant lines in our HTML template that leverage this functionality can be seen in the following code snippet:
Up next, lets look at the steps needed to deploy the static website within an ECS container.
Bundling all application dependencies together for deployment on ECS
ECS requires a Docker image that can be referenced in your task definitions. You could host them in DockerHub or ECR, which is Amazon’s offering for hosting your Docker image artifacts. For simplicity, we will use the image hosted in DockerHub in this exercise, which can be found at akskap/flask-todo-list-app. However, if you wish to build your own image, you can reference the Dockerfileavailable at https://github.com/PacktPublishing/AWS-DevOps-Simplified/ blob/main/chapter-7/chapter-7-flask-app/Dockerfile.
© Copyright 2024 morningfun.org