The following article is from wechat public number Python programming time, if there is infringement, contact will be deleted

Pywebio is a Plus + Pro + Max version of PyWeBio, but it is very powerful. Before learning a new framework, you should research what it can do.

But for Streamlit, believe me, it’s a framework you can learn without thinking, and I say that because I’m sure you’ll be able to use it someday.

Streamlit is a Python framework for machine learning and data visualization that can build a beautiful online app in just a few lines of code.

What does it do, depending on what you want to do?

Streamlit is very powerful and has a lot of functions to learn, but it’s very easy to learn and much cheaper to learn than front-end +Flask. Next, I will introduce them one by one.

# 1. How to install?

As with other packages, installing Streamlit is as simple as a single command

➜ pip install streamlit 
Copy the code

Given that Streamlit comes with a lot of installed tool dependencies, I used Venv to create a new virtual environment so as not to contaminate my current primary environment.

➜ python3 -m venv.Copy the code

Then run the following command to enter the virtual environment

➜ source. / venv/bin/activateCopy the code

Next, install Streamlit with the command above.

There are a lot of packages installed (close to 92?). The process will take a long time and will require patience

➜ PIP list | wc - 92 lCopy the code

During the installation process, you may encounter some problems, but not necessarily, it depends on your machine, if you encounter problems, please use the search engine to solve.

# 2. Getting started example

Streamlit provides some examples to get started

➜ streamlit hello!Copy the code

Streamlit automatically opens the browser after execution to load a local page http://localhost:8501/

There are a lot of demos in there, and you can take a look at them, and they have the code that goes with them

These codes can be copied and saved so that you can run the following commands on the local PC

➜ streamlit run st - demo. PyCopy the code

# 2. Markdown text

Once Streamlit is imported, it can be initialized directly with St.Markdown (), calling different methods to populate the document object

  • St. title() : Article title
  • St.header () : Level 1 header
  • St. subheader() : Secondary header
  • St. text () : the text
  • St.code () : code, and the language of the code can be set. It is highlighted when displayed
  • St.latex () : latex formula
  • St. Caption () : Small font text

The following is a small Demo I wrote for your reference

import streamlit as st

# markdown
st.markdown('Streamlit Demo')

Set the page title
st.title('A Python artifact for building visual Web for dumb-ass -- Streamlit')

# Show level 1 titles
st.header('1. Install')

st.text('Like installing any other package, installing Streamlit is simple, with a single command')
code1 = '''pip3 install streamlit'''
st.code(code1, language='bash')


# Show level 1 titles
st.header('2. Use')

# Show secondary headings
st.subheader('2.1 Generate Markdown document ')

# plain text
st.text('After streamlit is imported, it can be initialized directly with St.Markdown ()')

# Show code with highlight effect
code2 = '''import streamlit as st
st.markdown('Streamlit Demo')'''
st.code(code2, language='python')
Copy the code

Streamlit runs differently than normal scripts and should use Streamlit Run st-demo.py

After running, the browser will automatically open and load the page. If it does not open automatically, you can also manually copy the link in the above image to open the page.

Does it smell a little like that? That’s it. It’s just an appetizer

# 3. Data chart support

3.1 Chart Components

Streamlit is supported by two components for the presentation of data

  • Table: a common table used to display static data
  • Dataframe: Advanced table for data manipulation, such as sorting

The Table of the sample

df = pd.DataFrame(
    np.random.randn(10.5),
    columns=('column %d' % (i+1for i in range(5))
)

st.table(df)
Copy the code

Results the following

Datafram sample

df = pd.DataFrame(
    np.random.randn(10.5),
    columns=('column %d' % (i+1for i in range(5))
)

st.dataframe(df.style.highlight_max(axis=0))
Copy the code

And it looks like this, and you can see on the outside, there’s a little downward arrow, and when you click on it, it sort

In addition, you can also see that I have highlighted the maximum value because I passed in the argument df.style.highlight_max(axis=0)

In fact, there are n more styles, such as:

  • Highlight_null: null value highlighting
  • Highlight_min: minimum highlighting
  • Highlight_max: maximum highlighting
  • Highlight_between: highlights values in a range
  • Highlight_quantile: not used yet

You can find examples of all of these in the source code

3.2 Monitoring Components

Streamlit also provides metric components if you need to make a monitoring panel after collecting some monitoring data

The following code creates three metrics and fills in the corresponding data

col1, col2, col3 = st.columns(3)
col1.metric("Temperature"."70 ° F"."1.2 ° F")
col2.metric("Wind"."9 mph"."8%")
col3.metric("Humidity"."86%"."4%")
Copy the code

Refresh the page and see the following

3.3 Native chart components

Streamlit native supports a variety of charts:

  • St. line_chart: line chart
  • St. area_chart: Area chart
  • St. bar_chart: Bar chart
  • St. map: the map

I’ll show you one by one

The line chart

chart_data = pd.DataFrame(
    np.random.randn(20.3),
    columns=['a'.'b'.'c'])

st.line_chart(chart_data)
Copy the code

Area chart

chart_data = pd.DataFrame(
    np.random.randn(20.3),
    columns = ['a'.'b'.'c'])

st.area_chart(chart_data)
Copy the code

A histogram

chart_data = pd.DataFrame(
    np.random.randn(50.3),
    columns = ["a"."b"."c"])
st.bar_chart(chart_data)
Copy the code

The map

df = pd.DataFrame(
    np.random.randn(1000.2/ [50.50] + [37.76, -122.4],
    columns=['lat'.'lon']
)
st.map(df)
Copy the code

3.4 External chart components

Some of Streamlit’s native chart components, while dumb, can only enter data, height, and width. If you want a prettier chart, Like Matplotlib.pyplot, Altair, Vega-Lite, Plotly, Bokeh, PyDeck, Graphviz, Streamlit also provides support:

  • st.pyplot
  • st.bokeh_chart
  • st.altair_chart
  • st.altair_chart
  • st.vega_lite_chart
  • st.plotly_chart
  • st.pydeck_chart
  • st.graphviz_chart

For this part, students who are familiar with it have tried it by themselves, and it will not be demonstrated here.

# 4. User operation support

All of the previous streamlit displays are text and data, and if that’s all, then Streamlit is just so so

For those who don’t know the front end and usually need to write some simple pages, the ability to write some interactive interfaces is a hard requirement.

Fortunately, Streamlit supports almost all of the interactive components you normally see on the web and in apps.

  • Button, button
  • Download_button: File download
  • File_uploader: uploads files
  • Checkbox: indicates the checkbox
  • Radio: Optional
  • Selectbox: a drop-down list box
  • Multiselect: a drop-down list box
  • Slider: indicates a sliding bar
  • Select_slider: select bar
  • Text_input: Text input box
  • Text_area: Text display box
  • Number_input: indicates a number input box that supports addition and subtraction buttons
  • Date_input: Date selection box
  • Time_input: time selection box
  • Color_picker: color picker

There are a lot of them, and they’re pretty simple, so you don’t need to give them one by one. You can just go to the comments in the Streamlit source code.

# 5. Multimedia components

To play images, audio, and video on a page, you can use these three components of Streamlit:

  • st.image
  • st.audio
  • st.video

# 6. State components

The status component is used to show the current running state of the program to the user, including:

  • Progress: progress bar, such as game loading progress
  • Spinner: Wait for the cue
  • Balloons: Float at the bottom of the page in congratulations
  • Error: Displays error information
  • Warning: Displays alarm information
  • Info: Displays general information
  • Success: The success information is displayed
  • Exception: Displays exception information (code error stack)

The effect is as follows:

# 7. Page layout

Streamlit is rendered top-down, and the order in which components are arranged on the page corresponds to the order in which the code is executed.

For a beautiful Web app, a one-column layout is definitely not enough.

In fact, Streamlit also offers a variety of layouts:

St. sidebar: Sidebar

The sidebar can do some user controls

St. columns: Column containers, components within the same columns, displayed from left to right

St. Expander: To hide the information, click to expand the detailed content, such as: show more

St. Container: A container containing multiple components

St. Empty: Container containing a single component

# 8. Process control system

Streamlit renders progressively from top to bottom, and if your scene requires some control over rendering, Streamlit also provides a way to do so

  • St. stop: Allows the Streamlit application to be stopped without going down, for example, after the verification code has passed, and then running down to show the subsequent content.
  • St. form: Form, Streamlit reexecutes the page program after a component has interacted with it, but sometimes it is necessary to wait for a set of components to complete the interaction before refreshing (e.g., login for username and password) and then add these components to the form
  • St. form_submit_button: Used in forms, submit the form.

# 9. Caching features improve speed

When the user does something on the page, such as entering data, the entire Streamlit application code is reexecuted, and if there are steps to read external data (gigabytes of data), the performance loss can be terrible.

Streamlit, however, provides a cache decorator that, when reexecuting code to render a page, looks in the cache first and calls the cached result if the code or data has not changed.

It is easy to use the @st.cache decorator for functions that need caching.

DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'
            'streamlit-demo-data/uber-raw-data-sep14.csv.gz')

@st.cache
def load_data(nrows) :
    data = pd.read_csv(DATA_URL, nrows=nrows)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
    return data
Copy the code

# 10. Deploy online

Streamlit applications, written locally, are only accessible locally once they are up and running.

To make the application accessible to others, you need to have a server that can be accessed via a public IP address

If you need a server, you can click this link to get a coupon.

Another option is to deploy your application using Heroku.

Heroku is a cloud platform as a service that supports multiple programming languages. All you need to do is register an account (I heard that NetEase and QQ email are not available, but I use Gmail to register).

And then create your own app

The name of this App seems to be unique on the whole web. I wanted to call it Hello-streamlit, but it has already been used.

Then create several Heroku specified files for your application

  • Requirements. TXT: dependency package file
  • Setup. sh: installation script that creates folders and writes configuration files
  • Procfile: Startup script that tells Heroku how to install and start the application

The encoding of these files has a fixed format.

Once you have this template, you can create your Git repository based on it

git init
git add --all
git commit -m "init"
Copy the code

And then deployed to Heroku

heroku login
heroku create
git push heroku master
heroku ps:scale web=1
Copy the code

Follow the URL output from the command line to access your application.

View Heroku logs:

heroku logs --tail
Copy the code

To use your own domain, you need to be authenticated by Heroku. Then run:

heroku domains:add hivecnstats.iswbm.com
Copy the code

The only disadvantage of using Heroku is that Heroku requires a ladder, which is not accessible to ordinary people. If there is no condition, it is still a obedient standby server.

# 12. To sum up

Streamlit is an out-of-the-box toolset that allows the average individual developer to quickly and easily build a clean, elegant Web app without having to learn a lot about the front-end.

For those of you in the field of data analytics or machine learning, it’s a great tool to develop, but even if you’re not in that field, you’ll definitely need to build a Web app, and StreamLit is exactly what you need.