0% found this document useful (0 votes)
18 views

Web Application Development with Streamlit: Develop and Deploy Secure and Scalable Web Applications to the Cloud Using a Pure Python Framework 1st Edition Mohammad Khorasani - The ebook in PDF and DOCX formats is ready for download now

The document provides information about the ebook 'Web Application Development with Streamlit' by Mohammad Khorasani and others, which focuses on developing and deploying secure web applications using a Python framework. It includes links to various related ebooks available for instant download on ebookmeta.com. Additionally, it outlines the structure and contents of the book, including chapters on Streamlit basics, user interface design, data management, and database integration.

Uploaded by

deltintebyan94
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Web Application Development with Streamlit: Develop and Deploy Secure and Scalable Web Applications to the Cloud Using a Pure Python Framework 1st Edition Mohammad Khorasani - The ebook in PDF and DOCX formats is ready for download now

The document provides information about the ebook 'Web Application Development with Streamlit' by Mohammad Khorasani and others, which focuses on developing and deploying secure web applications using a Python framework. It includes links to various related ebooks available for instant download on ebookmeta.com. Additionally, it outlines the structure and contents of the book, including chapters on Streamlit basics, user interface design, data management, and database integration.

Uploaded by

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

Read Anytime Anywhere Easy Ebook Downloads at ebookmeta.

com

Web Application Development with Streamlit:


Develop and Deploy Secure and Scalable Web
Applications to the Cloud Using a Pure Python
Framework 1st Edition Mohammad Khorasani
https://ebookmeta.com/product/web-application-development-
with-streamlit-develop-and-deploy-secure-and-scalable-web-
applications-to-the-cloud-using-a-pure-python-framework-1st-
edition-mohammad-khorasani/

OR CLICK HERE

DOWLOAD EBOOK

Visit and Get More Ebook Downloads Instantly at https://ebookmeta.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Secure Web Application Development: A Hands-On Guide with


Python and Django 1st Edition Matthew Baker

https://ebookmeta.com/product/secure-web-application-development-a-
hands-on-guide-with-python-and-django-1st-edition-matthew-baker/

ebookmeta.com

Web App Development and Real-Time Web Analytics with


Python: Develop and Integrate Machine Learning Algorithms
into Web Apps Nokeri
https://ebookmeta.com/product/web-app-development-and-real-time-web-
analytics-with-python-develop-and-integrate-machine-learning-
algorithms-into-web-apps-nokeri/
ebookmeta.com

Beginner's Guide to Streamlit with Python: Build Web-Based


Data and Machine Learning Applications 1st Edition Sujay
Raghavendra
https://ebookmeta.com/product/beginners-guide-to-streamlit-with-
python-build-web-based-data-and-machine-learning-applications-1st-
edition-sujay-raghavendra/
ebookmeta.com

The American War in Afghanistan: A History 1st Edition


Malkasian

https://ebookmeta.com/product/the-american-war-in-afghanistan-a-
history-1st-edition-malkasian/

ebookmeta.com
Directed Evolution Methods and Protocols Methods in
Molecular Biology 2461 Andrew Currin (Editor)

https://ebookmeta.com/product/directed-evolution-methods-and-
protocols-methods-in-molecular-biology-2461-andrew-currin-editor/

ebookmeta.com

Managing Innovation: Integrating Technological, Market and


Organizational Change 6th Edition Joe Tidd

https://ebookmeta.com/product/managing-innovation-integrating-
technological-market-and-organizational-change-6th-edition-joe-tidd/

ebookmeta.com

Reassured Love Club Curve Club Curves Series 1st Edition


Jade Royal

https://ebookmeta.com/product/reassured-love-club-curve-club-curves-
series-1st-edition-jade-royal-2/

ebookmeta.com

Practical Leadership in Community Colleges : Navigating


Today's Challenges 1st Edition George R. Boggs

https://ebookmeta.com/product/practical-leadership-in-community-
colleges-navigating-todays-challenges-1st-edition-george-r-boggs/

ebookmeta.com

InHabit People Places and Possessions Cultural


Interactions Studies in the Relationship between the Arts
Antony Buxton (Editor)
https://ebookmeta.com/product/inhabit-people-places-and-possessions-
cultural-interactions-studies-in-the-relationship-between-the-arts-
antony-buxton-editor/
ebookmeta.com
An Unexpected Love A Variation of Jane Austen s Pride and
Prejudice Lily Bernard

https://ebookmeta.com/product/an-unexpected-love-a-variation-of-jane-
austen-s-pride-and-prejudice-lily-bernard/

ebookmeta.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
Discovering Diverse Content Through
Random Scribd Documents
The Project Gutenberg eBook of An English girl
in Japan
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.

Title: An English girl in Japan

Author: Ella M. Hart Bennett

Release date: April 23, 2017 [eBook #54591]


Most recently updated: October 23, 2024

Language: English

Credits: Produced by KD Weeks, MFR and the Online Distributed


Proofreading Team at http://www.pgdp.net (This file
was
produced from images generously made available by
The
Internet Archive)

*** START OF THE PROJECT GUTENBERG EBOOK AN ENGLISH


GIRL IN JAPAN ***
Transcriber’s Note:
Illustrations have been moved slightly to avoid falling
within paragraphs. The full-page illustrations with a blank
verso participated in pagination. These pages have been
removed, and page numbers are skipped.
The few footnotes have been moved to the end of
paragraph in which they are referenced.
Minor errors, attributable to the printer, have been
corrected. Please see the transcriber’s note at the end of
this text for details regarding the handling of any textual
issues encountered during its preparation.
Corrections appear as underlined word or phrase. If
the cursor is placed over the phrase, the original text
appears in a popup tool-tip. The endnote’s errata table
will provide a brief explanation of the change to be found
at the indicated page and line of the original.

AN ENGLISH GIRL IN JAPAN


(Page 24.
A LITTLE NASAN APPEARED.
AN ENGLISH GIRL
IN JAPAN
BY
ELLA M. HART BENNETT

SECOND EDITION

Illustrated

LONDON
WELLS GARDNER, DARTON & CO., LTD.
3, PATERNOSTER BUILDINGS, E.C.
First Edition, May, 1904
Second Edition, June, 1906

TO

MY FRIEND MARY
A SOUVENIR

OF MANY PLEASANT DAYS

‘Though wide the ocean now dividing us,


Ne’er let its waters separate our souls.’
(Japanese quotation.)
PREFACE TO SECOND EDITION

The following sketches of life in Japan and the voyage there and
back are taken from a diary which I kept during my travels.
Since writing my little book of personal reminiscences, which,
thanks to indulgent readers and kind friends, is now republished in a
second edition, many and great changes have taken place in the Far
East.
Japan has now become a great Power--not only in the East, but
also in the West. It is little Japan no longer; or, rather, its greatness
is now understood and acknowledged by all the world. Western
civilization has taken a firm hold on the Japanese people. They have
been rapidly adopting, and, in fact, improving on, Western methods,
customs, and manners. The fear of the globe-trotter of to-day is
whether he will be in time to see the Japan of his dreams and of
romance, before this great Western wave of progress and reform has
divested the Land of the Rising Sun of its quaint originality and
fascinating charm.
E. H. B.
1906.
PREFACE TO FIRST EDITION

The following sketches of life in Japan and the voyage there and
back are taken from a diary which I kept during my travels.
As Japan and its wonderful little people have come so much
before the world during the last few years, and especially at this
time are one of the chief factors in the crisis in the Far East, I
thought that these reminiscences and anecdotes taken from real life
might be of interest.
I am indebted to the editors of the Cornhill, Sketch, Sunday, and
the Buenos Aires Standard for the reproduction of some of the
following sketches.
ELLA HART BENNETT.
1904.
CONTENTS

CHAPTER I
ON THE WAY

PAGE
I start on my travels--A fair Theosophist--Life on an 1–12
American liner--Arrival at New York--Delmonico’s---
The Hotel Waldorf--Niagara Falls--Across the Lakes--
The prairies--A quiet Sunday

CHAPTER II
IN THE ROCKIES

First sight of the Rockies--Stay at Banff--Indians and 13–22


salmon--Arrival at Vancouver--The Empress of India--
Chinese passengers--The missing day--A court-
martial--First sight of Japan

CHAPTER III
EARLY DAYS IN JAPAN

A new friend--A Japanese dinner--Japanese temples--An 23–32


earthquake--A fire in Yokohama

CHAPTER IV
A JAPANESE HARROGATE

A trip to the Japanese Harrogate--A curious travelling 33–50


companion--A Japanese inn--A mountain ride--At the
sulphur springs--A sulphur bath--A night in a tea-
house--Sad news

CHAPTER V
AN IMPERIAL GARDEN-PARTY

Silk dresses and frock-coats--A disappointed Colonel-- 51–65


The Royal procession--The chrysanthemums--I am
presented--A Japanese play--Japanese royal sport--
The Mikado and his subjects

CHAPTER VI
JAPANESE LADIES

Their habits and ways--Home life--The Honourable 66–82


Bath--Count Ito and his wife--Old Japan--Loyalty to
husbands--A mixed marriage--Curious customs--
Japanese sayings

CHAPTER VII
JAPANESE CHILDREN

Boys and girls--Games--The Feast of Dolls--School life-- 83–97


The ‘Hina Matsuri’--The Feast of the Carp--The ‘Bon
Matsuri,’ the festival for dead children

CHAPTER VIII
SERVANTS IN JAPAN
Their politeness--Frequency of their baths--Always 98–108
ready for a nap--Mrs. Peter Potts

CHAPTER IX
SOME FESTIVALS AND A FUNERAL

The Imperial Silver Wedding--Parade of the troops--The 109–123


wedding feast--The Chinese ball in Tokio--A gay
assembly--A Royal funeral--Strange customs

CHAPTER X
CHANG, MY CHOW

His first appearance--Adventures and mishaps-- 124–140


Companions in the Hospital--Chang goes to church--
Facing the enemy

CHAPTER XI
FURTHER ADVENTURES OF CHANG

The tale of a tub--Sayonara--Board-ship acquaintance-- 141–163


Queer company

CHAPTER XII
PAUL AND VIRGINIA

Life on a tea-estate--My animal friends--Two brown 164–176


bears--Brutus, the monkey--Always in mischief--The
Brazilian macaw
LIST OF ILLUSTRATIONS

PAGE
A little Nasan appeared Frontispiece
In the Heart of the Rockies 15
‘Tum adain soone! sayonara!’ 26
One of the Shinto Temples 27
The Great Bronze Buddha 28
We start for Kodzu 35
Idaka, the Guide 39
Prepared for the Night 47
Our Invitation-cards were very large and thick 53
The Gardens are very beautiful 57
Quaint Signboards in some of the Streets, Tokio: 63
Butcher’s, Umbrella Shop
Quaint Signboards in some of the Streets, Tokio: Poultry 64
and Egg Shop, Japanese Tailor
‘Many are distinctly pretty when young’ 68
A Japanese Lady of the Upper Class 69
A Tea-house Veranda 72
‘How picturesque they looked!’ 84
Japanese Children 87
Japanese Servants 99
That Delightful Hotel in the Hills 102
Three Friends 125
The Garden of the Little Tea-house 129
The Kind Old ‘Isha-san’ 133
The Little House in the Forest 137
Chang’s First Appearance 140
Yum-Yum and Dodo 141
The Monastery in the Rock 143
Mystical ‘Fuji-Yama’ 151
The Lotus Flower of Japan 154
Arara 173
Initials, Tailpieces, etc.
An English Girl in Japan
CHAPTER I
ON THE WAY

I start on my travels--A fair Theosophist--Life on an American liner--


Arrival at New York--Delmonico’s--The Hotel Waldorf--Niagara
Falls--Across the Lakes--The prairies--A quiet Sunday.

he visit to the Far East, where my father had


business in Japan, was taken when I was
only eighteen. Being an only child, I had
been his constant companion since the death
of my mother nine years previously. I was
never sent to school, and, after a succession
of governesses, my education was put into
the hands of the old bachelor Rector of our
parish, whose ideas as to what a girl ought
to know were somewhat peculiar. However, in other ways I had
more practical knowledge of life than was usual for one of my age,
as my father discussed subjects of all kinds with me freely; and I
grew up to take interest in topics of the day, in animal life of all
kinds, and in my garden, of which I was very proud.
Until the last moment I feared something might occur to prevent
our going; and it seemed almost too good to be true to think I was
actually to see the country from where my father had brought so
many beautiful curios on his former visit, and which I had always
heard spoken of as an earthly paradise.
However, the day of departure came at last, and after many
preparations and tearful farewells from the two old servants, who
were to keep house for us during our absence, we started--two
planet pilgrims bound for the Land of the Rising Sun.
I have always disliked books of travel with dates describing the
day and hour when the writer did this or that, and giving minute
descriptions of food, climate, feelings, etc. I don’t think it is in the
least amusing to read that on Monday, the 26th, the heroine was
seasick, and on the 30th, at 6 p.m., was able to enjoy roast mutton
and pudding. Or that she landed on such a day at such a place, and
exactly how she spent each hour. I have decided only to write about
the events and experiences which have most impressed me during
my travels, and to describe as well as I can the characteristics of the
people that I came across.
We sailed from Southampton in the Paris, a huge American liner of
12,000 tons, more like a floating hotel than a ship. My first
impressions of life on board were not altogether enjoyable, as we
started in a gale, and I own to more than once wishing myself back
again in Old England. However, in a couple of days the weather
calmed down, and I soon recovered my sea-legs, and was able once
again to enjoy life.
There were a good number of passengers of every description and
nationality on board--a theatrical company, Mr. Carnegie (the
millionaire), the late Dr. Barnardo, Mrs. Annie Besant, a foreign
Ambassador and a Colonial Governor, besides many other well-
known people. Mrs. Besant was accompanied by two Indian
Mahatmas, who were the objects of much interest. They spent the
greater part of their time together, reclining in long deck-chairs, with
pillows behind their heads, and covered up to their chins with thick
rugs. Sometimes they lay for hours, hand in hand, with closed eyes;
at other times they talked earnestly in low tones. One Indian was
very short and fat, the other long and thin, with snake-like
movements and curious piercing eyes. They had thick black hair
down to their shoulders, little red caps with tassels on their heads,
and long, rusty black frock-coats and white trousers--a truly
remarkable pair. I overheard the fat one remark to Mrs. Besant that
before they could disintegrate and assume their astral shapes it was
necessary to abstain from food for twelve hours, when their bodies
would be in a fit state to soar. The fat little man must evidently have
made up for his abstinence at other times, judging from his portly
appearance. We were told that the trio were going to lecture on
Theosophy in Chicago, and, after some little persuasion, Mrs. Besant
consented to give a lecture on board. Over three hundred of the
passengers assembled in the saloon, and the fair Theosophist held
us fascinated for more than an hour. She spoke very quietly, but with
intense earnestness, in a rich, deep voice, with hardly a moment’s
pause. The subject was evolution, and the manner in which the soul
passes from one body to another, either getting higher and more
spiritual, or deteriorating and becoming more animal.
One of the audience got up and asked for the proofs of Buddhism
being superior to other religions, others followed suit, and the
discussion became somewhat heated, until the chairman, Mr.
Carnegie, restored order by saying that we were not at a debating
society, but that Mrs. Besant having been persuaded to speak for our
pleasure and entertainment, he thought the least we could do was
to listen with respectful attention, if not agreeing with the subject in
question. (Loud applause.)
The remainder of the voyage passed in the usual way--sports,
tournaments, concerts, the daily lottery on the run--the prize
number being sometimes worth between thirty and forty pounds.
Various other amusements were arranged by enterprising
passengers and officers of the ship.
We were fortunate in arriving at New York up to time--in five days
and a half--as the week before the mails had been delayed by a
severe cyclone, from the effects of which New York was still
suffering. On landing at the Custom House the scene of confusion
baffled description. We luckily possessed a pass, so had not to open
our trunks, but it seemed hours before our thirty-five boxes and
packages were collected together. Meanwhile, I sat waiting on one of
my boxes until my patience was quite exhausted.
My father had engaged rooms at the Hotel Waldorf, where we
found a most charming suite had been reserved for us. Each set of
rooms in the hotel is furnished in a different style--one Indian, one
Japanese, another Egyptian, and a special honeymoon suite, all pink,
blue, and Cupids. This hotel--probably the most luxurious in the
world--was built by Mr. Astor, the millionaire, costing £400,000, and
£200,000 to furnish. The State-rooms, fitted up for the Prince of
Wales, who never went there after all, are magnificent. The walls are
hung with Gobelin tapestry, and all the dinner-service is of solid
silver. I was particularly fascinated with the winter garden, which
resembles a huge conservatory, with fountains, palms, and little
tables dotted about. A string band played there every evening, and I
saw a number of smartly-dressed American women and girls, as well
as men, enjoying their favourite American drinks. I was not content
until I had sampled a ‘corpse reviver,’ drinking it through a long
straw, but I cannot say the result was altogether satisfactory.
Everything about New York interested me immensely after the
quiet country life I had led at home. The crowds in the streets, the
bustle, the electric-cars and overhead railways, were at first
bewildering. We were given a box at the Opera Comique to see
‘Panjandrum,’ and there I saw several American society beauties.
The girls reminded me much of Dana Gibson’s charming drawings.
The men seemed insignificant in comparison; but it is said they
make ideal husbands, which is an important consideration.
After the theatre we went to a ‘roof garden,’ going up by lift to the
top of a large building, and through a door on to the roof. This had
been converted into a Café Chantant--plants, chairs, a small stage,
and a restaurant, all lit up with little coloured lamps. It was very
amusing, and a delightful way of spending a hot evening, as,
although the end of September, the weather in New York was still
sultry.
Before returning to the hotel, my father took me to Delmonico’s,
the famous New York restaurant, where we had an excellent supper,
beginning with hot, soft-shell crabs--a very favourite dish in America.
They are just like our crabs, but the shells are quite soft and crisp,
and one eats shell, legs, and all. Mrs. Besant and her two Mahatmas
were sitting at a table near us. They had evidently no immediate
intention of assuming their astral shapes, to judge by the number of
dishes which were placed before them and were carried away empty.
A precocious little American girl of about ten was having supper with
her ‘poppa’ and ‘momma’ at the table next to us. Between the
intervals of eating she placed her elbows on the table, brandishing
aloft her knife and fork, and made comments on the people round in
a loud, nasal voice. After some especially indiscreet remark about
the long, thin Indian, who turned and looked at her with a
melancholy gleam in his snake-like eye, ‘momma’ exclaimed in
equally strident tones: ‘I guess, Jemima, you had better keep your
remarks to your own inside, and not make them public, or you’ll get
yourself disliked--say?’ For a few moments Jemima remained silent,
but soon began again.
The next morning I was awakened to find a negro standing by my
bedside with a tray in his hands. He stood motionless in an attitude
of attention, his feet well turned out, a broad grin showing his white
teeth, apparently awaiting my commands. After receiving my orders,
he departed with another low bow, still smiling. Most of the house-
work is done in America by negroes, who are very quick and willing.
After three delightful but most fatiguing days in New York, spent
in sight-seeing, we left by the night train for Niagara. I shall never
forget my first impressions of those wonderful Falls, which even
exceeded my expectations, they are so indescribably beautiful and
impressive.
After lunch at the hotel where we were to stay the night, we
walked to various points on the American side, and at each the view
seemed more beautiful than the last. The Niagara River divides and
forms three islands. On one side are the American Falls; on the
other, over a large suspension-bridge, are the Canadian Horseshoe
Falls. I persuaded my father to take me down under the latter. We
were first both arrayed in a complete set of oilskins--coat, long
boots, and pointed hood--and presented most comical figures. A
guide led the way, as the path in places was very steep and slippery.
At one spot the water poured down on us like a shower-bath, and it
required some strength of mind not to turn back; but when we had
once started we were determined to see all. We came to a tunnel,
lighted by lanterns, where the water dripped from the roof and
walls, forming deep puddles, through which we plunged; and I was
glad to find myself in the daylight again, safe and sound. The
sunshine on the water produced a rainbow at both Falls--a most
beautiful sight on the white foam.
Almost more impressive, if possible, than the Falls are the
whirlpool rapids, which we visited next morning--the place where
Captain Webb was drowned, and where only lately a foolhardy
woman lost her life attempting to cross in a cask. The cask reached
its destination safely, after some hours’ buffeting with the current,
but when opened, the woman was found dead.
I can only liken the scene to a tremendous storm on a rocky coast,
as the waves dashed over the rocks, throwing up foam and spray
high into the air, whilst the thunder of the water was deafening. The
cliffs on either side of the river were covered with grass and trees
growing to the water’s edge, calm and peaceful--a striking contrast
to the Rapids and their ceaseless tumult.
From Niagara we went by train and boat to Toronto. On our arrival
at the hotel we found five reporters sitting in the hall awaiting us,
ready to pounce on my father, who, being well known in the literary
world, was doomed to be victimized. In vain did my unfortunate
parent remind them it was past nine o’clock, that we had had no
dinner, and having only that evening made our first acquaintance
with the delights of Canada, it was impossible fully to do justice
either to himself or the country. All was of no avail; a long string of
questions had to be answered before we were permitted to depart in
peace, and the next morning in all the leading papers appeared
wonderful and totally untrue accounts of our family history,
appearance, and sentiments.
From Owen Sound we went by steamboat across Lake Huron and
Lake Superior to Port William, which is in connection with the
Canadian-Pacific Railway. The lake scenery is very beautiful, and was
a pleasant change after the dusty train. We were three hours
passing through the lock which divides the two lakes. As the
steamboats are run on strictly temperance principles, and no wine or
spirit of any description allowed on board--although we were fed
with such dainties as frogs’ legs and soft-shell crab--the excitement
was great on seeing a little shanty by the lock where home-brewed
beer could be obtained. There was a frantic rush on shore, and the
little inn must have reaped a harvest that day. Whilst waiting at the
lock I was much interested in seeing large quantities of timber
floating over the rapids, having come downstream hundreds of miles
from the Canadian forests. The wood is caught by huge nets made
of chains, and just by the side of the lock is a storage depot, where
the timber is collected and cut into planks. We had some excellent
lake trout for dinner, and in the evening watched the northern lights,
which illuminated the sky far into the night.
The next morning we left Port William, a quaint little town which
had only been in existence three years, but already boasted of a
church and good shops and houses, and started westward on our
four days’ train journey to Vancouver. During the first twenty-four
hours we passed through the prairies, a vast stretch of yellow plain,
with its deep purple shadows, looking terribly desolate, but yet
fascinating in its loneliness. Here and there were prairie fires--some
still smouldering, others which had left only their charred and
blackened marks behind them. We passed many little settlements
and farms--one farm was a hundred miles in size--and an immense
quantity of wheat is grown in this district. At each station are huge
elevators, and the grain is sucked up into them through tubes by
means of compressed air at marvellous rapidity. It was harvest-time
when we passed, but, being Sunday, none of the men were at work.
It seemed quite pathetic to see lines of buggies and cars waiting
outside some of the little settlement churches, and as we passed we
saw many of the settlers riding and driving to and from service.
Some must have come very long distances. At one place, far away
from any dwelling, there was a little cemetery--just a dozen white
stones and one little cross standing out against the sky--only divided
by a rough wooden rail from the rest of the prairie. In winter the
country is covered with snow to a depth of from twenty to thirty
feet, and the occupants of the farms have to dig their way out,
leaving only the front-door exposed. We saw large herds of cattle
and horses, but the buffalo is almost extinct. He, as well as the
Indian, seems to disappear as civilization advances.
There are still some Indians left, however, and we passed several
encampments. Their wigwams looked more picturesque than

You might also like