|
1 | 1 | # Configuration
|
2 | 2 |
|
| 3 | +## Create configuration |
3 | 4 | Each microservice needs a config file in yaml or json format to work with it. This configuration contains
|
4 |
| -the Flask settings of your project and the [Services](services.md). |
| 5 | +the Flask settings of your project and the [Services](services.md). With this way to create configuration files, we |
| 6 | +solve two problems of the [12 Factor apps](https://12factor.net/): |
| 7 | +- Store config out of the code |
| 8 | +- Dev/prod parity: the configuration could be injected and not depends of our code, for example, Kubernetes config maps |
5 | 9 |
|
6 | 10 | a simple configuration file could be a config.yaml:
|
7 | 11 |
|
@@ -91,3 +95,51 @@ ms1-api:
|
91 | 95 | DEBUG: true
|
92 | 96 | TESTING: false
|
93 | 97 | ```
|
| 98 | + |
| 99 | +## Import Configuration |
| 100 | +With pyms, all configuration is stored as flask configuration and it can be acceded from: |
| 101 | + |
| 102 | +```python |
| 103 | +from flask import current_app; |
| 104 | +
|
| 105 | +def my_endpoint(): |
| 106 | + print(current_app.config["DEBUG"]) |
| 107 | +``` |
| 108 | + |
| 109 | +But, what happend if you need the configuration BEFORE Flask class is instanced? Imagine this case: |
| 110 | + |
| 111 | +```python |
| 112 | +from flask import Blueprint, current_app |
| 113 | +from flask_restplus import Api |
| 114 | +
|
| 115 | +my_api_blueprint = Blueprint('api', __name__) |
| 116 | +
|
| 117 | +API = Api( |
| 118 | + my_api_blueprint, |
| 119 | + title='My Microservice', |
| 120 | + version=current_app.config["APP_VERSION"], |
| 121 | + description='Microservice to manage hierarchies', |
| 122 | + add_specs=True, |
| 123 | +) |
| 124 | +``` |
| 125 | + |
| 126 | +This raise a `'working outside of application context` error. Who can solve this problem? |
| 127 | + |
| 128 | +```python |
| 129 | +from flask import Blueprint, current_app |
| 130 | +from flask_restplus import Api |
| 131 | +from pyms.flask.app import config |
| 132 | +
|
| 133 | +my_api_blueprint = Blueprint('api', __name__) |
| 134 | +
|
| 135 | +API = Api( |
| 136 | + my_api_blueprint, |
| 137 | + title='My Microservice', |
| 138 | + version=config().APP_VERSION, |
| 139 | + description='Microservice to manage hierarchies', |
| 140 | + add_specs=True, |
| 141 | +) |
| 142 | +``` |
| 143 | + |
| 144 | +**IMPORTANT:** If you use this method to get configuration out of context, you must set the `CONFIGMAP_SERVICE` or set |
| 145 | +the default key `ms` for your configuration block in your config.yml |
0 commit comments