DEV Community

Cover image for Deploying cloud-based Python web apps with Streamlit sharing
Scofield Idehen
Scofield Idehen

Posted on • Originally published at blog.learnhub.africa

Deploying cloud-based Python web apps with Streamlit sharing

Streamlit is an open-source Python library that makes it easy to create and share beautiful, custom web apps for machine learning and data science. With Streamlit, you can turn Python scripts into web apps in just a few minutes without knowing any JavaScript or HTML.

One of the best features of Streamlit is Streamlit sharing, which allows you to deploy your Streamlit apps for free instantly. Streamlit sharing handles all the complexity of deployment and hosting so you can focus on building your apps.

In this article, we’ll walk through how to use Streamlit sharing to deploy a simple Python web app powered by Streamlit. We’ll cover:

  • Creating a basic Streamlit app
  • Signing up for Streamlit sharing
  • Deploying the app with one click
  • Customizing and updating the deployed app
  • Best practices for production Streamlit apps

Creating a Basic Streamlit App

First, let’s create a simple Streamlit app that we can deploy. We’ll build an app that classifies iris flowers based on sepal/petal measurements using sklearn’s iris dataset and a random forest model.

Import the necessary libraries:

import streamlit as st
import pandas as pd 
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
Enter fullscreen mode Exit fullscreen mode

Define a function to make predictions:

def prediction(sepal_length, sepal_width, petal_length, petal_width):  

    # load dataset 
    data = load_iris()
    # prepare data
    X = data.data 
    Y = data.target
    # model building
    clf = RandomForestClassifier() 
    clf.fit(X, Y)

    # make predictions 
    prediction = clf.predict([[sepal_length, sepal_width, petal_length, petal_width]])
    prediction = prediction[0]

    return prediction
Enter fullscreen mode Exit fullscreen mode

In our Streamlit app, we’ll create sliders to input the flower measurements then display the predicted species:

# Streamlit app 
st.write("""
# Iris Flower Species Prediction App
""")

sepal_length = st.slider('Sepal length', 0.0, 10.0, 5.0)  
sepal_width = st.slider('Sepal width', 0.0, 10.0, 5.0)
petal_length = st.slider('Petal length', 0.0, 10.0, 5.0)  
petal_width = st.slider('Petal width', 0.0, 10.0, 5.0)

species_type = prediction(sepal_length, sepal_width, petal_length, petal_width)  

st.write('Predicted iris species:', species_type)
Enter fullscreen mode Exit fullscreen mode

That’s our basic app! Next, let’s look at deploying it for free with Streamlit sharing.

Signing Up for Streamlit Sharing

To deploy our Streamlit app, we first need to sign up for a free Streamlit sharing account:

  • Go to streamlit and click “Sign up”

  • Sign up with your Email or with GitHub.

  • A Streamlit account will automatically be created after you fill in your details.

That’s all there is to it! We now have everything we need to deploy apps to the cloud instantly.
Deploying the App

With just a single terminal command, we can now deploy our app to the cloud via Streamlit sharing:

$ streamlit run my_app.py --global.sharingMode=s3
Enter fullscreen mode Exit fullscreen mode

The --global.sharingMode=s3 flag tells Streamlit to deploy our app. We’ll be prompted to enter a unique app name and select a sharing access level. Let’s name our app “iris-classifier” and make it publicly viewable.

Once deployed, we can access our live web app from the app URL printed in the terminal and also view it by going to streamlit and selecting our app. It’s that simple to create and deploy cloud-hosted Streamlit apps!

Customizing and Updating

Our app is now live, but the work doesn’t stop there. Streamlit sharing gives us some great benefits when customizing and iteratively improving our app over time:

Automatic updates - Any changes we push to our code are automatically redeployed. There’s no need to redeploy each time manually.

Version control - Streamlit keeps the version history of our deployed apps, allowing us to revert to older versions or deploy side-by-side versions for testing.

Custom domains - We can associate our own custom domain name with apps, providing branded, professional hosting.

Private apps - Streamlit supports restricted app access through authorization and teams, which is useful for internal web tools.

By handling deployment details behind the scenes, Streamlit sharing lets us focus on rapidly developing and refining our app.

Best Practices for Production

Here are a few key tips to follow when developing production-level Streamlit apps:

  • Validate input data - Use Streamlit components like input sliders/text areas to constrain what values a user can provide. Validate malformed inputs server-side before passing to models.
  • Handle errors gracefully - Use try/except blocks and Streamlit error components to account for any failures and provide helpful error messages to users.
  • Structure for scale - Break code into modules to better manage complex logic. Use Streamlit components for reusable UI elements.
  • Monitor usage - Integrate GA for usage analytics. Use Streamlit session states to track user state. Monitor logs for any application issues.
  • Update dependencies - Streamlit provides images with the latest Python data science packages. Manage dependencies explicitly for production.

Following best practices like these, we can take our Streamlit prototype apps and harden them for real-world usage.

Conclusion

With Streamlit’s incredibly simple deployment model, we can go from idea to deployed web app in just minutes. By handling all DevOps complexity behind its easy-to-use interface, Streamlit allows us to focus on rapidly developing and iterating data apps.

Some key highlights:

  • Instantly deploy Python scripts as web apps with streamlit run
  • Free cloud hosting through Streamlit sharing
  • Automatic updates and version control
  • Ability to fully customize and refine over time
  • Best practices available for hardened production apps

The power of Streamlit is how it completely changes the game for creating and deploying data-driven web tools. Streamlit allows us to create various web apps for analysis and ML model serving by putting deployment on autopilot. The sky's the limit on what you can build and easily deploy with Streamlit!

If you find this post exciting, find more exciting posts on Learnhub Blog; we write everything tech from Cloud computing to Frontend Dev, Cybersecurity, AI, and Blockchain.

Resource

Top comments (0)