Skip to content

Instantly share code, notes, and snippets.

@wfng92
Created October 19, 2021 08:27
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wfng92/0cc6673e9ce4e8b880e6a38c134ed0cf to your computer and use it in GitHub Desktop.
Save wfng92/0cc6673e9ce4e8b880e6a38c134ed0cf to your computer and use it in GitHub Desktop.
import streamlit as st
import aiohttp
import asyncio
async def fetch(session, url):
try:
async with session.get(url) as response:
result = await response.json()
return result
except Exception:
return {}
async def main():
st.set_page_config(page_title="Example App", page_icon="🤖")
st.title("Get Image by Id")
async with aiohttp.ClientSession() as session:
with st.form("my_form"):
index = st.number_input("ID", min_value=0, max_value=100, key="index")
submitted = st.form_submit_button("Submit")
if submitted:
st.write("Result")
data = await fetch(session, f"https://picsum.photos/id/{index}/info")
if data:
st.image(data['download_url'], caption=f"Author: {data['author']}")
else:
st.error("Error")
if __name__ == '__main__':
loop = asyncio.new_event_loop()
loop.run_until_complete(main())
@Dimfred
Copy link

Dimfred commented Nov 25, 2022

Does this really work? As soon as the streamlit page refreshes the main is called again and it happens that loop is closed then / a new one is created.

@kratika2210
Copy link

kratika2210 commented Sep 11, 2023

+1 to @Dimfred's question

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment