...

/

Connect to a Production-ready Database

Connect to a Production-ready Database

Let’s learn how to connect to the database of a production-ready system.

Stop the docker

Before we start changing the code of the application, we have to tear down the system that’s running by executing the command below:

$ python3 manage.py compose down
/*
Stopping production_web_1   ... done
Stopping production_nginx_1 ... done
Stopping production_db_1    ... done
Removing production_web_1   ... done
Removing production_nginx_1 ... done
Removing production_db_1    ... done
Removing network production_default
*/

Changes in the application

Thanks to the common interface between repositories, moving from the memory-based MemRepo to PostgresRepo is very simple. Because the external database won’t contain any data initially, the response of the use case will be empty.

First of all, let’s move the application to the PostgreSQL repository. The new version of the endpoint is as follows:

Press + to interact
import os
import json
from flask import Blueprint, request, Response
from rentomatic.repository.postgresrepo import PostgresRepo
from rentomatic.use_cases.room_list import room_list_use_case
from rentomatic.serializers.room import RoomJsonEncoder
from rentomatic.requests.room_list import build_room_list_request
from rentomatic.responses import ResponseTypes
blueprint = Blueprint("room", __name__)
STATUS_CODES = {
ResponseTypes.SUCCESS: 200,
ResponseTypes.RESOURCE_ERROR: 404,
ResponseTypes.PARAMETERS_ERROR: 400,
ResponseTypes.SYSTEM_ERROR: 500,
}
postgres_configuration = {
"POSTGRES_USER": os.environ["POSTGRES_USER"],
"POSTGRES_PASSWORD": os.environ["POSTGRES_PASSWORD"],
"POSTGRES_HOSTNAME": os.environ["POSTGRES_HOSTNAME"],
"POSTGRES_PORT": os.environ["POSTGRES_PORT"],
"APPLICATION_DB": os.environ["APPLICATION_DB"],
}
@blueprint.route("/rooms", methods=["GET"])
def room_list():
qrystr_params = {
"filters": {},
}
for arg, values in request.args.items():
if arg.startswith("filter_"):
qrystr_params["filters"][arg.replace("filter_", "")] = values
request_object = build_room_list_request(
filters=qrystr_params["filters"]
)
repo = PostgresRepo(postgres_configuration)
response = room_list_use_case(repo, request_object)
return Response(
json.dumps(response.value, cls=RoomJsonEncoder),
mimetype="application/json",
status=STATUS_CODES[response.type],
)

As we can see, the main difference from the previous version is that repo = MemRepo(rooms) becomes repo = PostgresRepo(postgres_configuration) in line 44. Such a simple change is made possible by clean architecture and its strict layered approach. The only other notable difference is that we replaced the initial data of the memory-based repository with a dictionary containing connection data, which comes from the ...

Access this course and 1400+ top-rated courses and projects.