Returning watch stream using Kubernetes with python client with server sent events

12/26/2019

I'm new to kubernetes and I wanted to return the watch stream data in JSON to frontend, where they have implemented store which will check the data and display it on UI. I'm implementing it with Flask and Server Sent Events, I've pasted the code here below, please suggest me if there is any better way to do this or how to return the data using watch. Also how to calculate the age of the pods?

def getpods():

    config.load_kube_config()
    w = watch.Watch()
    v1 = client.CoreV1Api()
    age_final = '0h'
    ret = w.stream(v1.list_pod_for_all_namespaces)
    for event in ret:

        list1=[]
        myjson = {}
        list2 = []
        restarts = 0
        if event['object'].status.container_statuses != None:
            for j in event['object'].status.container_statuses:
                restarts += j.restart_count
            list1.append([event['object'].metadata.name, event['object'].status.phase, restarts, age_final, event['object'].metadata.namespace])
            restarts = 0

        for i in range(0, len(list1)):
            myjson = {'name':list1[i][0],'phase':list1[i][1], 'restart':list1[i][2], 'age':list1[i][3], 'namespace' :list1[i][4]}

            list2.append(myjson)
            jdump = json.dumps(list2)

        print(jdump)


def stream():
    def evesource(): 
        while True: 
            yield 'data: {}\n\n'.format(getpods())
    return Response(evesource(), mimetype="text/event-stream")
-- RA_010
flask
kubernetes
kubernetes-pod
python
stream

0 Answers