Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add examples for asynchronous usage (callback, asycio) #324

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import asyncio
import functools

from kubernetes import client, config


# return a callback and assigned future where data will be stored
def create_async_callback():
def set_result(loop, future, data):
loop.call_soon_threadsafe(future.set_result, data)
future = asyncio.Future()
return functools.partial(
set_result, asyncio.get_event_loop(), future), future


async def main():

# Configs can be set in Configuration class directly or using helper
# utility
config.load_kube_config()

v1 = client.CoreV1Api()
print("Listing pods with their IPs:")

callback, future = create_async_callback()
v1.list_pod_for_all_namespaces(watch=False, callback=callback)
ret = await future
for i in ret.items:
print(
"%s\t%s\t%s" %
(i.status.pod_ip,
i.metadata.namespace,
i.metadata.name))


if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
25 changes: 25 additions & 0 deletions examples/callbacks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import time

from kubernetes import client, config


def recv_namespace(data):
print("Listing pods with their IPs:")
for i in data.items:
print(
"%s\t%s\t%s" %
(i.status.pod_ip,
i.metadata.namespace,
i.metadata.name))


# Configs can be set in Configuration class directly or using helper utility
config.load_kube_config()

v1 = client.CoreV1Api()
thread = v1.list_pod_for_all_namespaces(watch=False, callback=recv_namespace)

# do something in the main thread
for i in range(0, 10):
print('-- do something --')
time.sleep(0.5)