main.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. #!/usr/bin/env python3
  2. import asyncio
  3. from typing import Optional
  4. import httpx
  5. from nicegui import events, ui
  6. api = httpx.AsyncClient()
  7. running_query: Optional[asyncio.Task] = None
  8. async def search(e: events.ValueChangeEventArguments) -> None:
  9. '''Search for cocktails as you type.'''
  10. global running_query
  11. if running_query:
  12. running_query.cancel() # cancel the previous query; happens when you type fast
  13. search_field.classes('mt-2', remove='mt-24') # move the search field up
  14. results.clear()
  15. # store the http coroutine in a task so we can cancel it later if needed
  16. running_query = asyncio.create_task(api.get(f'https://www.thecocktaildb.com/api/json/v1/1/search.php?s={e.value}'))
  17. response = await running_query
  18. if response.text == '':
  19. return
  20. with results: # enter the context of the the results row
  21. for drink in response.json()['drinks'] or []: # iterate over the response data of the api
  22. with ui.image(drink['strDrinkThumb']).classes('w-64'):
  23. ui.label(drink['strDrink']).classes('absolute-bottom text-subtitle2 text-center')
  24. running_query = None
  25. # create a search field which is initially focused and leaves space at the top
  26. search_field = ui.input(on_change=search) \
  27. .props('autofocus outlined rounded item-aligned input-class="ml-3"') \
  28. .classes('w-96 self-center mt-24 transition-all')
  29. results = ui.row()
  30. ui.run()