How to use ZeroMQ in Streamlit
Using ZMQ in streamlit is not trivial since the entire file will be executed many times. So you need to take care that context, socket etc are only created once.
The trick is to use @st.cache_resource
to cache the context and socket. Here’s an example:
#!/usr/bin/env python3
import zmq
import json
import streamlit as st
# Set up ZMQ PUB socket
@st.cache_resource
def init_zmq():
print("Initializing ZMQ")
context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:15629")
return context, socket
# Create context and socket, or use cached one
context,socket = init_zmq()
st.title('My streamlit ZMQ test')
# Create button
my_button = st.toggle('My button')
# Save button
if st.button('Save'):
st.write('Button clicked!')
message = json.dumps({
'my_button': all_motors_on,
})
print(f"Sending message: {message}")
socket.send_string(message)