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:
import osimport jsonfrom flask import Blueprint, request, Responsefrom rentomatic.repository.postgresrepo import PostgresRepofrom rentomatic.use_cases.room_list import room_list_use_casefrom rentomatic.serializers.room import RoomJsonEncoderfrom rentomatic.requests.room_list import build_room_list_requestfrom rentomatic.responses import ResponseTypesblueprint = 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_", "")] = valuesrequest_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 ...