Created
July 19, 2023 14:40
-
-
Save kulothunganug/1c90a856f054e988b6ee3c91323e0f5e to your computer and use it in GitHub Desktop.
Asynchronous http request in kivy
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import httpx | |
from kivy.animation import Animation | |
from kivy.app import App | |
from kivy.uix.boxlayout import BoxLayout | |
from kivy.uix.button import Button | |
from kivy.uix.label import Label | |
class AsyncRequestsApp(App): | |
def __init__(self, **kwargs): | |
super().__init__(**kwargs) | |
self.data = [] | |
self.loading = False | |
def on_start(self): | |
anim = Animation(font_size=10) + Animation(font_size=30) | |
anim.repeat = True | |
anim.start(self.anim_widget) | |
def build(self): | |
self.layout = BoxLayout(orientation="vertical") | |
self.anim_widget = Label( | |
text="Animated label to check whether it is blocking the UI or not", | |
font_size=10, | |
) | |
self.layout.add_widget(self.anim_widget) | |
self.message_label = Label(text="Press below", size_hint=(1, 0.2)) | |
self.layout.add_widget(self.message_label) | |
self.load_button = Button(text="Load Data", size_hint=(1, 0.2)) | |
self.load_button.bind(on_press=self.fetch_data) | |
self.layout.add_widget(self.load_button) | |
return self.layout | |
def fetch_data(self, instance): | |
if not self.loading: | |
self.loading = True | |
self.message_label.text = "Loading Data..." | |
asyncio.ensure_future(self.get_data_from_api()) | |
async def get_data_from_api(self): | |
try: | |
async with httpx.AsyncClient() as client: | |
res = await client.get("https://jsonplaceholder.typicode.com/posts") | |
self.data = res.json() | |
await asyncio.sleep(2) | |
self.loading = False | |
self.message_label.text = "Data Loaded!" | |
except Exception as e: | |
self.loading = False | |
self.message_label.text = f"Error: {str(e)}" | |
print(f"Error: {str(e)}") | |
if __name__ == "__main__": | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(AsyncRequestsApp().async_run(async_lib="asyncio")) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment