22,79 €
The HTML over WebSockets approach simplifies single-page application (SPA) development and lets you bypass learning a JavaScript rendering framework such as React, Vue, or Angular, moving the logic to Python. This web application development book provides you with all the Django tools you need to simplify your developments with real-time results.
You’ll learn state-of-the-art WebSocket techniques to realize real-time applications with minimal reliance on JavaScript. This book will also show you how to create a project with Docker from the ground up, test it, and deploy it on a server. You’ll learn how to create a project, add Docker, and discover development libraries, Django channels, and bidirectional communication, and from then, on you’ll create real projects of all kinds using HTML over WebSockets as a chat app or a blog with real-time comments. In addition, you’ll modernize your development techniques by moving from using an SSR model to creating web pages using WebSockets over HTML. With Django, you’ll be able to create SPAs with professional real-time projects where the logic is in Python.
By the end of this Django book, you’ll be able to build real-time applications, as well as gaining a solid understanding of WebSockets with Django.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 197
Veröffentlichungsjahr: 2022
Learn to build real-time single page applications with Python
Andros Fenollosa
BIRMINGHAM—MUMBAI
Copyright © 2022 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: Pavan Ramchandani
Publishing Product Manager: Bhavya Rao
Senior Editor: Mark D'Souza
Content Development Editor: Feza Shaikh
Technical Editor: Simran Udasi
Copy Editor: Safis Editing
Project Coordinator: Manthan Patel
Proofreader: Safis Editing
Indexer: Tejal Daruwale Soni
Production Designer: Joshua Misquitta
Marketing Coordinators: Anamika Singh and Marylou De Mello
First published: August 2022
Production reference: 1290722
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-80324-019-0
www.packt.com
I want to dedicate this book to four people who gave me the necessary tools to make writing it possible:
My mother, for giving me a heart
My grandmother, for giving me an education
My uncle, Toni Hurtado, for giving me wisdom
My girlfriend, Valentina Rubane, for giving me motivation
– Andros Fenollosa
This book is about one principle: coordination. How do we coordinate events that occur in different places and at different times within a web application? For example, if multiple users are connected to the same website and need to send messages to each other, how can we achieve fast and effective communication? Such systems are known as real-time applications.
Real-time applications are a standard in web development today. The WebSocket protocol emerged in 2011; it allows you to open a bidirectional tunnel between your web application and another component. The WebSocket protocol creates greater dynamism, and thus improves the user experience. In addition to lower resource consumption, information is updated only when necessary - this avoids redundant requests to the server.
There are many sorts of real-time applications. The first ones that come to mind are social networks or messaging applications since they are part of our daily life. We like to receive information instantly, because we don’t need to refresh the page to know if an event has occurred. We don’t want to wait, we are inherently impatient. Learning how to develop real-time applications gives us an advantage when finding new techniques to start a software project.
This work presents an alternative to JavaScript for creating Single-Page Applications; and some might worry that the author has started a crusade against JavaScript - but it’s not the case. Instead, his interest is in explaining the power of Python using WebSockets over HTML to produce real-time applications.
The author of this book, Andros Fenollosa, is a passionate web developer who, using his extensive teaching experience, will give you the necessary foundations to be involved in the development of real-time application.
Camilo Chacón Sartori,
Ph.D. Student in Computer Science at Artificial Intelligence Research Centre (IIIA)
Andros Fenollosa have been teaching web technologies, best practices, and the fundamentals of functional programming for more than a decade.
Since finishing his studies, he have not stopped developing applications, sometimes as a frontend developer, others as a mobile application developer, backend developer, and project manager. Currently, he is working as CTO in a software development studio.
He combine his professional work maintaining several open source projects related to Python, Django, Clojure (including my own framework: Tadam Web Framework), and Linux. He also like to share his knowledge through podcasting, writing newsletters and books, Twitter, and his blog.
Norbert Máté is a senior web developer/tech lead with 13+ years of experience. His primary programming languages are Python and JavaScript. He is passionate about software architecture, clean code, and leadership. Norbert has also reviewed other Django books, such as Django RESTful Web Services and Django 2 by Example.
I would like to thank my wife for her support.
HTML over WebSockets simplifies the creation of single-page applications (SPAs) by avoiding frontend rendering, giving real-time responses, and simplifying the logic by moving it to the backend. In this book, you won't learn how to use a JavaScript rendering framework such as React, Vue, or Angular, instead moving the logic to Python. This will simplify your developments, giving you real-time results with all the tools provided by Django.
Developers will learn state-of-the-art WebSockets techniques to realize real-time applications with minimal reliance on JavaScript. They will also learn, from the ground up, how to create a project with Docker, test it, and deploy it on a server.
You will follow the roadmap of a Django developer who wants to create SPAs with a good experience. You will create a project and add Docker, development libraries, Django channels, and bidirectional communication, and then you will create real projects of all kinds using HTML over WebSockets, such as a chat app or a blog with real-time comments. You will modernize your development techniques by moving from using an SSR model to creating web pages using HTML over WebSockets. With Django, you will create SPAs with professional real-time projects where the logic will be in Python.
By the end of the book, you will be able to make real-time applications and will have mastered WebSockets with Django.
This book is for intermediate-level Django developers and Python web developers who wish to create real-time websites with HTML and Django channels. If you are a developer looking for an alternative to creating an API without giving up the possibility of separating the frontend from the backend and do not want to depend on JavaScript to make SPAs, then this book is for you. Basic knowledge of HTML and Python along with an understanding of basic web development concepts is expected.
Chapter 1, Setting up the Virtual Environment, is where we prepare the IDE and Docker to be able to work with Python.
Chapter 2, Creating a Django Project around Docker, is where we create a project in Django and test it with different Docker containers.
Chapter 3, Adding WebSockets to Django, is where we integrate a WebSockets server into Django via Channels and then test that it can send and receive data.
Chapter 4, Working with the Database, is where we create a microblogging application where we interact with a database performing elementary actions, such as querying, filtering, updating, or deleting.
Chapter 5, Separating Communication in Rooms, is where we learn how to separate communication by users or groups by creating a chat application with private messages and groups.
Chapter 6, Creating SPAs on the Backends, is where we will integrate solutions for the typical problems you may encounter when building a SPA, such as integrating a server-side rendering system per route or hydration sections.
Chapter 7, Creating a Real-Time Blog Using Only Django, helps you use all the knowledge acquired to build a complete SPA blog in real time.
Chapter 8, Simplifying the Frontend, covers simplifying the interaction with client events by integrating Stimulus into the frontend.
You will need a version of Docker and Docker Compose (or Docker Desktop, which includes everything) installed on your computer in the latest version and a code editor or IDE. I recommend PyCharm Professional. All code samples have been tested using Docker on macOS and Linux operating systems; however, they should also work without a problem on Windows.
You will need the professional version of PyCharm to have Docker integration. Otherwise, you can start Docker from the terminal or with Docker Desktop.
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/Building-SPAs-with-Django-and-HTML-Over-the-Wire. 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!
We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/2q526.
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: "The information from the frontend goes to receive_json, which in turn receives the 'text in capital letters' action by executing the self.send_uppercase(data) function."
A block of code is set as follows:
* { font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; box-sizing: border-box;}Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: "At the moment, the Edit and Delete buttons are for decoration; later, we will give them their functionality."
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 Real-Time Django over the Wire, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page 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.
In this part, we will learn how to configure and build a Django project using Docker containers. We start with preparing a workspace, configuring a Python image, creating a Django project and integrating it so that it is isolated to the operating system, and can be lifted from any computer.
In this part, we cover the following chapters:
Chapter 1, Setting up the Virtual EnvironmentChapter 2, Creating a Django Project around DockerA good programmer is not afraid of technology because their confidence doesn’t lie in the programming language, but in their own skills and experience. Tools only make them more productive. We can’t build even the simplest website in an acceptable amount of time without the right software. Building websites with Python is possible on any modern operating system, regardless of the hardware behind it. The core team that maintains this fantastic language already takes care of some of the more tedious tasks, such as compiling it and optimizing it for the processor you’re using.
However, building a web application in Python, even if we only respond with plain text, requires a great deal of knowledge, including of servers and web applications as well as the WSGI or ASGI interface. We need to abstract that complexity to respond to requests, environments, asynchrony, WebSocket, database connections, and the other elements that define a current web application. That’s why we’re going to set up a desktop with everything you need to be a productive modern Django developer. We will build different real-time applications using the technology offered by Channels, a Django extension (developed by the same Django team), which includes a WebSocket server and WebSocket integrations. The architecture of the applications will differ from how server-side rendering works. The communication path between the server and the client will be bidirectional, allowing us to use it to receive or send events and/or HTML. My intention is that upon finishing the chapter, your focus will be on the code and not on complex configurations that may distract you. To achieve this, we will make use of Docker, the famous container manager, which will open up the possibility of adding all kinds of software already precooked to launch without investing practically any time: databases, web servers, mail servers, and caches, among others. Don’t worry if you have no experience with Docker. I’ll teach you the basics without going into low-level details. After a few tweaks, you’ll practically forget that it’s running in the background.
It’s important not only that we know how to write Python and create real-time infrastructures with Django but also that we have the skills to be independent of the operating system when deploying or working in a team. By virtualizing (or isolating) the processes, we can remain unconcerned about the operating system where it runs, making the project easy to continue for any specialist, and we can anticipate future problems that may occur when deploying to a production server.
In this chapter, we’ll be covering the following topics:
Exploring the software requiredAdding dependenciesConfiguring the IDEInstalling DjangoCreating our projectIn this section, we will take a look at the software that we’ll be using throughout the book and how to install it. The code for this chapter can be found at https://github.com/PacktPublishing/Building-SPAs-with-Django-and-HTML-Over-the-Wire/tree/main/chapter-1.
You should work on an operating system that supports Docker, such as one of the following:
Linux distribution, preferably Ubuntu or DebianmacOS in its latest versionWindows 10 or higher, preferably with the Linux subsystem active and Ubuntu or Debian installedBSD descendants, preferably FreeBSDI assume that if you are reading this book, you already have experience with Python and you have an IDE or rich editor that is ready. If you need to change the IDE, I have recommended, from most to least highly recommended, in the following list some that I consider perfect for working with Python:
PyCharm Professional: If you are a student at a recognized school, you can claim a free student license from JetBrains. Otherwise, I encourage you to pay for the license or use their demo. There is a free version of the IDE, PyCharm Community Edition, but you will not be able to use the Docker interpreter, as this is a feature of the Professional version. You can download this editor from https://www.jetbrains.com/pycharm/.Visual Studio Code (VSCode): This is a very popular editor in web development, created and maintained by Microsoft. You can download this editor from https://code.visualstudio.com/.Emacs: This is very easy to use with a preconfigured framework such as Spacemacs or Doom. You can download this editor from https://www.gnu.org/software/emacs/.Sublime Text with the Djaneiro package: This is the easiest option if you are not looking for complications. You can download this editor from https://www.sublimetext.com/.Don’t force yourself to change. A code editor is a very personal thing, like choosing a brand of underwear: once you find one that fits your way of being, you don’t want to change. I understand that you may not feel like learning new shortcuts or workflows either. Otherwise, if you have no preference, you are free to visit the website of any of the preceding editors to download and install it on your computer.
All the examples, activities, and snippets in the book will work with whatever your editor or IDE of choice is. They will mainly help you with syntax errors, autocompletion, and hints, but your code will be self-contained since it is always stored in plain text. A Python programmer is a Python programmer in any editor but not all editors work well with Python.
You don’t need to install it. You’re reading correctly; the editor didn’t make a mistake in the review. We’ll use Docker to install a Python container capable of launching basic commands in Django, such as creating a project or an app or launching the development server.
I assume that if you are here, it is because you feel comfortable programming with Python. If not, I would recommend you read some of Packt’s books:
Learn Python Programming – Third Edition, Fabrizio Romano and Heinrich Kruger, Packt Publishing (https://bit.ly/3yikXfg)Expert Python Programming – Fourth Edition, Michał Jaworski and Tarek Ziadé, Packt Publishing (https://bit.ly/3pUi9kZ)The fastest way to install Docker is through Docker Desktop.. It’s available on Windows, macOS, and Linux (in beta as I write this). Just go to the official website, download, and install:
https://www.docker.com/get-started
In the case that you want to install it directly through the terminal, you will need to search for Docker Engine (https://docs.docker.com/engine/). This is highly recommended if you use Linux or BSD.
Also install Docker Compose, which will simplify the declaration and management of images and services:
https://docs.docker.com/compose/install/
There is no development that does not involve a versioning system. Git is the most popular option and is almost mandatory to learn.
If you have no knowledge or relatively basic experience with it, I recommend looking at another of Packt’s books, such as Git Essentials – Second Edition, Ferdinando Santacroce, Packt Publishing (https://bit.ly/3rYVvKL).
Alternatively, you can opt to review the more extensive documentation from the official Git website:
https://git-scm.com/
We will avoid focusing on the visual aspect of the browser, which means frontend implementation features such as CSS compatibility or JavaScript features do not matter. The most important thing is to feel comfortable when debugging the backend. Most of the time, we will be in the console checking that the requests (GET, POST, and the like) work as expected, watching the communication over WebSocket to make it smooth, and sporadically manipulating the rendered HTML.
WebSocket
WebSocket is a bidirectional communication protocol, different from HTTP, which facilitates the sending of data in real time between a server and a client, in our case, between a Django server and a frontend client.
In this book, I will use the Firefox Developer Edition (https://www.mozilla.org/en-US/firefox/developer/) browser because it is so convenient to manage the aspects mentioned using it. You are free to use any other browser, such as Chrome, Safari, or Edge, but I’m not sure whether all the features I will use are available with those browsers.
With the software installed, we can start working with the preparations around Python and Docker to run Django or future Python code.
We’re going to run Python via Docker and a configuration file. That way, any developer can replicate our code regardless of whether they have Python installed on their machine and they will be able to run the associated services with just one command.
First, we will create a Python file called hello.py with the following content:
print(“Wow, I have run in a Docker container!”)
The code is ready. We can continue.
The goal will be to configure Docker to run the file. Sounds easy, doesn’t it? Here we go!
We’ll create a file called Dockerfile with the following code:
# ImageFROM python:3.10# Display the Python output through the terminalENV PYTHONUNBUFFERED: 1# Set work directoryWORKDIR /usr/src/app# Add Python dependencies## Update pipRUN pip install --upgrade pip## Copy requirementsCOPY requirements.txt ./requirements.txt## Install requirementsRUN pip3 install -r requirements.txtThis file is used to create a Docker image, or template, with instructions that will be cached. Since they are precached, their launch will be almost instantaneous. Let’s check out what’s going on in the code:
With FROM python:3.10, we are using another existing image as a base. We are extending the work already done. But... where is it? Docker has a repository full of images, or templates, called Docker Hub (https://hub.docker.com/), a place where developers selflessly upload their work. There is an official image called python and we mark it with a tag to use version 3.10. If you have worked with Docker before, you might be wondering why we are not using the Alpine version, the famous operating system that saves so much space in servers around the world. For two reasons: Python is slower (https://pythonspeed.com/articles/alpine-docker-python/