Created
September 27, 2022 17:24
-
-
Save asehmi/fe5f6733fc5ab6d615d28f920b676f57 to your computer and use it in GitHub Desktop.
Embedding Flask in Streamlit
This file contains 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 requests | |
import streamlit as st | |
state = st.session_state | |
if 'flask_started' not in state: | |
state.flask_started = False | |
def start_flask(): | |
if state.flask_started: | |
return | |
import os, sys, time | |
import subprocess | |
import threading | |
def _run(job): | |
print (f'\nRunning job: {job}\n') | |
proc = subprocess.Popen(job) | |
proc.wait() | |
return proc | |
job = [f'{sys.executable}', os.path.join('.', 'flask_runner.py'), 'localhost', '8888'] | |
# server thread will remain active as long as streamlit thread is running, or is manually shutdown | |
thread = threading.Thread(name='Flask Server', target=_run, args=(job,), daemon=False) | |
thread.start() | |
time.sleep(5) | |
state.flask_started = True | |
flask_message = st.empty() | |
x = st.slider('Pick a number') | |
st.write('You picked:', x) | |
start_flask() | |
if state.flask_started: | |
resp = requests.get('http://localhost:8888/foo').text | |
flask_message.write(resp) |
This file contains 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 time | |
import datetime as dt | |
from flask import Flask | |
def flask_runner(): | |
app = Flask(__name__) | |
@app.route('/foo') | |
def serve_foo(): | |
ts = time.time() | |
t = dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S") | |
return f'Hello from Flask! ({t})' | |
app.run(port=8888) | |
if __name__ == '__main__': | |
flask_runner() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment