28,79 €
This book is a comprehensive guide to the Streamlit open-source Python library and simplifying the process of creating web applications. Through hands-on guidance and realistic examples, you’ll progress from crafting simple to sophisticated web applications from scratch. This book covers everything from understanding Streamlit's central principles, modules, basic features, and widgets to advanced skills such as dealing with databases, hashes, sessions, and multipages.
Starting with fundamental concepts like operation systems virtualization, IDEs, development environments, widgets, scripting, and the anatomy of web apps, the initial chapters set the groundwork. You’ll then apply this knowledge to develop some real web apps, gradually advancing to more complex apps, incorporating features like natural language processing (NLP), computer vision, dashboards with interactive charts, file uploading, and much more. The book concludes by delving into the implementation of advanced skills and deployment techniques.
By the end of this book, you’ll have transformed into a proficient developer, equipped with advanced skills for handling databases, implementing secure login processes, managing session states, creating multipage applications, and seamlessly deploying them on the cloud.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 276
Veröffentlichungsjahr: 2024
Web App Development Made Simple with Streamlit
A web developer’s guide to effortless web app development, deployment, and scalability
Rosario Moscato
Copyright © 2024 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Group Product Manager: Rohit Rajkumar
Publishing Product Manager: Chayan Majumdar
Book Project Manager: Sonam Pandey
Senior Editor: Anuradha Joglekar
Technical Editor: K Bimala Singha and Simran Haresh Udasi
Copy Editor: Safis Editing
Proofreader: Safis Editing
Indexer: Pratik Shirodkar
Production Designer: Jyoti Kadam
DevRel Marketing Coordinators: Namita Velgekar and Nivedita Pandey
Publication date: February 2024
Production reference: 1110124
Published by Packt Publishing Ltd.
Grosvenor House
11 St Paul’s Square
Birmingham
B3 1RB, UK
ISBN 978-1-83508-631-5
www.packtpub.com
This book was in progress for a long time, and I would like to thank all my e-students for supporting me and pushing me to turn video lessons into pages. I would also to thank my kids, Liv and Giu, for motivating me to be a role model, and my parents for inspiring me to do great things and keep moving forward toward a noble target, come what may!
- Rosario Moscato
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 about 25 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 the 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 a CTO with one of the oldest AI companies in Italy.
Alessio Ligios is a dynamic data scientist, renowned for his proficiency in data analysis and machine learning. With a solid foundation in science and engineering, Alessio excels in transforming intricate data into practical business solutions. In his current role at Live Tech - Amplify your Data, Alessio has demonstrated his expertise by developing and implementing advanced textual content classification models. He excels in predictive modeling, leveraging machine learning (ML) and deep learning (DL) algorithms for accurate trend forecasting. Educationally, Alessio holds a master’s degree in computer science from Università degli Studi “Roma Tre” with a distinguished vote of 110/110.
Corrado Silvestri is a computer engineer. He earned a master’s degree from “Roma Tre” University with a GPA of 100/110. Passionate about the realm of AI and ML, he has produced models and projects of many types, such as forecasting, NLP, and computer vision, establishing the groundwork for his present position as a data scientist at a company that is verticalized in AI. An expert in the analytical phase and data manipulation, he has implemented AI models and solutions, expanding his technical experience and excelling in this field. He is a specialist at finding the perfect compromise by combining engineering expertise, data manipulation, and AI to build cutting-edge solutions for businesses in a variety of industries.
In the swiftly evolving landscape of web application development, the desire to transform innovative ideas into functional web apps has never been more pressing. Web App Development Made Simple with Streamlit is a book that emerges as a beacon for those who seek to navigate this dynamic domain with ease and confidence. This book is meticulously crafted for a diverse range of professionals who share a common goal – the rapid transformation of code into working web applications.
At its core, Web App Development Made Simple with Streamlit is more than just a guide; it’s a journey. It takes you from the fundamentals of Streamlit, a powerful tool that simplifies web app development, to the intricate processes of deploying your solutions on cloud services. This journey is designed to be accessible, empowering you to make your applications available to a vast, global audience with minimal hassle.
Throughout the book, you’ll find a harmonious blend of theoretical knowledge and practical application. The chapters are structured to provide a clear, step-by-step guide, ensuring that even those new to web development can follow along with ease. Moreover, the book is peppered with real-world examples and case studies, providing you with a tangible understanding of how Streamlit can be leveraged in various scenarios.
As you delve into the pages of this book, expect to embark on a transformative learning experience. You’ll gain not just the skills to develop web applications but also the vision to see the potential of your code in the digital world. This book is your companion in unlocking the power of Streamlit, simplifying web app development, and bringing your ideas to the global stage.
This book is tailored for Python programmers looking to transform their scripts into interactive web applications. It’s an essential resource for web developers seeking to streamline their prototyping process using Streamlit’s intuitive framework. Computer science students will find this book a practical guide for applying their theoretical knowledge to real-world web app development. IT professionals and enthusiasts eager to explore the realm of web app creation, especially those keen on deploying applications quickly and efficiently, will discover invaluable insights within these pages. Essentially, this book is a comprehensive toolkit for anyone passionate about bringing web app ideas to life with simplicity and speed.
Chapter 1, Getting to Know Streamlit – A Brief Overview, introduces Streamlit’s role in web app development. The chapter offers an overview of Streamlit’s user-friendly features and capabilities, as well as insight into rapid development with Streamlit.
Chapter 2, Setting Up the Python Coding Environment, includes a step-by-step guide for Python environment setup. The chapter includes tips for efficient Streamlit integration and focuses on creating a streamlined development workflow.
Chapter 3, Exploring Streamlit’s Features and Functionality, explores Streamlit’s functionalities in detail. Practical examples showcasing its versatility are included. The chapter also offers insights into Streamlit’s unique feature set.
Chapter 4, Streamlit Essentials – Configuring the Environment, Managing Packages, and More, describes key techniques for Streamlit environment configuration as well as best practices for efficient package management. Tips for optimizing the Streamlit setup are included.
Chapter 5, Organizing and Displaying Content with Columns, Expanders, and NLP Techniques, explores strategies for content organization using Streamlit’s tools. The chapter introduces natural language processing (NLP) techniques for enhanced content management and describes methods for effective data presentation.
Chapter 6, Implementing NLP Techniques for Text Analysis and Processing in Streamlit, teaches you how to apply NLP for text analysis within Streamlit. A step-by-step guide for NLP integration and case studies showcasing NLP in web app development are included.
Chapter 7, Sharing and Deploying Your Apps on the Cloud Using Streamlit Share, describes instructions for cloud deployment using Streamlit Share. Tips for making apps accessible globally are included. The chapter also offers insights into cloud-based app sharing.
Chapter 8, Advanced Environment Setup and Package Management for Building an AI-Powered Web App, teaches you advanced setup techniques for AI-driven web apps. Package management for AI integration and strategies for setting up an efficient AI web app environment are explained in detail.
Chapter 9, Optimizing Streamlit Web App UX with Customization and UI Features, explains how to enhance user experience through Streamlit customization. The chapter also explores UI features for functional aesthetics. Techniques for UI-driven app optimization are described.
Chapter 10, Utilizing Pretrained Models to Create Specialized and Personalized Web Applications, delves into the integration of pretrained models in web apps. The chapter explains how to create specialized, user-centric applications. Personalization strategies using AI models are described.
Chapter 11, Deploying and Managing Complex Libraries on Streamlit Share, explores techniques for deploying complex libraries on Streamlit Share. Strategies for managing robust app performance and complex library integration are included.
Chapter 12, Smart File Uploading – Advanced Techniques for Professional Web Applications, explains advanced file uploading methods for professionalism. The chapter teaches you how to streamline file uploads for user ease and enhance web apps with efficient file management.
Chapter 13, Creating a Secure Login and Signup Process for Web Applications, shows you how to design secure authentication processes, ensure user data protection, and implement robust login/signup systems in web apps.
Chapter 14, Customizing Pages, Personalizing Themes, and Implementing Multi-Pages, describes techniques for unique page customization. The chapter teaches you how to personalize themes for brand identity and utilize multi-page layouts for complex apps.
Chapter 15, Enhancing Web Apps with Forms, Session State, and Customizable Subdomains, teaches you how to utilize forms and session states for dynamic content. The chapter also describes how to implement customizable subdomains for branding. Strategies for enhancing web apps with advanced features are explored.
Chapter 16, Takeaways and Conclusion, summarizes the book’s essential insights and what you have learned, reflecting on Streamlit’s impact on web app development and offering concluding thoughts on future trends.
You will need an understanding of the basics of Python programming and the Linux Terminal.
Software/hardware covered in the book
Operating system requirements
Python 3.X
The Linux Terminal
If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.
You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Web-App-Development-Made-Simple-with-Streamlit. If there’s an update to the code, it will be updated in the GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “Let’s check whether pip is installed in our Ubuntu box.”
A block of code is set as follows:
st.header("This is a header") st.subheader("This is a subheader") st.text("This is a simple text") st.write("This is a write dimension")Any command-line input or output is written as follows:
pip --version (or pip3 --version)Bold: Indicates a new term, an important word, or words that you see on screen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “We have also completed the Text Analysis and About sections of the menu.”
Tips or important notes
Appear like this.
Feedback from our readers is always welcome.
General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.
Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Once you’ve read Web App Development Made Simple with Streamlit, we’d love to hear your thoughts! Please visit https://packt.link/r/1835086314 for this book and share your feedback.
Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Thanks for purchasing this book!
Do you like to read on the go but are unable to carry your print books everywhere?
Is your eBook purchase not compatible with the device of your choice?
Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.
Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.
The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily
Follow these simple steps to get the benefits:
Scan the QR code or visit the link belowhttps://packt.link/free-ebook/9781835086315
Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directlyPart 1 serves as the foundation for your journey into Streamlit. It begins with a comprehensive introduction to Streamlit, highlighting its significance in the realm of web app development. You are then guided through setting up the necessary Python coding environment, ensuring a smooth start. The part culminates with an in-depth exploration of Streamlit’s diverse features and functionalities, providing a solid base of understanding for you to start building your own web application. This part is crucial for establishing the knowledge and skills needed for the more advanced concepts covered in later sections of the book.
This part contains the following chapters:
Chapter 1, Getting to Know Streamlit – A Brief OverviewChapter 2, Setting Up the Python Coding EnvironmentChapter 3, Exploring Streamlit’s Features and FunctionalityStreamlit is a Python library that allows developers to quickly create interactive web applications with plottings, widgets, themes, and more. It provides an intuitive and easy-to-use interface that makes it simple to create custom web apps with minimal coding effort. It offers a range of built-in widgets and components, such as sliders, dropdowns, and text inputs, that can be used to create interactive visualizations and dashboards. The library also supports real-time data updates and even integrates with popular data science tools, such as pandas, Matplotlib, and TensorFlow.
Compared to other Python libraries for creating web apps, such as Flask and Django, Streamlit focuses on providing an intuitive interface for creating interactive visualizations and dashboards in a very simple and fast way. Flask and Django are more general-purpose web frameworks that can be used for a wider range of web applications, but they require more coding effort to set up and customize. Streamlit is designed to be used primarily for prototyping and creating small to medium-sized web apps and makes it possible to speed up the development process, enabling programmers to share their results with others in a user-friendly and engaging way.
In this chapter, we will first understand the changing scenario in computing methods and cover some key benefits of web applications. Next, we will understand the importance of a Python web framework. After that, we will focus on understanding when to use a local approach and when to work on the cloud. Then, we will learn about some very interesting capabilities of Streamlit. Finally, we will emphasize the importance of turning ideas into prototypes.
In this chapter, we’re going to cover the following main topics:
The changing scenario in computing methodsThe importance of a full Python web frameworkLocal versus the cloudPython libraries for web applications (Flask and Django)Examples of Streamlit’s capabilitiesComputing has advanced dramatically over the past few decades. Earlier systems relied on programs that were installed and run on individual personal computers. Users would purchase software licenses, install the programs themselves, and then access those applications from their desktops. If you wanted to use an application on another computer, you had to install it there as well.
This model dominated computing for many years but was limited and static. It lacked interconnectivity and did not facilitate true collaboration or data sharing across machines. Users were confined to the specific software they installed locally and had to manage separate copies of files and settings on each computer they used.
The rise of networks, improved connectivity, and the early internet started to change this. New possibilities emerged for distributed software, real-time collaboration, and synchronized information across devices. Users no longer had to install and manage many duplicate software installations. Applications could be accessed from anywhere with an internet connection.
Web-based services fueled this transition and accelerated the move to more cloud-centric and mobile-friendly computing. Apps began to launch directly in web browsers instead of requiring installation. Data and files could be stored in central cloud platforms instead of locally, and new devices such as smartphones, tablets, and laptops made the cloud and web even more compelling.
People now live their digital lives in the cloud through web-based services, mobile apps, and cloud platforms. Everything from business software, media, productivity tools, educational resources, and more now have predominantly cloud-based and web-centered counterparts. The cloud provides ubiquitous access across any connected device, constant integration and interoperability between services, automatic updates, scalable resources, collaboration features, mobile optimization, and cost benefits.
Local software is still used in some contexts but is increasingly viewed as limited or outdated. The transition to the cloud and web computing has been rapid and enormously impactful. It has reshaped how we work, learn, play, communicate, consume media, and more. And this transformation will likely only accelerate as enhanced AI technologies, IoT devices, VR/AR systems, and other innovations integrate more deeply into web-based services and cloud platforms.
We have come far from the software installations of yesterday, but the potential is hugely promising. Cloud computing is reimagining technology to fit our modern highly connected and increasingly mobile lifestyles. And this new era of ubiquitous, web-first computing is here to stay.
But considering that we are dealing with web applications in this book, what exactly is a web app?
A web application is a software application that runs within a web browser.
It is accessed via a network and delivers an interactive user experience through a web browser.
The purpose of a web application is to provide access to software capabilities and data over a network using standard web technologies. They allow users to access features and content from any internet-connected device with a web browser.
Web applications are useful when you want to provide access to software and data for a large number of users, potentially within an organization or to external customers and partners. They provide a convenient, consistent interface that works across devices and locations.
Here are some of the key benefits of web applications:
Accessibility: Available anywhere with an internet connection and web browser.Consistency: The same interface and features are available on any device. The look and feel translate across platforms (desktop, mobile, tablet, and more).Centralized management: It’s easy to update web applications for all users simultaneously. New features and enhancements automatically propagate to all users.Integration: Can integrate with other web services, databases, APIs, and more using standard web technologies.Scalability: Can scale to support a large number of simultaneous users with minimal additional overhead. Additional computing resources can be allocated as needed.Cost-effective: Often, it’s more affordable and economical to develop and deploy web applications versus standalone software applications.To summarize, use web applications when you need to provide an application and its data to a large number of users over a network, with the benefits of accessibility, consistency, integration, and scalability that web applications offer. They are a very effective and popular type of software solution.
Now that we know the benefits of web applications, we can move on to the next section, where we will understand the importance of a full Python-based framework.
Building and publishing web applications on the cloud today relies on several key frameworks, languages, and techniques. Some of the most important are as follows:
Web frameworks: Frameworks such as React, Angular, and Node.js make developing web apps easier and more efficient. They handle key tasks such as routing, state management, building components, and handling events. Developers can focus on writing code for their specific applications instead of building infrastructure.Server-side languages: Languages such as PHP, Ruby on Rails, Python, Java, and C# are used on the server side to handle requests, access databases, build APIs, and generate dynamic web content. Node.js, which uses JavaScript, has also become very popular for server-side development.JavaScript: JavaScript is the primary language of the frontend web. It is used to build client-side interfaces, animate and create interactive content, handle user input, request data via HTTP requests, and more. Modern JavaScript frameworks have also enabled the rise of single-page applications.Version control: Tools such as Git help developers collaborate and keep a project’s code and file history synchronized. They enable useful features such as branching, merging, committing, pushing to remote repositories, and rolling back changes.Deployment: There are several options for deploying web applications, including server management services such as AWS EC2, managed services such as Firebase, virtual private servers (VPS), and bare-metal servers. Continuous integration and deployment help get new features and code live as quickly and seamlessly as possible.Containerization: Docker containers package web applications and all their dependencies into isolated, portable, lightweight environments. They help keep development, staging, and production environments consistent and optimized. Containers simplify deploying and scaling web apps.Application programming interfaces (APIs): These allow web applications to integrate with external services and pass data back and forth seamlessly. APIs power features such as user authentication, payment handling, location services, social networking, and much more without requiring multiple web apps to share code bases.As we can see, there are many tools and techniques we can use to build, deploy, scale, and integrate web applications professionally and efficiently today. When combined effectively, they enable fast, robust development cycles, optimized performance, and seamless connectivity between services. Moreover, as technologies continue to evolve, these best practices and stacks will adapt to meet new demands.
This great variety of frameworks, languages, and techniques is a strong weapon in our hands that can make it possible to develop more or less any idea we could have. However, this requires continuous learning and huge know-how of too many different topics.
For this reason, it would be great if a unique framework fully available in Python, a simplistic programming language, could help us develop our web applications quickly, making their deployment simple and smooth. The answer to this problem is Streamlit.
So, in a few words, Streamlit is something that makes it much easier for us to develop, implement, and deploy our ideas and turn them into wonderful web apps. But should the product be made available on our local machines or in the cloud?
There are some key differences to keep in mind when developing software applications versus cloud-based web applications:
Installation: Traditional software needs to be installed on local machines or servers. This includes copying files, setting permissions, possibly configuring settings, and other setup steps. Web apps hosted on cloud platforms such as AWS, GCP, and Azure are deployed and managed by the cloud provider. No local installation is required.Updates: Software updates typically require manual installation on all machines where the application is installed. Web apps hosted on the cloud are automatically updated when developers push new code deployments. Users always get the latest version without any manual work.Scalability: Servers hosting traditional software applications would require manual configuration to scale resources up or down as needed. Cloud infrastructure is infinitely scalable on demand through API calls or automatic scaling policies. More or less CPU, memory, disk space, and more can be allocated programmatically.Availability: Uptime depends on local infrastructure for traditional software. Downtime can occur due to issues with individual servers, networking equipment, database servers, and more. Web apps benefit from the high availability of scalable cloud infrastructure. Regions, availability zones, and replication help minimize outages.Mobility: Traditional software is accessed through dedicated desktop or mobile applications. Web apps are accessible through any modern browser on any internet-connected device. This includes laptops, phones, tablets, TVs, watches, and more.Collaboration: Multiple developers can work together simultaneously, editing code and deploying updates to web apps hosted on version control repositories and cloud hosting services. Edits to code bases are easily synced through source version control systems such as Git. Concurrent editing exposes opportunities for conflicts in traditional development workflows.Costs: Significant upfront costs are typically associated with purchasing and maintaining hardware and software licenses for traditional infrastructure. Cloud computing is based on a pay-per-use model with costs that can be reduced by scaling down or turning off unused resources. No large capital expenses are required. Resources can be scaled on-demand as needs evolve.To summarize, developing web applications on cloud platforms differs from building traditional software installations in key ways. Web apps are often easier to deploy, update, scale, and make highly available and mobile, involve more concurrent collaboration, and have lower upfront costs and more adjustable pricing models.
As we can see, cloud platforms have a lot of advantages and should be our first choice. Now, let’s delve a little bit deeper and look at the differences and specific features of the most popular Python libraries for web applications.
Here’s an overview of some popular Python libraries for building web applications:
Flask: A lightweight and flexible web framework. It’s great for building small to mid-sized apps. Some of its main features are as follows:It has a minimal and intuitive core that can be easily extended. This makes it suitable for anyone looking to create web applications.It supports extensions and integrates with many Python libraries. This allows you to easily expand its functionality.It has built-in support for routing, templates, file uploading, and more, which means it’s quite easy to build APIs and render HTML templates.It’s suited for both small and large-scale projects. Many big companies such as Airbnb and Pinterest use Flask.Let’s look at some situations when we should use Flask:
Building a small to mid-sized website or web appWhen we need more flexibility and control than what a microframework providesThe need to support extensions and integrations with other librariesWhen we’re familiar with Python and want a framework that’s easy to get started withDjango: A high-level Python web framework that encourages rapid development and clean design. It’s suited for large projects and applications. Some of its main features are as follows:It has an object-relational mapper (ORM) that supports multiple databases.It has a permission system and built-in support for users, groups, permissions, and more.It scales well and is used by huge companies such as Instagram, Netflix, Spotify, and others.It has a lot of add-on libraries and integrations available.It enforces a certain structure and best practices. This can be good for newcomers but can also be restrictive.Let’s look at some situations when we should use Django:
