Skip to content

Microservices class

The Microservice class is the core of all microservices built with PyMS.

You can create a simple microservice such as:

from flask import jsonify

from pyms.flask.app import Microservice

ms = Microservice(path=__file__)
app = ms.create_app()


@app.route("/")
def example():
    return jsonify({"main": "hello world"})


if __name__ == '__main__':
    app.run()

And a config file like this config.yml

pyms:
    config:
    APP_NAME: "Python Microservice"

Check the Configuration section to learn how to create a configuration file.

The Microservice class searches for a config.yml in the directory you pass in path parameter or looks for the file in PYMS_CONFIGMAP_FILE env var.

Each keyword in our configuration block, can be accessed in our Microservice object through the attribute config.

# Config.yml
pyms:
  config:
    app_name: "Python Microservice"
      foo: "var"
        multiplevars:
          config1: "test1"
          config2: "test2"

#app.py
from pyms.flask.app import Microservice

ms = Microservice(path=__file__)
print(ms.config.APP_NAME) 
# >> "Python Microservice"
print(ms.config.app_name) 
# >> "Python Microservice"
print(ms.config.foo) 
# >> "bar"
print(ms.config.multiplevars.config1) 
# >> "test1"
print(ms.config.multiplevars.config2) 
# >> "test2"

Personalize your microservices

The Microservice class initializes libraries and other process in the following way:

        ...
    def create_app(self):
        """Initialize the Flask app, register blueprints and initialize
        all libraries like Swagger, database,
        the trace system...
        return the app and the database objects.
        :return:
        """
        self.application = self.init_app()
        self.application.config.from_object(self.config)
        self.application.tracer = None
        self.application.ms = self

        # Initialize Blueprints
        self.application.register_blueprint(healthcheck_blueprint)

        self.init_libs()
        self.add_error_handlers()

        self.init_tracer()

        self.init_logger()

        return self.application

Check for more examples in this Github page