How to Create a User Interface for Your Python Application

Python is one of the common programming languages ​​for automating SEO processes.

One of the best libraries to create a front-end for our applications without any knowledge of HTML, CSS or coding with a JavaScript-based framework is the Streamlit package.

In this Streamlit tutorial, we will explain how to create a nice application with Python and the Dockerfile to deploy your Streamlit application.

What is Streamlit?

Streamlit is an open-source application framework (a Python package) that gives us the power to build beautiful applications without any front-end development knowledge.

This frees us from any involvement in a front-end framework or coding in HTML, CSS and JavaScript.

You use pure Python to develop your front-end.

When will the Streamlit library become useful?

First of all, if you are coding Python scripts that run regularly on a machine with a task scheduler like cron, Streamlit is not useful for you.

But if you are developing a tool that you want to share with your team members, such as a keyword research app, you can use Streamlit.

Also, if you need a user authentication method, the Streamlit community has developed a package that can handle it for you.

Create a Streamlit application: getting started

Let’s create a simple app that gets autocomplete queries for a seed keyword from Google’s public API.

Before you begin, create a folder on your machine and name it whatever you want.

Also, I’ll assume you already have Python installed and know the basics of Python programming.

For the whole process, we need to use these Python libraries:

  • Requests.
  • Streamlit.
  • Streamlit-Authenticator.
  • PyYAML.

Additionally, we’ll import a standard Python library:

The tutorial code is in my Streamlit starter template repository on Github.

Installing the Streamlit package

First, I prefer to create a virtual environment by running python3 -m venv .env and then installing the Streamlit package by running pip3 install streamlit.

Now create a Python script. Let’s call it streamlit_app.py.

In complex projects that have too many functions, I prefer to have separate Python script files for my different functions and then import them into streamlit_app.py or create a separate app with Flask or FastAPI.

For example, in a keyword research app, I have a Python script for different functions that get data from Semrush, a script to get top 10 or 20 results from Google, a script to get autocomplete from Google and Google-related searches, etc. .

Get autocomplete queries from Google

To make requests, we need to use the Requests package. To get this package you need to run pip3 install queries.

Also, to parse the autocomplete API response, we need to import the standard Python JSON library.

First, we import the standard JSON library, the Requests package to make requests, and Streamlit to build our application.

Next, I defined a function to get Google’s autocomplete queries as a list of strings.

I used the replace function twice to keep everything simple, but you can use the re library to use regex.

"""A Streamlit app for getting the Google autocomplete queries
"""
import json

import requests
import streamlit as st

def google_autocomplete(keyword: str) -> list[str]:
    """Get Google autocomplete queries for a seed keyword

    Args:
        keyword (str): The seed keyword

    Returns:
        list[str]: A list of the autocomplete queries
    """
    google_autocomplete_api: str = "https://www.google.com/complete/search"
    google_autocomplete_params: dict = {
        "q": keyword,
        "cp": 8,
        "client": "gws-wiz",
        "xssi": "t",
        "hl": "en-US"
    }

    response = requests.get(google_autocomplete_api, params=google_autocomplete_params)

    list_google_autocomplete_uncleaned: list
    = json.loads((response.content).decode("UTF-8")[5:])[0] list_google_autocomplete_cleaned: list[str] = [ element[0].replace('', '').replace('', '') for element in list_google_autocomplete_uncleaned ] return list_google_autocomplete_cleaned

    The Streamlit app

    So far we have installed the Streamlit package and defined our function to get Google’s autocomplete queries. Now let’s create the actual application.

    To view the Streamlit app, we need to run Streamlit with the run streamlit_app.py command in the terminal to run our app locally. After running this command, by accessing the URL http://localhost:8501/, you can view the application.

    Yes, it’s empty because we haven’t added any titles etc. to it.

    Screenshot by author, October 2022

    Add title to Streamlit app

    Let’s add a title to our application. As you see above, I imported the Streamlit as st.

    Now, by calling the st.title() function, we can add a title to the page with a title style. Let’s say st.title (“This is a top level SEO application”).

    Remember that after editing your streamlit_app.py file and saving it, an icon will appear in the top right corner of the page and you should press always come back to view changes to the app without any page refreshes.

    Always return button in the Streamlit appScreenshot by author, October 2022

    Now our application looks like the image below. If your system theme is dark, your app is dark-themed.

    A preview of a Streamlit application with headerScreenshot by author, October 2022

    Add Text to Streamlit App

    To add a paragraph of text to the application, you must use the st.write() function. For example, st.write(“Put your ideas into action”).

    Steamlit appScreenshot by author, October 2022

    Add text input to Streamlit app

    As you saw in Google’s autocomplete function, there was an argument called “keyword”.

    This argument must come from user input.

    To get user input, we can use a text input field in Streamlit. With st.text_input() we can add text input. For example, st.text_input(“What is your seed keyword?”).

    Also, in order to use the input keyword later to pass to our function, we need to assign it to a variable.

    input_google_autocomplete_keyword: str = st.text_input(
        "What is your seed keyword?")

    Now we want to run our application when there is an input keyword. Here we are using an if statement to check whether the variable is empty or not.

    if input_google_autocomplete_keyword:
        output_list_google_autocomplete: list[str] = google_autocomplete(
            input_google_autocomplete_keyword)
    Preview of a Streamlit application with a header, text and text inputScreenshot by author, October 2022

    Download from Streamlit app

    So we added a header, a line of text and a text input field to get the user keyword.

    Now we need to run our written function and create a download button for the user to get the results in a text file.

    if output_list_google_autocomplete:
            st.download_button("Download the output",
                               ("n").join(output_list_google_autocomplete))
    Preview of a Streamlit app with title, text, text input and download buttonScreenshot by author, October 2022

    We have created our simple app! Let’s change the app title and favicon.

    Before that, let’s see the code from the Streamlit app section so far.

    The code of the Streamlit application sectionScreenshot by author, October 2022

    Change app title and favicon

    The app’s default title is streamlit_app · Streamlit, and the app’s favicon is the Streamlit icon.

    To change the title and the favicon we have to use the st.set_page_config().

    Also, I prefer the app layout to be wide (you can test it).

    st.set_page_config(
        page_title="Oh My App!",
        page_icon="😎",
        layout="wide"
    )
    The Streamlit app in the browserScreenshot by author, October 2022

    Set app default theme

    The app theme is based on the user’s system settings, but personally most of the time I find the light theme has better contrast – and I don’t want my team to spend their time figuring out how change app theme.

    To set a default theme for the Streamlit application, you must first create a folder and name it .streamlit. In this folder, create a file and name it config.toml.

    In the config.toml file, you need to insert the lines below to set the default theme for your application.

    [theme]
    base = "light"
    confing.toml file code to customize Streamlit app themeScreenshot by author, October 2022

    User authentication in Streamlit

    Imagine that after deploying your application, someone discovers the application URL and accesses it.

    To protect your app, you need to authorize users before they can use the app – like most SASS we use every day.

    For a Streamlit application, we can use the Streamlit-Authenticator package. To install it, in the terminal located in your application folder, type the command pip3 install streamlit-authenticator and import the package into your application.

    I recommend that you read the Streamlit authentication package documentation to better understand what is going on.

    import streamlit_authenticator as stauth

    Now create a config.yaml file to insert our user credentials.

    credentials:
      usernames:
        firstUser:
          email: [email protected]
          name: The first username
          password: 12345 # Must be replaced with the hashed password
        secondUser:
          email: [email protected]
          name: The second username
          password: 111213 # Must be replaced with the hashed password
    cookie:
      expiry_days: 30
      key: some_signature_key
      name: some_cookie_name
    preauthorized:
      emails:
        - [email protected]

    As in the package document you can see, we now need to hash passwords with Hasher modules. I prefer to open an IPython and run the line of code below.

    hashed_passwords = stauth.Hasher([‘12345’, ‘111213’]).produce()

    Create a login widget

    Now we need to create a login widget where users can enter their username, password and then login to the application.

    First, you need to install the PyYAML package with the pip3 install pyyaml ​​command and import it with the import yaml file.

    Then create an authentication object and display the login module.

    with open("./config.yaml") as file:
        config = yaml.load(file, Loader=yaml.SafeLoader)
    
    authenticator = stauth.Authenticate(
        config["credentials"],
        config["cookie"]["name"],
        config["cookie"]["key"],
        config["cookie"]["expiry_days"],
        config["preauthorized"]
    )
    
    name, authentication_status, username = authenticator.login("Login", "main")
    The Streamlit Login WidgetScreenshot by author, October 2022

    Show app to successfully logged in users

    We can now use the authentication_status variable to see the app for our successfully logged in users.

    if authentication_status:
        authenticator.logout('Logout', 'main')
        # OUR APP CODE COMES HERE
    elif authentication_status == False:
        st.error('Username/password is incorrect')
    elif authentication_status == None:
        st.warning('Please enter your username and password')

    Deploy the Streamlit application with Docker

    We are now in the final stage of developing our app.

    You can use different services to deploy your application, such as AWS, Google Cloud, Azure, Heroku, DigitalOcean, etc.

    Before the Dockerfile, let’s create the requirements.txt file. To do this, we can use the command pip3 freeze > requirements.txt.

    Docker Streamlit File

    To deploy our application, I’m using Python 3.9.10.

    FROM python:3.9.10
    WORKDIR /app
    COPY . .
    RUN pip3 install -r requirements.txt
    CMD ["streamlit", "run", "streamlit_app.py"]
    EXPOSE 8501

    Wrap

    In this tutorial, we saw how to create a beautiful UI with pure Python and deploy it with Docker.

    To learn more about the different Streamlit widgets, check out their well-documented documentation API reference.

    More resources:


    Featured Image: Yaran/Shutterstock

    Comments are closed.