k8s/StudyNotes/ k8s Python app.py

   1 from flask import Flask, request
   2 from flask import render_template
   3 import requests
   4 import os.path
   5 
   6 TEMPLATES_FOLDER = 'templates'
   7 STATICS_FOLDER = 'static'
   8 app = Flask(__name__, static_url_path='', static_folder=STATICS_FOLDER, template_folder=TEMPLATES_FOLDER)
   9 
  10 SA_TOKEN = None
  11 SA_TOKEN_FROM_PATH = None
  12 SA_TOKEN_PATH = '/var/run/secrets/kubernetes.io/serviceaccount/token'
  13 
  14 APP_NAME = "APP_NAME" in os.environ and os.environ.get('APP_NAME') or "My Kubernetes Dashboard"
  15 
  16 
  17 @app.route('/test', methods=['POST'])
  18 
  19 def test():
  20     global SA_TOKEN
  21     json_data = request.get_json(silent=True)
  22 
  23     print("json_data")
  24     print(json_data)
  25 
  26     SA_TOKEN = "token" in json_data and json_data["token"] or SA_TOKEN_FROM_PATH
  27 
  28     print("SA_TOKEN=" + str(SA_TOKEN))
  29 
  30     test_results = requests.get('https://kubernetes.default.svc/api/v1/namespaces/default/pods', headers={'Authorization': 'Bearer ' + str(SA_
  31 TOKEN)},
  32                                         verify=False)
  33 
  34     print("test_results.text")
  35     print(test_results.text)
  36     print("test_results.status_code")
  37     print(test_results.status_code)
  38 
  39     return (test_results.text, test_results.status_code)@app.route('/')def main():    try:        return render_template('index.html', theme='blue', app_name=APP_NAME, backgroundcolor='#2980b9')
  40     except Exception as ex:
  41         print(str(ex))
  42 
  43 
  44 if __name__ == "__main__":
  45 
  46     if os.path.exists(SA_TOKEN_PATH):
  47         f = open(SA_TOKEN_PATH, "r")
  48         SA_TOKEN_FROM_PATH = f.read()
  49     app.run(host="0.0.0.0", port=8080)

k8s/StudyNotes/k8sPythonApp (last edited 2021-10-23 08:28:48 by PieterSmit)