Skip to content

Instantly share code, notes, and snippets.

@ma7dev
Last active March 25, 2023 21:43
Show Gist options
  • Save ma7dev/644e7c060839e659635f0b736a6d9885 to your computer and use it in GitHub Desktop.
Save ma7dev/644e7c060839e659635f0b736a6d9885 to your computer and use it in GitHub Desktop.
Streamlit + Flask example

A simple example for Streamlit and Flask project

  • server.py contains the API code for the Flask server (back-end)
  • main.py contains the streamlit code (front-end)

Requirements

pip install plotly streamlit pandas requests flask

Running

To the run the example, you will need to have two separate terminals and run the two scripts:

# to run the Flask server
FLASK_APP=server.py flask run
# to run Streamlit
streamlit run main.py
##########################################################
# to run: streamlit run main.py
##########################################################
import plotly.express as px
import streamlit as st
import pandas as pd
import requests
# labels
labels = requests.get("http://localhost:5000/api/labels").json()
selector = st.multiselect("Select WELL:", labels)
# load data
data = pd.read_json(
requests.get("http://localhost:5000/api/data", params={"selector": selector}).json()
)
# setup figure
fig = px.scatter(
x=data["PHIND"],
y=data["GR"],
)
st.write(fig)
##########################################################
# to run: FLASK_APP=server.py flask run
##########################################################
import json
from flask import Flask, request
app = Flask(__name__)
import pandas as pd
import numpy as np
train = pd.read_csv(
"https://raw.githubusercontent.com/pkhetland/Facies-prediction-TIP160/master/datasets/facies_vectors.csv"
)
train = train.rename(columns={"Well Name": "WELL"})
@app.route("/api/data")
def data():
selector = request.args.get("selector")
if not selector:
selector = "SHRIMPLIN"
# print(selector)
data = train[train["WELL"].isin([selector])]
# print(data)
return json.dumps(data.to_json())
@app.route("/api/labels")
def labels():
return json.dumps(train.WELL.unique().tolist())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment