Rinor Maloku

Kubernetes and everything else, part 4 of 12

Setting up the Python Application

All 12 parts of the series
  1. 1 Introduction and Application Architecture
  2. 2 Setting up the React Application
  3. 3 Setting up the Spring WebApplication
  4. 4 Setting up the Python Application
  5. 5 Container-ization of the Services
  6. 6 Container-ization of everything else
  7. 7 Introduction to Kubernetes
  8. 8 Kubernetes in Practice – Pods
  9. 9 Kubernetes in Practice – Services
  10. 10 Kubernetes in Practice – Deployments
  11. 11 Kubernetes and everything else in Practice
  12. 12 Kubernetes Volumes – in Practice

To start the Python application we need to have Python3 and Pip installed (their environment variables need to be set up as well).

Installing Dependencies

Navigate in the CMD to the directory **sa-logic/sa (repo) **and type the following command:

$ python -m pip install -r requirements.txt
$ python -m textblob.download_corpora

Starting the app

Pip installs the dependencies and we are ready to start the application by executing the following command:

python sentiment_analysis.py
* Running on http://localhost:5000/ (Press CTRL+C to quit)

Which means that our application is running and listening for HTTP Requests at the port 5000 on localhost.

Inspecting the Code

Let’s investigate the code to understand what is happening in the SA Logic python application.

from textblob import TextBlob
from flask import Flask, request, jsonify

app = Flask(__name__)                                   #1


@app.route("/analyse/sentiment", methods=['POST'])      #2
def analyse_sentiment():
    sentence = request.get_json()['sentence']           #3
    polarity = TextBlob(sentence).sentences[0].polarity #4
    return jsonify(                                     #5
        sentence=sentence,
        polarity=polarity
    )


if __name__ == '__main__':
    app.run(host='localhost', port=5000)                #6
  1. Instantiate a Flask object.
  2. Defines the path at which a POST request can be made.
  3. Extract the “sentence” property from the request body.
  4. Instantiate an anonymous TextBlob object and get the polarity from the first sentence. (We have only one).
  5. Return the response with the body containing the sentence and the polarity to the caller.
  6. Run the flask object app to listen for requests on localhost:5000.

The services are set up to communicate with each other, give them a try before continuing on!

Fig. 1. Microservice architecture set up

Let’s recapitulate what we did; We started all the microservices running in different ports, we configured each to communicate with each other, and this was a tedious process, but it worked, so why Kubernetes you ask? Because our application is not scalable, it’s not resilient and not maintainable. Stay tuned as in the next article, we will go over how to start the services in Docker Containers, as it is a prerequisite to being able to run them in Kubernetes Cluster.