Book Image

Building SPAs with Django and HTML Over the Wire

By : Andros Fenollosa
4.5 (2)
Book Image

Building SPAs with Django and HTML Over the Wire

4.5 (2)
By: Andros Fenollosa

Overview of this book

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.
Table of Contents (14 chapters)
1
Part 1: Getting Started with Python
4
Part 2: WebSockets in Django
8
Part 3: HTML over WebSockets
11
Part 4: Simplifying the frontend with Stimulus

Avoiding cross-site request forgery (CSRF) with WebSockets

By using sessions, we are exposing users to a CSRF attack unless we put appropriate measures in place.

CSRF attacks

CSRF attacks are malicious attacks on a website in which unauthorized commands are sent from one user to a second site with hidden forms, AJAX requests, or any other method in a hidden way.

You can find a reference here: https://en.wikipedia.org/wiki/Cross-site_request_forgery.

Channels provides a tool that will help us to avoid this type of attack in a simple way:

  1. We define the allowed Hosts in project_template/settings.py. In our case, we are using environment variables inside Docker:
    ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS"). split(",")
  2. We edit project_template/asgi.py, by importing OriginValidator. We must pass two parameters: URLRouter (or any intermediary middleware) and the Hosts we want to protect:
    # project_template/asgi.py
    import django
     
    os.environ.setdefault...