Frontend WebUI

Build WebUI that uses preceding microservice by following steps:

  1. Here is the simple frontend WebUI that also uses Python Flask:
$ cat entry.py
import os
import httplib
from flask import Flask, request, render_template

app = Flask(__name__)

@app.route("/")
def index():
return render_template('index.html')


@app.route("/add", methods=['POST'])
def add():
#
# from POST parameters
#
x = int(request.form['x'])
y = int(request.form['y'])

#
# from Kubernetes Service(environment variables)
#
my_calc_host = os.environ['MY_CALC_SERVICE_SERVICE_HOST']
my_calc_port = os.environ['MY_CALC_SERVICE_SERVICE_PORT']

#
# REST call to MicroService(my-calc)
#
client = httplib.HTTPConnection(my_calc_host, my_calc_port)
client.request("GET", "/addition/%d/%d" % (x, y))
response = client.getresponse()
result = response.read()
return render_template('index.html', add_x=x, add_y=y,
add_result=result)

if __name__ == "__main__":
app.debug = True
app.run(host='0.0.0.0')
Kubernetes service generates the Kubernetes service name and port number as an environment variable to the other pods. Therefore, the environment variable's name and the Kubernetes service name must be consistent. In this scenario, the my-calc service name must be my-calc-service
  1. The frontend WebUI uses the Flask HTML template; it is similar to PHP and JSP in that entry.py will pass the parameter to the template (index.html) to render the HTML:
$ cat templates/index.html
<html>
<body>
<div>
<form method="post" action="/add">
<input type="text" name="x" size="2"/>
<input type="text" name="y" size="2"/>
<input type="submit" value="addition"/>
</form>
{% if add_result %}
<p>Answer : {{ add_x }} + {{ add_y }} = {{ add_result }}</p>
{% endif %}
</div>
</body>
</html>
  1. Dockerfile is exactly the same as the microservice my-calc. So, eventually, the file structure will be as follows. Note that index.html is a jinja2 template file; therefore, put it under the /templates directory:
/Dockerfile
/entry.py
/templates/index.html
  1. Then, build a Docker image and push to Docker hub as follows:
In order to push your image to Docker hub, you need to log in using the Docker login command. It is needed only once; the system checks ~/.docker/config.json to read from there.
//build frontend Webui image 
$ sudo docker build -t hidetosaito/my-frontend .

//login to docker hub
$ sudo docker login

//push frontend webui image
$ sudo docker push hidetosaito/my-frontend
  1. Upon access to Docker hub, you can see your WebUI application in the repository:
Microservices and frontend WebUI image on Docker Hub
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.103.77