Streamlit has come a long way since its inception back in October of 2019. It has empowered the software development community and has effectively democratized the way we develop and deploy apps to the cloud. However as with all new tools, there is still some way to go, and while the Streamlit team works tirelessly on addressing requests for new features, we developers ourselves can create ad hoc work arounds in the meantime.
A feature that Streamlit currently lacks, is the ability to implement programmable state for its apps. In its current form, there is no internal state that can store volatile data such as user inputs, dataframes and values entered into widgets. Given that Streamlit innately re-runs the entire script when the user triggers an action in the event of pressing a button or switching between pages, the app will reset all inputs and data. While for many applications, this is a non-issue, for others it can be a deal breaker. Just imagine if you are trying to build an app with sequential logic using incremental steps, the absence of a stateful architecture would render Streamlit as an unsuitable framework. The founders have committed to releasing a stateful version in the near future, but until then, one can use an open source database such as PostgreSQL to develop a hack as I will explain below.
PostgreSQL or Postgres for short is a free and open source relational database system that is often the database of choice for most developers due to its ease of use and extended capabilities. While it is ostensibly a structured database management system, it can also store non-structured data such as arrays and binary objects, which makes it rather useful for open-ended projects. In addition, its graphical user interface is highly intuitive and straightforward ensuring that the learning curve is very shallow.
In our implementation of a stateful architecture, we will be using a local Postgres server to store our state variables such as the user inputs and dataframes generated in our Streamlit app. Before we proceed, please download and install Postgres using this link. During the installation you will be prompted to configure a username, password and local TCP port to forward your database server to. The default port is 5432 which you may keep as is. Once the installation is completed, you will be able to login to your server by running the ‘pgAdmin 4’ application which will then open your server’s portal on your browser as shown below.
#web-development #cloud-computing #data #data-science #database