» Python: Build a REST API with Flask » 2. Development » 2.7 Config File

Config File

c = Config(
    ApplicationConfig(
        5000
    ),
    DBConfig(
        "test.db",
        "127.0.0.1",
        3306,
        "test_user",
        "test_pass",
        "lr_book"
    )
)

As you may have noticed, hard-coded config items are potential security breaches. And they're hard to change and control after being compiled and deployed.

That's why you need a separate config file.

Add config.yml:

app:
  port: 5000
db:
  file_name: "test.db"
  host: "127.0.0.1"
  port: 3306
  user: "test_user"
  password: "test_pass"
  database: "lr_book"

Add yaml dependency:

pip3 install pyyaml

Update requirements.txt:

pip3 freeze > requirements.txt 

Add parseConfig function in infrastructure/config/config.py:

@@ -1,4 +1,5 @@
 from dataclasses import dataclass
+import yaml
 
 
 @dataclass
@@ -20,3 +21,12 @@ class ApplicationConfig:
 class Config:
     app: ApplicationConfig
     db: DBConfig
+
+
+def parseConfig(filename: str) -> Config:
+    with open(filename, 'r') as f:
+        data = yaml.safe_load(f)
+        return Config(
+            ApplicationConfig(**data['app']),
+            DBConfig(**data['db'])
+        )

Use parseConfig in main.py:

@@ -2,21 +2,11 @@ from flask import Flask
 
 from books.adapter.router import make_router
 from books.application import WireHelper
-from books.infrastructure.config import Config, ApplicationConfig, DBConfig
+from books.infrastructure.config import Config, ApplicationConfig, DBConfig, parseConfig
 
-c = Config(
-    ApplicationConfig(
-        8080
-    ),
-    DBConfig(
-        "test.db",
-        "127.0.0.1",
-        3306,
-        "test_user",
-        "test_pass",
-        "lr_book"
-    )
-)
+CONFIG_FILENAME = "config.yml"
+
+c = parseConfig(CONFIG_FILENAME)
 wire_helper = WireHelper.new(c)
 app = Flask(__name__)
 make_router(app, wire_helper)

Hard-coded config items are moved into config.yml. Nice!

Caution: Do not directly track your config.yaml file with Git, as this could potentially leak sensitive data. If necessary, only track the template of the configuration file.
e.g.

app:
  port: 5000
db:
  file_name: ""
  host: ""
  ...
PrevNext