100% found this document useful (4 votes)
17 views

Download (Ebook) Web Application Development with Streamlit: Develop and Deploy Secure and Scalable Web Applications to the Cloud Using a Pure Python Framework by Mohammad Khorasani, Mohamed Abdou, Javier Hernández Fernández ISBN 9781484281116, 148428111X ebook All Chapters PDF

The document provides information about various ebooks available for download on ebooknice.com, focusing on topics related to web application development, particularly using frameworks like Streamlit and Django. It includes details about specific titles, authors, and ISBN numbers, as well as links to access the ebooks. Additionally, it outlines the content structure of one specific ebook, 'Web Application Development with Streamlit,' detailing its chapters and topics covered.

Uploaded by

soodootudun8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
17 views

Download (Ebook) Web Application Development with Streamlit: Develop and Deploy Secure and Scalable Web Applications to the Cloud Using a Pure Python Framework by Mohammad Khorasani, Mohamed Abdou, Javier Hernández Fernández ISBN 9781484281116, 148428111X ebook All Chapters PDF

The document provides information about various ebooks available for download on ebooknice.com, focusing on topics related to web application development, particularly using frameworks like Streamlit and Django. It includes details about specific titles, authors, and ISBN numbers, as well as links to access the ebooks. Additionally, it outlines the content structure of one specific ebook, 'Web Application Development with Streamlit,' detailing its chapters and topics covered.

Uploaded by

soodootudun8
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Download the Full Ebook and Access More Features - ebooknice.

com

(Ebook) Web Application Development with


Streamlit: Develop and Deploy Secure and Scalable
Web Applications to the Cloud Using a Pure Python
Framework by Mohammad Khorasani, Mohamed Abdou,
Javier Hernández Fernández ISBN 9781484281116,
https://ebooknice.com/product/web-application-development-
148428111X
with-streamlit-develop-and-deploy-secure-and-scalable-web-
applications-to-the-cloud-using-a-pure-python-
framework-44888638

OR CLICK HERE

DOWLOAD EBOOK

Download more ebook instantly today at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;


Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374

ebooknice.com

(Ebook) Building Serverless Web Applications: Develop


scalable web apps using the Serverless Framework on AWS by
Zanon, Diego ISBN 9781787126473, 1787126471
https://ebooknice.com/product/building-serverless-web-applications-
develop-scalable-web-apps-using-the-serverless-framework-on-
aws-55161950
ebooknice.com

(Ebook) Secure Web Application Development: A Hands-On


Guide with Python and Django by Matthew Baker ISBN
9781484285954, 1484285956
https://ebooknice.com/product/secure-web-application-development-a-
hands-on-guide-with-python-and-django-46851192

ebooknice.com

(Ebook) Web App Development Made Simple with Streamlit: A


web developer's guide to effortless web app development,
deployment by Rosario Moscato
https://ebooknice.com/product/web-app-development-made-simple-with-
streamlit-a-web-developer-s-guide-to-effortless-web-app-development-
deployment-56268460
ebooknice.com
(Ebook) Learning Django Web Development_ From idea to
prototype, a learner's guide for web development with the
Django application framework by kan
https://ebooknice.com/product/learning-django-web-development-from-
idea-to-prototype-a-learner-s-guide-for-web-development-with-the-
django-application-framework-50195350
ebooknice.com

(Ebook) Beginner's Guide to Streamlit with Python: Build


Web-Based Data and Machine Learning Applications by Sujay
Raghavendra ISBN 9781484289822, 148428982X
https://ebooknice.com/product/beginner-s-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-47436422

ebooknice.com

(Ebook) Web App Development and Real-Time Web Analytics


with Python: Develop and Integrate Machine Learning
Algorithms into Web Apps by Nokeri, Tshepo Chris ISBN
9781484277829, 1484277821
https://ebooknice.com/product/web-app-development-and-real-time-web-
analytics-with-python-develop-and-integrate-machine-learning-
algorithms-into-web-apps-36127710
ebooknice.com

(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT


II Success) by Peterson's ISBN 9780768906677, 0768906679

https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018

ebooknice.com

(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena


Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312

ebooknice.com
Web Application
Development with
Streamlit
Develop and Deploy Secure
and Scalable Web Applications
to the Cloud Using a Pure
Python Framework

Mohammad Khorasani
Mohamed Abdou
Javier Hernández Fernández
Web Application Development with Streamlit: Develop and Deploy Secure
and Scalable Web Applications to the Cloud Using a Pure Python Framework

Mohammad Khorasani Mohamed Abdou


Doha, Qatar Cambridge, United Kingdom

Javier Hernández Fernández


Doha, Qatar

ISBN-13 (pbk): 978-1-4842-8110-9 ISBN-13 (electronic): 978-1-4842-8111-6


https://doi.org/10.1007/978-1-4842-8111-6

Copyright © 2022 by Mohammad Khorasani, Mohamed Abdou,


Javier Hernández Fernández
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: James Robinson-Prior
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233
Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail
[email protected], or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for
reprint, paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is
available to readers on the Github repository: https://github.com/Apress/Web-­Application-
Development-­with-­Streamlit. For more detailed information, please visit http://www.apress.com/
source-­code.
Printed on acid-free paper
To my parents Yeganeh and Daryoush and to
my departed grandparents Ghamar and Reza.
—Mohammad Khorasani
To my family, friends, and the open source community.
—Mohamed Abdou
To my family and friends for their support.
—Javier Hernández Fernández
Table of Contents
About the Authors������������������������������������������������������������������������������xiii

About the Technical Reviewers����������������������������������������������������������xv


Acknowledgments����������������������������������������������������������������������������xvii
Preface����������������������������������������������������������������������������������������������xix
Acronyms������������������������������������������������������������������������������������������xxi
Intended Audience���������������������������������������������������������������������������xxiii
Additional Material������������������������������������������������������������������������� xxvii

Chapter 1: Getting Started with Streamlit��������������������������������������������1


1.1 Why Streamlit?������������������������������������������������������������������������������������������������1
1.1.1 Local vs. the Cloud���������������������������������������������������������������������������������2
1.1.2 A Trend Toward Cloud Computing�����������������������������������������������������������3
1.1.3 History of Web Frameworks in Python���������������������������������������������������5
1.1.4 Flask�������������������������������������������������������������������������������������������������������6
1.1.5 Django����������������������������������������������������������������������������������������������������6
1.1.6 Dash�������������������������������������������������������������������������������������������������������7
1.1.7 Web2Py���������������������������������������������������������������������������������������������������7
1.1.8 The Need for a Pure Python Web Framework�����������������������������������������8
1.1.9 Academic Significance���������������������������������������������������������������������������8
1.2 Firing It Up������������������������������������������������������������������������������������������������������9
1.2.1 Technical Requirements�������������������������������������������������������������������������9
1.2.2 Environment Installation with Anaconda����������������������������������������������10

v
Table of Contents

1.2.3 Downloading and Installing Streamlit���������������������������������������������������15


1.2.4 Streamlit Console Commands��������������������������������������������������������������17
1.2.5 Running Demo Apps�����������������������������������������������������������������������������19
1.2.6 Writing and Testing Code with PyCharm�����������������������������������������������21
1.3 How Streamlit Works������������������������������������������������������������������������������������25
1.3.1 The Streamlit Architecture��������������������������������������������������������������������26
1.3.2 ReactJS in Streamlit�����������������������������������������������������������������������������29
1.4 Summary������������������������������������������������������������������������������������������������������30

Chapter 2: Streamlit Basics����������������������������������������������������������������31


2.1 Creating a Basic Application�������������������������������������������������������������������������31
2.1.1 Generating User Input Forms����������������������������������������������������������������32
2.1.2 Introducing Conditional Flow����������������������������������������������������������������34
2.1.3 Managing and Debugging Errors����������������������������������������������������������36
2.2 Mutating Dataframes������������������������������������������������������������������������������������40
2.2.1 Filter�����������������������������������������������������������������������������������������������������41
2.2.2 Select���������������������������������������������������������������������������������������������������42
2.2.3 Arrange�������������������������������������������������������������������������������������������������44
2.2.4 Mutate��������������������������������������������������������������������������������������������������46
2.2.5 Group By�����������������������������������������������������������������������������������������������48
2.2.6 Merge���������������������������������������������������������������������������������������������������49
2.3 Rendering Static and Interactive Charts�������������������������������������������������������52
2.3.1 Static Bar Chart������������������������������������������������������������������������������������52
2.3.2 Static Line Chart�����������������������������������������������������������������������������������53
2.3.3 Interactive Line Chart���������������������������������������������������������������������������55
2.3.4 Interactive Map�������������������������������������������������������������������������������������57
2.4 Developing the User Interface�����������������������������������������������������������������������58
2.5 Summary������������������������������������������������������������������������������������������������������62

vi
Table of Contents

Chapter 3: Architecting the User Interface�����������������������������������������63


3.1 Designing the Application�����������������������������������������������������������������������������64
3.1.1 Configuring the Page����������������������������������������������������������������������������64
3.1.2 Developing Themes and Color schemes�����������������������������������������������77
3.1.3 Organizing the Page�����������������������������������������������������������������������������81
3.2 Displaying Dynamic Content�������������������������������������������������������������������������85
3.2.1 Creating a Real-Time Progress Bar������������������������������������������������������87
3.3 Provisioning Multipage Applications�������������������������������������������������������������88
3.3.1 Creating Pages�������������������������������������������������������������������������������������88
3.3.2 Creating Subpages�������������������������������������������������������������������������������91
3.4 Modularizing Application Development���������������������������������������������������������94
3.4.1 Example: Developing a Social Network Application�����������������������������95
3.4.2 Best Practices for Folder Structuring�������������������������������������������������101
3.5 Summary����������������������������������������������������������������������������������������������������104

Chapter 4: Data Management and Visualization������������������������������105


4.1 Data Management���������������������������������������������������������������������������������������106
4.1.1 Processing Bytes Data������������������������������������������������������������������������106
4.1.2 Caching Big Data��������������������������������������������������������������������������������108
4.1.3 Mutating Data in Real Time����������������������������������������������������������������111
4.1.4 Advanced and Interactive Data Mutation��������������������������������������������113
4.2 Exploring Plotly Data Visualizations������������������������������������������������������������120
4.2.1 Rendering Plotly in Streamlit��������������������������������������������������������������120
4.2.2 Basic Charts���������������������������������������������������������������������������������������121
4.2.3 Statistical Charts��������������������������������������������������������������������������������125
4.2.4 Time-Series Charts�����������������������������������������������������������������������������127
4.2.5 Geospatial Charts�������������������������������������������������������������������������������128
4.2.6 Animated Visualizations����������������������������������������������������������������������128
4.3 Summary����������������������������������������������������������������������������������������������������131

vii
Table of Contents

Chapter 5: Database Integration�������������������������������������������������������133


5.1 Relational Databases����������������������������������������������������������������������������������133
5.1.1 Introduction to SQL�����������������������������������������������������������������������������134
5.1.2 Connecting a PostgreSQL Database to Streamlit�������������������������������136
5.1.3 Displaying Tables in Streamlit������������������������������������������������������������141
5.2 Nonrelational Databases�����������������������������������������������������������������������������144
5.2.1 Introduction to MongoDB��������������������������������������������������������������������145
5.2.2 Provisioning a Cloud Database�����������������������������������������������������������146
5.2.3 Full-Text Indexing�������������������������������������������������������������������������������150
5.2.4 Querying the Database�����������������������������������������������������������������������152
5.2.5 Displaying Tables in Streamlit������������������������������������������������������������157
5.3 Summary����������������������������������������������������������������������������������������������������160

Chapter 6: Leveraging Backend Servers������������������������������������������161


6.1 The Need for Backend Servers�������������������������������������������������������������������161
6.2 Frontend-Backend Communication������������������������������������������������������������162
6.2.1 HTTP Methods������������������������������������������������������������������������������������163
6.3 Working with JSON Files�����������������������������������������������������������������������������164
6.4 Provisioning a Backend Server�������������������������������������������������������������������165
6.4.1 API Building����������������������������������������������������������������������������������������166
6.4.2 API Testing������������������������������������������������������������������������������������������170
6.5 Multithreading and Multiprocessing Requests�������������������������������������������171
6.6 Connecting Streamlit to a Backend Server�������������������������������������������������174
6.7 Summary����������������������������������������������������������������������������������������������������177

viii
Table of Contents

Chapter 7: Implementing Session State�������������������������������������������179


7.1 Implementing Session State Natively���������������������������������������������������������179
7.1.1 Building an Application with Session State����������������������������������������182
7.2 Introducing Session IDs������������������������������������������������������������������������������185
7.3 Implementing Session State Persistently���������������������������������������������������186
7.4 User Insights�����������������������������������������������������������������������������������������������191
7.4.1 Visualizing User Insights���������������������������������������������������������������������195
7.5 Cookie Management�����������������������������������������������������������������������������������198
7.6 Summary����������������������������������������������������������������������������������������������������202

Chapter 8: Authentication and Application Security������������������������203


8.1 Developing User Accounts��������������������������������������������������������������������������203
8.1.1 Hashing����������������������������������������������������������������������������������������������204
8.1.2 Salting������������������������������������������������������������������������������������������������205
8.2 Verifying User Credentials���������������������������������������������������������������������������207
8.3 Secrets Management����������������������������������������������������������������������������������224
8.4 Anti-SQL Injection Measures with SQLAlchemy������������������������������������������225
8.5 Configuring Gitignore Variables�������������������������������������������������������������������226
8.6 Summary����������������������������������������������������������������������������������������������������227

Chapter 9: Deploying Locally and to the Cloud���������������������������������229


9.1 Exposing Streamlit to the World Wide Web�������������������������������������������������230
9.1.1 Port Forwarding over a Network Gateway������������������������������������������230
9.1.2 HTTP Tunneling Using NGROK�������������������������������������������������������������232
9.2 Deployment to Streamlit Cloud�������������������������������������������������������������������235
9.2.1 One-Click Deployment������������������������������������������������������������������������235
9.2.2 Streamlit Secrets��������������������������������������������������������������������������������238

ix
Table of Contents

9.3 Deployment to Linux�����������������������������������������������������������������������������������240


9.3.1 Native Deployment on a Linux Machine���������������������������������������������240
9.3.2 Deployment with Linux Docker Containers�����������������������������������������243
9.4 Deployment to Windows Server������������������������������������������������������������������246
9.4.1 Establishing a Remote Desktop Connection���������������������������������������247
9.4.2 Opening TCP/IP Ports��������������������������������������������������������������������������249
9.4.3 Anaconda Offline Package Installation�����������������������������������������������253
9.4.4 Adding Anaconda to System Path�������������������������������������������������������254
9.4.5 Running Application as an Executable Batch File�������������������������������256
9.4.6 Running Application As a Persistent Windows Service����������������������257
9.5 Summary����������������������������������������������������������������������������������������������������261

Chapter 10: Building Streamlit Components������������������������������������263


10.1 Introduction to Streamlit Custom Components�����������������������������������������263
10.2 Using ReactJS to Create Streamlit Custom Components��������������������������264
10.2.1 Making a ReactJS Component���������������������������������������������������������265
10.2.2 Using a ReactJS Component in Streamlit�����������������������������������������268
10.2.3 Sending Data to the Custom Component������������������������������������������270
10.2.4 Receiving Data from the Custom Component�����������������������������������273
10.3 Publishing Components As Pip Packages�������������������������������������������������276
10.4 Component in Focus: Extra-Streamlit-­Components����������������������������������280
10.4.1 Stepper Bar��������������������������������������������������������������������������������������280
10.4.2 Bouncing Image��������������������������������������������������������������������������������286
10.4.3 Tab Bar����������������������������������������������������������������������������������������������290
10.4.4 Cookie Manager�������������������������������������������������������������������������������295
10.4.5 Router�����������������������������������������������������������������������������������������������302
10.5 Summary��������������������������������������������������������������������������������������������������307

x
Table of Contents

Chapter 11: Streamlit Use Cases������������������������������������������������������309


11.1 Dashboards and Real-Time Applications��������������������������������������������������309
11.1.1 Temperature Data Recorder Application�������������������������������������������310
11.1.2 Motor Command and Control Application�����������������������������������������316
11.2 Time-Series Applications��������������������������������������������������������������������������321
11.2.1 Date-Time Filter Application�������������������������������������������������������������321
11.2.2 Time-Series Heatmap Application����������������������������������������������������324
11.2.3 Time Synchronization Application�����������������������������������������������������328
11.3 Data Management and Machine Learning Applications����������������������������332
11.3.1 Data Warehouse Application�������������������������������������������������������������332
11.3.2 Advanced Application Development: Machine Learning As a
Service����������������������������������������������������������������������������������������������344
11.4 Summary��������������������������������������������������������������������������������������������������361

Chapter 12: Streamlit at Work����������������������������������������������������������363


12.1 Streamlit in Clean Energy: Iberdrola���������������������������������������������������������363
12.1.1 Visualizing Operational Performance of Wind Farms������������������������365
12.1.2 Wind Turbine Power Curves��������������������������������������������������������������366
12.1.3 Wind Roses���������������������������������������������������������������������������������������369
12.1.4 Heat Maps����������������������������������������������������������������������������������������371
12.1.5 Closing Remarks������������������������������������������������������������������������������372
12.2 Streamlit in Industry: maxon Group����������������������������������������������������������373
12.2.1 Developing a Novel Surgical Scope Adapter System for Minimally
Invasive Laparoscopy�����������������������������������������������������������������������374
12.2.2 Streamlit Command and Control Dashboard������������������������������������377
12.2.3 Closing Remarks������������������������������������������������������������������������������378
12.3 Summary��������������������������������������������������������������������������������������������������379

xi
Table of Contents

Appendix A: Streamlit Application Program Interface���������������������381


A.1 The Streamlit API����������������������������������������������������������������������������������������381
A
 .1.1 Displaying Text�����������������������������������������������������������������������������������381
A
 .1.2 Displaying Data����������������������������������������������������������������������������������397
A
 .1.3 Displaying Charts�������������������������������������������������������������������������������402
A
 .1.4 Input Widgets�������������������������������������������������������������������������������������416
A
 .1.5 Displaying Interactive Widgets�����������������������������������������������������������443
A
 .1.6 Page Structure�����������������������������������������������������������������������������������447
A.1.7 Displaying Status and Progress���������������������������������������������������������451
A
 .1.8 Utilities�����������������������������������������������������������������������������������������������455
A.1.9 Session State Management���������������������������������������������������������������459
A
 .1.10 Data Management����������������������������������������������������������������������������461
A
 .1.11 The Hamburger Menu�����������������������������������������������������������������������467

Bibliography�������������������������������������������������������������������������������������469

Index�������������������������������������������������������������������������������������������������473

xii
About the Authors
Mohammad Khorasani is a hybrid of
an engineer and a computer scientist
with a Bachelor of Science in Mechanical
Engineering from Texas A&M University and a
master’s degree in Computer Science from the
University of Illinois at Urbana-Champaign.
Mohammad specializes in developing and
implementing software solutions for the
advancement of renewable energy systems and services at Iberdrola. In
addition, he develops robotic devices using embedded systems and rapid
prototyping technologies. He is also an avid blogger of STEM-related topics
on Towards Data Science – a Medium publication.
linkedin.com/in/mkhorasani/

Mohamed Abdou is a software engineer with


diverse academic and industrial exposure,
a graduate of Computer Engineering from
Qatar University, and currently an Software
Development Engineer at Amazon. Mohamed
has built a variety of open source tools used by
tens of thousands in the Streamlit community.
He led the first Google Developer Student Club
in Qatar and represented Qatar University in
national and international programming contests. He is a cyber security
enthusiast and was ranked second nationwide in bug bounty hunting in
Qatar in 2020 among under 25-year-­olds.
linkedin.com/in/mohamed-­ashraf-­abdou/

xiii
About the Authors

Javier Hernández Fernández specializes


in the area of technology innovation and
brings over 20 years of practical experience
in overseeing the design and delivery of
technological developments on behalf
of multinational companies in the fields
of IT, telecom, and utilities. He publishes
extensively, speaks at conferences around the
world, and spends his days wading through
piles of academic papers in the hope of finding something interesting.
He holds master’s degrees in both Energy Management and Project
Management, in addition to a BSc in Computer Science from the Faculty of
Engineering of the University of Ottawa.
linkedin.com/in/javier-­hernandezf/

xiv
About the Technical Reviewers
Rosario Moscato has a master’s degree in Electronic Engineering
(Federico II University, Naples) as well as a master’s degree in Internet
Software Design (CEFRIEL, Milan). He also has a Diploma in Apologetics
(Pontifical Athenaeum Regina Apostolorum, Rome) and a master’s
degree in Science and Faith (Pontifical Athenaeum Regina Apostolorum,
Rome). Rosario has gained over 20 years of experience, always
focusing his attention on the development and fine-tuning of the most
innovative technologies in various international companies in Europe
and Asia, covering various highly technical, commercial, and business
development roles.
In recent years, his interest has focused exclusively on artificial
intelligence and data science, pursuing, on one hand, the goal of
enhancing and making every business extremely competitive by
introducing and supporting machine and deep learning technologies
and on the other hand, analyzing the ethical-philosophical implications
deriving from the new scenarios that these disciplines open up.
Rosario has authored two books, and he is a speaker at international
research centers and conferences as well as a trainer and technical/
scientific consultant on the huge and changing world of AI.
Currently, he is working as Senior Data Scientist with one of the biggest
multinational IT companies in the world.

Randy Zwitch is a data science and analytics professional with broad


industry experience in big data and data science. He is also an open
source contributor in the R, Python, and Julia programming language
­communities.

xv
Acknowledgments
This undertaking would not have been possible without the support and
efforts of a selfless few. Individuals and entities who in one way or another
have made a contribution to the contents of this book are named as follows
in no particular order:
• Streamlit: The folks who created the framework itself,
empowering countless developers
• Iberdrola: Which provided the inspiration and time for
us to put Streamlit to a very noble use
• Iberdrola Innovation Middle East: The folks who served
as a test bed for our very first Streamlit ventures and
had to put up with our constant pitching of Streamlit’s
formidability
• Qatar Science & Technology Park: Which has fostered
an environment conducive to innovation and research
• Daniel Paredes, Jerome Dumont, Ana Martos, and
Gustavo López-Luzzatti: For being our very first
Streamlit users
• Dr. Nikhil Navkar: For being another trailblazing
Streamlit user

In addition, a tangible part of our careers and personal endeavors


would have simply been inconceivable without the spirit of the open
source community. It is therefore in order to give a special tribute to
Python and its respective developers, in addition to the multitude of other
online forums who are silent heroes. Without their efforts, all-nighters
would be every other night and our works not nearly as neat as they are.
xvii
Preface
It was an inconspicuous night like any other. I was about to doze off, but
right before that happened, my phone buzzed, and being a millennial,
I just could not resist the temptation to check. However, much to my
disdain, it was just another pesky email advertisement recommending an
online course in something called “Streamlit.” I am a strong disbeliever in
email lists, and, honestly, I would have investigated no further had it not
been for the aesthetically pleasing Streamlit logo. In retrospect, I am glad I
clicked on the ad. Since then, my programming life has one way or another
been intertwined with a framework that I had been yearning for someone
to create for years – the formidable Streamlit.
I noticed early on in my career that there is a plethora of seasoned
Python developers that are adept with backend and server-side
programming but cannot develop frontend user interfaces and client-­
side software to save their lives, myself included. While there were noble
efforts made by the teams in Flask and Django, both frameworks solicit
an abundance of exposure and technical know-how of HTML, CSS, and
HTTP, which effectively rendered them as no-fly zones. I found myself
making do with the likes of Tkinter and PyQt, thereby limiting myself to
local desktop software with no means of deploying my work to the cloud.
This is the predicament that I and a multitude of other programmers faced.
What all of us Python loyalists needed was a pure Python web framework
with an intuitive API that enabled the prompt creation and deployment of
web applications while allowing the developer to focus on the backend.
Similar perhaps to what ReactJS is to JavaScript. And when I clicked on
that pesky ad mentioned earlier, that is exactly what I found. It was a sort of
eureka moment!

xix
Preface

Mind you, this anecdote of mine occurred in the summer of 2020, and
Streamlit had only been released to the public in the fall of 2019. But less
than a year of development by their team had rendered exactly the sort of
framework and API that I had hoped for. And ever since then, this product has
only been moving in one direction – upward, with a steep incline. For myself
personally, I could not have discovered it at a more auspicious time. I had just
been hired by Iberdrola and tasked with the audacious goal of creating and
deploying a Python-based application to the Web. In a pre-Streamlit world, I
would have fervently resisted the notion of deploying applications to the Web,
but armed with my new friend, I found myself routinely advocating for the
development of web applications while passionately brandishing Streamlit’s
untethering capabilities. Overnight, I had been transformed into a trailblazing
member of sorts within our development team.
With all good things in the world, it just does not feel right to proceed
without sharing the goodness with the world at large. Consequently, I
have made it a subtle goal in life to inform the online and offline software
development community of the empowerment that Streamlit ushers in. This
book is the culmination of that effort, and more specifically it is intended
for those who have faced the same hurdles as I have, and it will provide a
holistic overview of Streamlit. This book will guide the reader through the life
cycle of creating scalable web applications of their own, from the most basic
use cases to crafting complex and distributed applications on the cloud.
In addition to learning all the ins and outs of Streamlit itself, after
perusing this book, readers should be able to interface their web
applications with robust server-side infrastructure like MongoDB,
PostgreSQL, Linux, Windows Server, and Streamlit’s own deployment
platform. In a nutshell, you should be able to walk away from this book
feeling empowered enough to unleash your ideas and to embody them on
the Internet. Perhaps this could be the beginning of your next startup for
the curious inner entrepreneur in you.

Mohammad Khorasani
September 2021

xx
Acronyms
aaS As a service
API Application programming interface
BLOB Binary large object
CLI Command-line interface
CPU Central processing unit
CRUD Create, read, update, and delete
CSP Cloud service provider
CSRF Cross-site request forgery
CSS Cascading Style Sheet
DI Dependency injection, a coding pattern
DG Delta Generator, a core module in Streamlit
DOM Document Object Model
DTW Dynamic time warping
GPU Graphics processing unit
HTML Hypertext Markup Language
IDE Integrated development environment
ISP Internet service provider
JSON JavaScript Object Notation
JWT JSON Web Token
MLaaS Machine learning as a service
NAT Network address translation
ORM Object-relational model
OS Operating system
PID Process identifier
RCE Remote Code Execution
RDP Remote Desktop Protocol

xxi
Acronyms

REST Representational state transfer


SaaS Software as a service
SCADA Supervisory Control and Data Acquisition
SQL Structured query language
SQLI SQL injection
SSH Secure Shell
TPU Tensor processing unit
UI User interface
URI Uniform Resource Identifier
URL Uniform Resource Locator
UX User experience
VPN Virtual private network
XSS Cross-site scripting

xxii
Intended Audience
This book assumes that you have no less than a basic level of exposure and
understanding in the following areas:

• Object-oriented programming

• Data structures and algorithms

• Python and the following bindings:

–– Pandas

–– Numpy

–– Plotly

• SQL (both relational and nonrelational databases)

• Git version control frameworks

• Cloud computing

In order to materialize on the concepts divulged in this book, it is


imperative that you possess sufficient experience in programming. If you
have little to no prior experience in the areas mentioned previously, then
you should consider first enrolling in an online crash course of your choice
that would offer at the least an introductory level of exposure. Other than
that, by no means must you be an expert of any sort in the aforementioned
concepts, although experts also stand to gain from the contents of this
book. Even if you have the ability to develop applications with a more
sophisticated stack, you may still appreciate the amount of time and
energy that is saved by utilizing Streamlit. With Streamlit, you can render

xxiii
Intended Audience

a robust web application in hours what would have previously taken you
weeks to produce in Flask or Django. In simpler terms, it offers a lot more
bang for the buck.
Notwithstanding, it is important to clarify that for those who are
looking for a means to deliver highly bespoke and tailored frontend user
interfaces, perhaps Streamlit is not what you should be scouting for. Not
that it will not address your needs someday, it is just that “someday” is
not today. Streamlit is a work in progress, and while their team perseveres
relentlessly, we should remain patient and expect a greater degree of
customizability alongside a multitude of additional features to be released
in the near future. Should you need something more amenable, then you
may find that Django is a more suitable option. Mind you, Django lands
you back in the realm of the predicament mentioned earlier, as you will
need to be a more advanced programmer to create web applications
with it.
Hopefully upon completion of this book, you should be equipped
with the tools that you will need to produce a scalable web application
deployed to the cloud from inception to deployment and operation. You
will become confident in addressing the functional and performance
requirements of developing both server-side and client-side software.
You will be able to create both backend functionality and frontend user
interfaces. In addition, you will learn to interface your software with
relational and nonrelational database systems such as PostgreSQL and
MongoDB in order to scale your application on demand. And finally, you
will acquire the technical know-how to orchestrate and provision your
scalable application on the cloud using Microsoft Server, Linux containers,
and Streamlit’s own cloud service.
While this book will go into great depth and breadth of the required
concepts, a degree of self-learning and research is still expected of any
reader. There will be gaps in tutorials, and perhaps some of the tools
used will be deprecated or obsolete by the time you are reading this

xxiv
Intended Audience

book; therefore, a great deal of intuition and sound judgment is solicited.


Furthermore, this book will not attempt to provide any explanation for the
source code used by Streamlit or any other binding/API. Our scope will
be solely limited to the application of the objects, classes, and functions
included in each of the tools used. Each tutorial included will address a
separate use case or application with the corresponding code provided.
All original source codes published in this book are released under the
MIT License and are open source. It is anticipated that you will utilize the
whole or part of the methodology of the provided book to fulfill your own
technical requirements.

xxv
Additional Material
This book is accompanied with an abundance of online material
including repositories, datasets, libraries, APIs, and their corresponding
documentation. Wherever necessary and possible, the URL to the material
will be provided. All tutorials and source code included in this book will be
available at the following repository: https://github.com/. Finally, any
reference made to the Streamlit API can be additionally found on
­https://docs.streamlit.io/library/api-­reference.

xxvii
CHAPTER 1

Getting Started
with Streamlit
With the inundation of data, and the pace at which it is created, traditional
computing methods possess limited means to deliver results. On the other
hand, cloud computing acts as an enabler, allowing one to overcome the
limitations of the former. With increased scalability, reduced costs, and
enhanced adaptability, cloud service providers, developers, and users alike
stand to gain from the fruits of migrating to the cloud.
Given that Python is currently the scripting language of choice for most
of the software development community, it is absolutely vital to provide
a web framework for developers that would bridge their skills gap. While
legacy frameworks such as Flask and Django solicit a firm understanding
of HTML and CSS, Streamlit is the first major framework that is all pure
Python, thereby reducing development time from weeks to hours.

1.1 Why Streamlit?


Limiting oneself to local computing options is simply a figment of the
distant past, given that the cloud unlocks a host of advantages and allows
developers to leave a tangibly greater impact on the world. It is for this
very reason that an entire new echelon of developers are beginning to
embrace everything cloud, and the rapid transition toward this new

© Mohammad Khorasani, Mohamed Abdou, Javier Hernández Fernández 2022 1


M. Khorasani et al., Web Application Development with Streamlit,
https://doi.org/10.1007/978-1-4842-8111-6_1
Chapter 1 Getting Started with Streamlit

paradigm of computing is a testament to that fact. And this is exactly where


a pure Python web framework such as Streamlit can deliver a lot of value
to developers who want to make the transition but who need an enabler
to do so.

1.1.1 Local vs. the Cloud


The cloud is rapidly becoming synonymous with data itself. Quite literally,
wherever there is an abundance of data, it is somehow intertwined with
cloud computing. Put into layman’s terms, it is simply inconceivable to
harness the value of big data without utilizing the resources of the cloud.
Gone are the days where one would brandish Microsoft Excel to create a
1990s style dashboard for their dataset. With the sheer magnitude of data
exposed to us, local computing will not make the cut.
Even still, there are certain tangible benefits to local computing,
namely, prototyping an idea is considerably faster, and latency between
nodes and servers is several orders of magnitude smaller. This is why
edge computing still holds an “edge” over the cloud, no pun intended.
In addition, there are applications for which security is sacrosanct and/
or regulations are inhibiting, and in that case, one may be better off
disconnecting themselves from the world at large. Other than that, there
is not much else that one can attribute to the list of benefits of local
computing. However, there is a plethora of reasons why you should steer
clear of it. To name a few, the bottom line will be quite lower with the
overheads solicited to run the infrastructure at hand. There will also be
very limited adaptability to fluctuating traffic; imagine the half-time surge
in traffic during the Super Bowl, you simply will not be able to scale to
meet demand.
On the other hand, cloud computing is cheaper to provision,
exceedingly adaptable to demand, highly robust against failure, and
supremely reliable to run. In addition, cloud computing platforms enable
scalability in two dimensions – horizontal and vertical. Horizontal for

2
Chapter 1 Getting Started with Streamlit

when you need multiple instances of the same computing resources and
vertical for when you need bespoke resources, the likes of GPUs, TPUs,
database systems, and more. Perhaps, the single most salient factor about
the cloud is that it expands your horizons and allows you to offer your
product as a service on the World Wide Web. The latest paradigm shift in
tech is to offer quite literally anything as a service. The as-a-service model
(aaS) can be applied to software (SaaS), machine learning (MLaaS), and
any other product that can be offered as a web application on the Internet.
And this is precisely where a web framework such as Streamlit fits the bill.
Streamlit is a cloud enabler for those of us in the software development
community that have been unable to deploy our value to the Internet due
to a hefty skills gap that has thus far impeded us from doing so. Concisely
put, Streamlit is a means of empowerment for developers at all levels.

1.1.2 A Trend Toward Cloud Computing


Cloud computing is north, south, east, and west. Academia, the corporate
world, governments, and even spy agencies are shifting from local
to the cloud at a breathtaking pace. With legacy software providing
limited means for growth and return on investments, organizations are
increasingly migrating to cloud service providers who in turn offer agility,
economies-of-scale, and advanced computing resources. Even CSPs
themselves are jumping on the bandwagon, with the likes of Google and
Microsoft offering their legacy applications on the cloud with Google G
Suite and Microsoft Office 365.
Evidently, from a business perspective, the justification is even more
so robust. Disruptive businesses are as pervasive as they have ever been
and have wholly championed what others had so far been reluctant to
accept. Therefore, embracing the cloud is no longer a subjective decision
but rather a means for survival. With reduced lead time, scalability, limited
capital investments, and increased innovation, businesses stand to gain
a great deal. From a CSP perspective, this proposition is possibly even

3
Chapter 1 Getting Started with Streamlit

more enticing. Equipped with the cloud, CSPs are able to pool resources
together, increase resource elasticity, and reduce maintenance and
overheads. And perhaps most importantly, from a consumer’s point of
view, the cloud is the best thing that ever happened since the Internet
itself. As a consumer, the SaaS model offers unparalleled flexibility, price
granularity, and plenty more bang for the buck. In other words, the cloud is
win-win-win; everyone stands to gain.
While the trend toward cloud computing was already on a healthy
trajectory, a once-in-a-century pandemic doubled as a booster toward
everything cloud. The pandemic all but destroyed the stigma associated
with remote learning, online examinations, working from home, and
other dogma that decades of noble efforts by the tech community had
failed to make a dent into. It is fair to assume that from here onward, the
progression toward everything cloud will exceed the prediction of pundits.
And if numbers alone can serve to indicate where we are heading, then
one should feast themselves on the omen of Figure 1-1.

Figure 1-1. Growth of the public cloud computing market from 2008
to 2020. Source: statista.com [13]

4
Chapter 1 Getting Started with Streamlit

1.1.3 History of Web Frameworks in Python


Web development can be quite an arduous task, soliciting a
multidisciplinary team with expertise in frontend, backend, and server-­side
software development. It is for this very reason that full-stack developers
who brandish the know-how for the entire development process are in
surplus demand and are often in receipt of a handsome compensation.
Traditionally, these developers would resort to using JavaScript, PHP,
or Perl to develop web applications, with Python being sidelined as a local
scripting language. This was due to the fact that Python is not inherently
designed to run on the Internet and requires a web framework to interface
with web servers and browsers. Over the years however, the community
has developed several novel frameworks that allow Python to be utilized
effectively for the Internet. And given Python’s emphasis on simplicity,
readability, rich ecosystem of libraries, and being open source, it has
steadily transformed into one of the main web scripting languages of
choice for many developers. Python has even gained enough traction to
being adopted by heavyweights, the likes of Google and Instagram.
Generally, such web frameworks come in two types, full-stack
and nonfull-stack. They manage everything from communications
and infrastructure to other lower-level abstractions required by web
applications. Nontrivial applications require a slew of functionalities
including but not limited to interpreting requests, producing responses,
storing data, and rendering user interfaces. For such applications, one
would often utilize a full-stack framework that provides an in-house
solution for all the technical requirements. This contrasts with nonfull-­
stack frameworks otherwise known as microframeworks that provide a
bare minimum level of functionality, typically limited to routing HTTP
requests to the relevant controllers, dispatching the controller, and
subsequently returning a response. Such frameworks are usually stacked
with other APIs and tools in order to create applications. Some of the most
popular examples of each type are listed in the following sections.

5
Chapter 1 Getting Started with Streamlit

1.1.4 Flask
Flask was developed in 2010 by Armin Ronacher from what was
allegedly an April fool’s joke to begin with. Flask is a nonfull-stack or
microframework that provisions an application server without offering
much else in terms of components. Flask is composed of two main
elements: Werkzeug, a tool that lends support for HTTP routing, and Jinja,
a template engine used to render basic HTML pages. In addition, Flask
uses MarkupSafe as a string handling library and ItsDangerous as a secure
data serialization library to store session data as cookies.
Flask is a minimalistic framework that is equipped with the bare
minimum of the components required to render a web application.
Consequently, the developer is afforded a great deal of autonomy and
also responsibility to create their own application. As a result, Flask is best
suited for static websites and for experienced developers who are able to
provision most of their own infrastructure and render their own interfaces.

1.1.5 Django
Django was developed by a group of web programmers in 2003 who
used Python to build web applications. It allows developers to create
complex applications with relatively less overhead in comparison to Flask.
Specifically, Django enables programmers to render dynamic content
with enhanced scalability and with in-house capabilities to interface with
database systems using object-relational mapping.
In addition, there are a host of other modules including but not limited
to ecommerce, authentication, and caching packages that allow the
developer to readily provision extended services. Bundled with a multitude
of other third-party packages, Django allows the developer to focus mainly
on the idea while not having to worry much about the implementation.

6
Chapter 1 Getting Started with Streamlit

1.1.6 Dash
Dash is a web framework developed by Plotly to render enterprise-­
grade web applications in Python, R, and even Julia. Given that Plotly
predominantly develops data analytics and visualization tools, similarly
Dash is more often used to create dashboards. Even still, it is indeed
possible to create a host of general-purpose applications with due to its
extended customizability.
Dash has the ability to natively support D3.js charts and provides
default HTML and CSS templates to use. However, for more tailored
interfaces, developers must be well versed with frontend programming
themselves. Furthermore, Dash tenders an enterprise package that
enables experienced developers to deploy their applications on the cloud
with production-grade capabilities such as authentication and database
systems.

1.1.7 Web2Py
Web2Py is a full-stack web framework for Python which like Django
makes use of the model view controller architectural paradigm. It allows
developers to create primitive yet dynamic content with relative ease and
interfaces natively with database systems. The novelty of this framework
as opposed to others is that it comes with its own web-based integrated
development environment equipped with a ticketing system for error
tracking and management.
The main disadvantage however is that Web2Py executes objects
and controllers via a single global environment that is initiated at each
HTTP request. While this has its benefits, it does also carry the pitfalls of
experiencing compromised performance and incompatibility issues with
certain modules.

7
Chapter 1 Getting Started with Streamlit

1.1.8 The Need for a Pure Python


Web Framework
Previously, the community of Python developers would have to suffice
with deploying their software locally as desktop applications unless they
commanded adept knowledge of HTML, CSS, and JavaScript. With Tkinter and
PyQt, programmers can indeed produce complex, dynamic, and aesthetically
pleasing interfaces, albeit with the heartbreak of not being able to render it on
the Web. And this has largely been the predicament of many Python loyalists,
who, up until recently, had no pure Pythonic way of migrating to the cloud.
It was always quite demeaning to peruse through repository after
repository of awesome applications developed by people who had no other
way of exposing their goodness to the world than sharing the source code with
others hoping that they would be able to replicate it locally. Oh, and forget
about the nontechnical users who had no hope whatsoever of executing
even as much as that. Countless noble efforts were left largely unutilized in
vain as a result. In other words, the community was in desperate need of a
major framework that would solicit no additional expertise other than the
knowledge of writing your average Python script and being able to deploy it
instantly to a cloud server. Then came along Streamlit and freed developers
from the shackles of HTML, CSS, and JavaScript. The rest will be history.

1.1.9 Academic Significance
Being able to create web apps directly from Python easily has made
Streamlit a valuable tool for academia [1]. Despite its recent creation,
the first beta release is dated April 2019; research teams worldwide
have started adopting the framework to showcase the outcomes of their
projects. Today, many publications already mention Streamlit as their
visualization framework covering a wide range of fields. Some of these
areas include health [2, 3, 4, 5], computer science [6, 7, 8, 9], economics
[11, 10], and civil engineering [12], to mention a few.

8
Chapter 1 Getting Started with Streamlit

1.2 Firing It Up
Being the highly versatile and accommodating framework that it is,
Streamlit allows the developer to utilize it with a variety of computing
resources and technical stack. Even still, there are some recommended
best practices to follow for greater ease and usability.

1.2.1 Technical Requirements
While there is no one-size-fits-all solution when it comes to running
Streamlit, the following computing and system requirements or greater are
recommended for developing and running applications smoothly.

Table 1-1. Hardware requirements


CPU RAM Storage Internet/Network access

2 x 64-bit 2.8 GHz 4 GB 1600 MHz DDR3 120 GB 1 Mbps

Table 1-2. System requirements


Operating System Database

Ubuntu 16.04 to 17.10 PostgreSQL 9.6 or higher


Windows 7 to 11 pgAdmin v4.0 or higher
Mac OS X 10.11 or higher
Linux: RHEL 6/7

Table 1-3. Software requirements


Streamlit Anaconda

1.9 or higher With Python 3.8 or higher

9
Chapter 1 Getting Started with Streamlit

Table 1-4. Network requirements


Inbound Ports Outbound Ports

HTTP: TCP 8080, 8443 HTTPS: TCP 443


SSH: TCP 22 SMTP: TCP 25
LDAP(s): TCP 389/636

1.2.2 Environment Installation with Anaconda


In order to create a web application run on a local Streamlit server for
prototyping and testing, we first need to install and create a Python
runtime environment with all the dependencies required for our server. In
this regard, we will be making use of Anaconda which is one of the most
widely used and supported Python distributions available. First, proceed
with downloading and installing a compatible version of Anaconda. Once
the installation has been successfully completed, you may then create a
virtual environment that will be used to download and install the packages
necessary to run your web application.

Programmatic Installation
To create an Anaconda environment through the console, please follow
these steps:

1. To create and install your environment


programmatically, enter the following commands in
Anaconda Prompt sequentially:

conda create -n <environment name>


python=<version number>

When conda asks you to proceed, select y.

proceed ([y]/n)?

10
Chapter 1 Getting Started with Streamlit

Subsequently, the new environment will be created


in the environments folder within the root directory
of Anaconda as C:/ProgramData/Anaconda3/envs/.

2. Activate your environment by typing the following:

conda activate <environment name>

3. If you have a list of dependencies, dependencies.


yml, place it in your newly created environment’s
directory: C:/ProgramData/Anaconda3/envs/
environment name/

4. Change your root directory to your environment’s


directory by typing the following:

cd C:/ProgramData/Anaconda3/envs/<environment name>/

5. Ensure that the first line in the dependencies.yml is


written correctly as the name of your environment,
name: environment name; otherwise, the
environment may not be installed.

6. Update your environment by installing all the


dependencies listed in the file dependencies.yml by
typing the following:

conda env update -f dependencies.yml

7. If prompted by Anaconda, proceed with updating


your version of conda by typing the following:

conda update -n base -c defaults conda

8. To check the list of environments, type the following:

conda info -envs

11
Chapter 1 Getting Started with Streamlit

9. To check the list of dependencies in your


environment, type the following:

conda list

10. To install additional dependencies that may be


required later, please type the following:

conda install <dependency name>

11. Some dependencies may not be available for


download via conda install; in this case, download
pip and subsequently use pip install as shown in the
following:

conda install pip


pip install <dependency name>

12. To deactivate your environment, you may type the


following:

conda deactivate

Graphical Installation
Alternatively, you may use Anaconda Navigator to create and maintain
your environments as follows:

1. Launch Anaconda Navigator.

2. Click the Environments tab.

12
Chapter 1 Getting Started with Streamlit

Figure 1-2. Opening the Environments tab in Anaconda

3. Click the Create button and enter the desired name


and Python version for your environment.

Figure 1-3. Creating an environment in Anaconda

13
Chapter 1 Getting Started with Streamlit

4. Next, follow steps 2–12 in the previous section to


install the dependencies. Subsequently, as shown
in Figure 1-4, the test_environment environment
will appear activated with all the required packages
installed.

Figure 1-4. Newly created environment in Anaconda

5. Finally, you will be able to launch any of the


available code editors in Anaconda within your
newly created environment in the Home tab.

14
Chapter 1 Getting Started with Streamlit

Figure 1-5. Selection of code editors in Anaconda

1.2.3 Downloading and Installing Streamlit


There are multiple ways to download and install the Streamlit library for
use, and in this section, we will cover one of the most commonly used
types of installation.

Direct pip Installation


1. To download and install Streamlit, first ensure that
you are in the correct environment by entering the
following command in Anaconda Prompt:

conda activate <environment name>

2. Subsequently, you may download and install


Streamlit by entering the following command:

pip install streamlit

15
Chapter 1 Getting Started with Streamlit

Manual Wheel File Installation


1. Ensure that you are in the correct environment
by entering the following command in
Anaconda Prompt:

conda activate <environment name>

2. Manually download the wheel installation file from

https://pypi.org/project/streamlit/

3. Change the directory to where the wheel file is


located:

cd C:/Users/.../

4. Subsequently install the downloaded wheel file by


entering the following command:

pip install streamlit-1.0.0-py2.py3-none-any.whl

If the installation has been successful, you may proceed with creating
your script. For good measure, restart Anaconda before you do so.

Importing Streamlit
To import Streamlit into your Python script, ensure that the following line
precedes the rest of your code:

import streamlit as st

Subsequently, any Streamlit method can be invoked by appending st


to it as follows:

st.write('Hello world')

16
Chapter 1 Getting Started with Streamlit

1.2.4 Streamlit Console Commands


When Streamlit is installed, the Streamlit command-line (CLI) tool is also
installed. The command line can help you run, operate, and diagnose
issues related to your Streamlit application.
To get additional help, enter the following command:

streamlit --help

To run your application, ensure that you have changed the directory to
where your script is located:

cd C:/Users/.../script directory/

Then enter the following to run your script:

streamlit run <script.py> [--script args]

Subsequently, your application’s local URL and network URL will be


displayed. Simultaneously, your application will automatically appear on
your default web browser. You may use the local URL to connect to your
application locally and the network URL to connect on any other device
over the local area network.

17
Chapter 1 Getting Started with Streamlit

Figure 1-6. Console while running the Streamlit application

To clear the cache, enter the following command:

streamlit cache clear

To open Streamlit’s documentation on a web browser, enter the


following command:

streamlit docs

To display Streamlit’s version, enter the following command:

streamlit --version

Configuring Streamlit Through the Console


You may pass config options to streamlit run to configure options such as
the port the application is being run on, disable run-on-save, and others.
For an exhaustive list of configuration options, enter the following
command:

streamlit run --help

18
Chapter 1 Getting Started with Streamlit

You can view the list of configured options by entering the following
command:

streamlit config show

You may configure these options using one of the four following
methods:

1. Using a global config file at .streamlit/config.toml:

[server]
port = 80

2. Using a config file for each project in your project’s


directory: C:/Users/.../.streamlit/config.toml.

3. Using STREAMLIT_* environment variables as


shown in the following:

export STREAMLIT_SERVER_PORT=80

4. Using flags in the command line when running your


script as shown in the following:

streamlit run <script.py> --server.port 80

1.2.5 Running Demo Apps


To run Streamlit’s demo applications, enter the following command:

streamlit hello

Subsequently, the following application will be displayed on your


default web browser. You may use the menu on the sidebar to visit the four
following demo applications.

19
Chapter 1 Getting Started with Streamlit

Figure 1-7. Streamlit demo application home page

Figure 1-8. Streamlit animation demo application

20
Chapter 1 Getting Started with Streamlit

1.2.6 Writing and Testing Code with PyCharm


Generally speaking, code expands over time, whether by making new
modules in the original code base or integrating it with third-party services.
As a step toward making sure the code performs flawlessly, testing can be
utilized. Code testing can be broken down to two methods: unit testing and
integration testing, where both can be used to test independent modules
and the whole system end to end, respectively. For the sake of this example,
we will cover unit tests, but the same concept can be applied to the other
option. Either way, we need to give inputs and compare expected outputs
against actual ones. For a simple Streamlit application which enables the
user to calculate the sum of any two numbers, we can test two main parts,
one being if the web application is rendered according to our expectations
and the other to verify the summation logic is correct. These are two different
unit tests to do, but the first is a common thing to do when developing any
frontend work. Listing 1-1 is the sample application we are trying to test in
this example with output of Figure 1-12 when ran with Streamlit. Listing 1-2
tests both rendering and summation logic of the mentioned example.

Figure 1-9. Streamlit plotting demo application

21
Discovering Diverse Content Through
Random Scribd Documents
*** END OF THE PROJECT GUTENBERG EBOOK LOCOMOTIVE
ENGINE RUNNING AND MANAGEMENT ***

Updated editions will replace the previous one—the old editions


will be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States
copyright in these works, so the Foundation (and you!) can copy
and distribute it in the United States without permission and
without paying copyright royalties. Special rules, set forth in the
General Terms of Use part of this license, apply to copying and
distributing Project Gutenberg™ electronic works to protect the
PROJECT GUTENBERG™ concept and trademark. Project
Gutenberg is a registered trademark, and may not be used if
you charge for an eBook, except by following the terms of the
trademark license, including paying royalties for use of the
Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such
as creation of derivative works, reports, performances and
research. Project Gutenberg eBooks may be modified and
printed and given away—you may do practically ANYTHING in
the United States with eBooks not protected by U.S. copyright
law. Redistribution is subject to the trademark license, especially
commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the


free distribution of electronic works, by using or distributing this
work (or any other work associated in any way with the phrase
“Project Gutenberg”), you agree to comply with all the terms of
the Full Project Gutenberg™ License available with this file or
online at www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand,
agree to and accept all the terms of this license and intellectual
property (trademark/copyright) agreement. If you do not agree
to abide by all the terms of this agreement, you must cease
using and return or destroy all copies of Project Gutenberg™
electronic works in your possession. If you paid a fee for
obtaining a copy of or access to a Project Gutenberg™
electronic work and you do not agree to be bound by the terms
of this agreement, you may obtain a refund from the person or
entity to whom you paid the fee as set forth in paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only


be used on or associated in any way with an electronic work by
people who agree to be bound by the terms of this agreement.
There are a few things that you can do with most Project
Gutenberg™ electronic works even without complying with the
full terms of this agreement. See paragraph 1.C below. There
are a lot of things you can do with Project Gutenberg™
electronic works if you follow the terms of this agreement and
help preserve free future access to Project Gutenberg™
electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright
law in the United States and you are located in the United
States, we do not claim a right to prevent you from copying,
distributing, performing, displaying or creating derivative works
based on the work as long as all references to Project
Gutenberg are removed. Of course, we hope that you will
support the Project Gutenberg™ mission of promoting free
access to electronic works by freely sharing Project Gutenberg™
works in compliance with the terms of this agreement for
keeping the Project Gutenberg™ name associated with the
work. You can easily comply with the terms of this agreement
by keeping this work in the same format with its attached full
Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside
the United States, check the laws of your country in addition to
the terms of this agreement before downloading, copying,
displaying, performing, distributing or creating derivative works
based on this work or any other Project Gutenberg™ work. The
Foundation makes no representations concerning the copyright
status of any work in any country other than the United States.

1.E. Unless you have removed all references to Project


Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project
Gutenberg™ work (any work on which the phrase “Project
Gutenberg” appears, or with which the phrase “Project
Gutenberg” is associated) is accessed, displayed, performed,
viewed, copied or distributed:

This eBook is for the use of anyone anywhere in the United


States and most other parts of the world at no cost and
with almost no restrictions whatsoever. You may copy it,
give it away or re-use it under the terms of the Project
Gutenberg License included with this eBook or online at
www.gutenberg.org. If you are not located in the United
States, you will have to check the laws of the country
where you are located before using this eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is


derived from texts not protected by U.S. copyright law (does not
contain a notice indicating that it is posted with permission of
the copyright holder), the work can be copied and distributed to
anyone in the United States without paying any fees or charges.
If you are redistributing or providing access to a work with the
phrase “Project Gutenberg” associated with or appearing on the
work, you must comply either with the requirements of
paragraphs 1.E.1 through 1.E.7 or obtain permission for the use
of the work and the Project Gutenberg™ trademark as set forth
in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is


posted with the permission of the copyright holder, your use and
distribution must comply with both paragraphs 1.E.1 through
1.E.7 and any additional terms imposed by the copyright holder.
Additional terms will be linked to the Project Gutenberg™
License for all works posted with the permission of the copyright
holder found at the beginning of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files
containing a part of this work or any other work associated with
Project Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute


this electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the
Project Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if
you provide access to or distribute copies of a Project
Gutenberg™ work in a format other than “Plain Vanilla ASCII” or
other format used in the official version posted on the official
Project Gutenberg™ website (www.gutenberg.org), you must,
at no additional cost, fee or expense to the user, provide a copy,
a means of exporting a copy, or a means of obtaining a copy
upon request, of the work in its original “Plain Vanilla ASCII” or
other form. Any alternate format must include the full Project
Gutenberg™ License as specified in paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™
works unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or


providing access to or distributing Project Gutenberg™
electronic works provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project


Gutenberg™ electronic work or group of works on different
terms than are set forth in this agreement, you must obtain
permission in writing from the Project Gutenberg Literary
Archive Foundation, the manager of the Project Gutenberg™
trademark. Contact the Foundation as set forth in Section 3
below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on,
transcribe and proofread works not protected by U.S. copyright
law in creating the Project Gutenberg™ collection. Despite these
efforts, Project Gutenberg™ electronic works, and the medium
on which they may be stored, may contain “Defects,” such as,
but not limited to, incomplete, inaccurate or corrupt data,
transcription errors, a copyright or other intellectual property
infringement, a defective or damaged disk or other medium, a
computer virus, or computer codes that damage or cannot be
read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except


for the “Right of Replacement or Refund” described in
paragraph 1.F.3, the Project Gutenberg Literary Archive
Foundation, the owner of the Project Gutenberg™ trademark,
and any other party distributing a Project Gutenberg™ electronic
work under this agreement, disclaim all liability to you for
damages, costs and expenses, including legal fees. YOU AGREE
THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT
LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT
EXCEPT THOSE PROVIDED IN PARAGRAPH 1.F.3. YOU AGREE
THAT THE FOUNDATION, THE TRADEMARK OWNER, AND ANY
DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE LIABLE
TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL,
PUNITIVE OR INCIDENTAL DAMAGES EVEN IF YOU GIVE
NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of
receiving it, you can receive a refund of the money (if any) you
paid for it by sending a written explanation to the person you
received the work from. If you received the work on a physical
medium, you must return the medium with your written
explanation. The person or entity that provided you with the
defective work may elect to provide a replacement copy in lieu
of a refund. If you received the work electronically, the person
or entity providing it to you may choose to give you a second
opportunity to receive the work electronically in lieu of a refund.
If the second copy is also defective, you may demand a refund
in writing without further opportunities to fix the problem.

1.F.4. Except for the limited right of replacement or refund set


forth in paragraph 1.F.3, this work is provided to you ‘AS-IS’,
WITH NO OTHER WARRANTIES OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of
damages. If any disclaimer or limitation set forth in this
agreement violates the law of the state applicable to this
agreement, the agreement shall be interpreted to make the
maximum disclaimer or limitation permitted by the applicable
state law. The invalidity or unenforceability of any provision of
this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the


Foundation, the trademark owner, any agent or employee of the
Foundation, anyone providing copies of Project Gutenberg™
electronic works in accordance with this agreement, and any
volunteers associated with the production, promotion and
distribution of Project Gutenberg™ electronic works, harmless
from all liability, costs and expenses, including legal fees, that
arise directly or indirectly from any of the following which you
do or cause to occur: (a) distribution of this or any Project
Gutenberg™ work, (b) alteration, modification, or additions or
deletions to any Project Gutenberg™ work, and (c) any Defect
you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new
computers. It exists because of the efforts of hundreds of
volunteers and donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project
Gutenberg™’s goals and ensuring that the Project Gutenberg™
collection will remain freely available for generations to come. In
2001, the Project Gutenberg Literary Archive Foundation was
created to provide a secure and permanent future for Project
Gutenberg™ and future generations. To learn more about the
Project Gutenberg Literary Archive Foundation and how your
efforts and donations can help, see Sections 3 and 4 and the
Foundation information page at www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-
profit 501(c)(3) educational corporation organized under the
laws of the state of Mississippi and granted tax exempt status
by the Internal Revenue Service. The Foundation’s EIN or
federal tax identification number is 64-6221541. Contributions
to the Project Gutenberg Literary Archive Foundation are tax
deductible to the full extent permitted by U.S. federal laws and
your state’s laws.

The Foundation’s business office is located at 809 North 1500


West, Salt Lake City, UT 84116, (801) 596-1887. Email contact
links and up to date contact information can be found at the
Foundation’s website and official page at
www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission
of increasing the number of public domain and licensed works
that can be freely distributed in machine-readable form
accessible by the widest array of equipment including outdated
equipment. Many small donations ($1 to $5,000) are particularly
important to maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws


regulating charities and charitable donations in all 50 states of
the United States. Compliance requirements are not uniform
and it takes a considerable effort, much paperwork and many
fees to meet and keep up with these requirements. We do not
solicit donations in locations where we have not received written
confirmation of compliance. To SEND DONATIONS or determine
the status of compliance for any particular state visit
www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states


where we have not met the solicitation requirements, we know
of no prohibition against accepting unsolicited donations from
donors in such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot


make any statements concerning tax treatment of donations
received from outside the United States. U.S. laws alone swamp
our small staff.

Please check the Project Gutenberg web pages for current


donation methods and addresses. Donations are accepted in a
number of other ways including checks, online payments and
credit card donations. To donate, please visit:
www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could
be freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose
network of volunteer support.

Project Gutenberg™ eBooks are often created from several


printed editions, all of which are confirmed as not protected by
copyright in the U.S. unless a copyright notice is included. Thus,
we do not necessarily keep eBooks in compliance with any
particular paper edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg
Literary Archive Foundation, how to help produce our new
eBooks, and how to subscribe to our email newsletter to hear
about new eBooks.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like