Django in Production - Arghya Saha - E-Book

Django in Production E-Book

Arghya Saha

0,0
28,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.
Mehr erfahren.
Beschreibung

You may have got your first Django developer job after a six-week bootcamp or online course, and that’s great, but what’s next? In small companies, mentorship can be hard to come by and gaining the traits of a senior developer without that can take a long time. This is precisely where Django in Production comes into play.

This book will first delve into the true meaning of "good practice" and help you understand the rationale behind industry professionals building websites in specific ways to develop a solid foundation for your Django projects. Next, you will uncover hidden Django secrets through hands-on exploration, leveraging the power of Docker and version control to your advantage. You will gain insights into mastering Git hooks for efficient code maintenance, establishing a robust CI pipeline, and harnessing the capabilities of AWS Beanstalk. These tools will empower you to develop highly scalable products—an essential skill set for aspiring developers transitioning from junior to senior roles. Later, you will understand the significance of monitoring and be introduced to industry-standard tools utilized by professionals for effective monitoring practices.

By the end of this book, you will have set yourself apart from the crowd, equipped with the knowledge and expertise to thrive as a seasoned Django developer.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 460

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Django in Production

Expert tips, strategies, and essential frameworks for writing scalable and maintainable code in Django

Arghya Saha

Django in Production

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: Jane Dsouza

Book Project Manager: Aishwarya Mohan

Senior Editor: Rashi Dubey

Technical Editor: K Bimala Singha

Copy Editor: Safis Editing

Indexer: Hemangini Bari

Production Designer: Alishon Mendonca

DevRel Marketing Coordinators: Nivedita Pandey and Anamika Singh

First published: April 2024

Production reference: 1070324

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-80461-048-0

www.packtpub.com

To my “Maa,” Anima Saha, and to the memory of my “Baba,” for their constant support in helping me reach where I am today. To my partner, Parul, for being a constant inspiration and motivation.

– Arghya Saha

Contributors

About the author

Arghya (argo) Saha, is a software developer with 8+ years of experience and has been working with Django since 2015. Apart from Django, he is proficient in JavaScript, ReactJS, Node.js, Postgres, AWS, and several other technologies. He has worked with multiple start-ups, such as Postman and HealthifyMe, among others, to build applications at scale. He currently works at Abnormal Security as a senior Site Reliability Engineer to explore his passion in the infrastructure domain.

In his spare time, he writes tech blogs. He is also an adventurous person who has done multiple Himalayan treks and is an endurance athlete with multiple marathons and triathlons under his belt.

This book is dedicated to my Maa and memories of my Baba. I would like to thank my partner, Parul, and all my friends who supported me throughout this journey. I am grateful to Ganesh, Rahul, and everyone who helped me with my book.

About the reviewers

Abdul-Rahman Mustafa Saber Abdul-Aziz is an Egyptian Python backend developer, senior AI instructor, capstone projects lead, and IBM consultant. He graduated from Assiut University in Upper Egypt. He believes that to be great, you must take great responsibility.

I want to thank my family, my friends, and my future wife, who I haven’t met yet. I love you so much. I want to thank my father once again; everything I am now is thanks to him. This is the second time that my name has appeared on the Contributors’ list of a book. I want to thank Dr. Rania Hafez, Dr. Huda Goda, Dr. Abdul-Rahman Eliwa, and Mr. Ehab, who always pushed me toward progress, and my close friends, Muhammad Adly, Ahmed Fouad, and many others. Thank you all for everything you gave me; you are my family.

Ruben Atinho, a software engineer specializing in backend engineering, explores the vast realms of technology. Proficient in Python, Django, and PostgreSQL, and experienced with Golang, he combines technical expertise with a passion for reading open source code. Beyond the code base, Ruben finds fulfillment in the harmonies of music, insightful articles, captivating books, and the imaginative narratives of anime.

Md Enamul Hasan is a seasoned full stack Python developer with over a decade of professional experience in software and web application development. Based in New York, United States, Enamul is renowned for his expertise in Python, Django, React, and AWS. He has successfully led the development of various software products, including ERP, e-commerce, and data-driven applications.

In addition to his technical proficiency, Enamul has excelled in leadership roles, contributing significantly to project success. He actively shares his knowledge, participating in forums and conferences and showcasing a passion for problem-solving in the ever-evolving software development landscape.

Enamul extends gratitude to the author for the opportunity to review Django in Production. His extensive experience in Python Django development adds depth to the review, highlighting the book’s value in bridging theory and practice in the dynamic tech industry.

Table of Contents

Preface

Part 1 – Using Django and DRF to Build Modern Web Application

1

Setting Up Django with DRF

Technical requirements

Why Django?

What is available with Django?

What is the MVT framework?

Creating a “Hello World” web app with Django and DRF

Creating our Django hello_world project

Creating our first app in Django

Linking app views using urls.py

Integrating DRF

Creating RESTful API endpoints with DRF

Best practices for defining RESTful APIs

Best practices to create a REST API with DRF

Working with views using DRF

Functional views

Class-based views

Introducing API development tools

Summary

2

Exploring Django ORM, Models, and Migrations

Technical requirements

Setting up PostgreSQL with a Django project

Creating a PostgreSQL server

Configuring Django with PostgreSQL

Using models and Django ORM

Adding Django models

Basic ORM concepts

How to get raw queries from ORM

Normalization using Django ORM

Exploring on_delete options

Using model inheritance

Understanding the crux of Django migrations

Demystifying migration management commands

Performing database migrations like a pro

Exploring best practices for working with models and ORM

Use base models

Use timezone.now() for any DateTime-related data

How to avoid circular dependency in models

Define __str__ for all models

Use custom model methods

Keep the default primary key

Use transactions

Avoid generic foreign keys

Use finite state machines (FSMs)

Break the model into packages

Learning about performance optimization

Demystifying performance using explain and analyze

Using index

Using Django ORM like a pro

Database connection configuration

Exploring Django Async ORM

Summary

3

Serializing Data with DRF

Technical requirements

Understanding the basics of DRF Serializers

Using Model Serializers

Creating a new model object

Updating existing model Objects

Retrieving data from the Model object instance

Exploring the Meta class

Implementing Serializer relations

Working with nested Serializers

Exploring source

Exploring SerializerMethodField

Validating data with serializers

Customizing field-level validation

Defining a custom field-level validator

Performing object-level validation

Defining custom object-level validators

The order of the evaluation of validators

Remove default validators from the DRF Serializer class

Mastering DRF Serializers

Using source

Embracing SerializerMethodField

Using validators

Using to_internal_value

Using to_representation

Use a context argument to pass information

Customizing fields

Passing a custom QuerySet to PrimaryKeyField

Building DynamicFieldsSerializer

Avoiding the N+1 query problem

Using Serializers with DRF views

Working with generic views

Filtering with SearchFilter and OrderingFilter

Summary

4

Exploring Django Admin and Management Commands

Technical requirements

Exploring Django Admin

Creating a superuser in Django

Understanding the Django Admin interface

Customizing Django Admin

Adding custom fields

Using filter_horizontal

Using get_queryset

Using third-party packages and themes

Using Django Admin logs

Optimizing Django Admin for production

Renaming admin URLs

Using two-factor authentication (2FA) for admin users

Using Custom Admin Paginator

Disabling ForeignKey drop-down options

Using list_select_related

Overriding get_queryset for performance

Adding django-json-widget

Using custom actions

Using permissions for Django Admin

Creating custom management commands

Summary

5

Mastering Django Authentication and Authorization

Technical requirements

Learning the basics of Django authentication

Customizing the User model

Using a OneToOneField relationship with the User model

Using Django permissions and groups

Using permissions and groups in Django Admin

Creating custom permissions

Using Django permissions and groups for an API

Caveats of using permissions

Using DRF token-based authentication

Integrating token-based authentication into DRF

Adding DRF token-based authentication to a Django project

Understanding the limitations of token-based authentication of DRF

Learning about third-party token-based authentication packages

Integrating social login into Django and DRF

Summary

Part 2 – Using the Advanced Concepts of Django

6

Caching, Logging, and Throttling

Technical requirements

Caching with Django

Using django-cacheops

Best practices for caching in production

Throttling with Django

Best practices for throttling in production

Logging with Django

Setting up logging

Best practices for logging in production

Summary

7

Using Pagination, Django Signals, and Custom Middleware

Technical requirements

Paginating responses in Django and DRF

Understanding pagination

Using pagination in DRF

Demystifying Django signals

Creating custom signals

Working with signals in production

Working with Django middleware

Creating custom middleware

Summary

8

Using Celery with Django

Technical requirements

Asynchronous programming in Django

Using Celery with Django

Integrating Celery and Django

Interfaces of Celery

Best practices for using Celery

Using celery beat with Django

Summary

9

Writing Tests in Django

Technical requirements

Introducing the different types of tests in software development

Unit testing

Integration testing

E2E testing

Setting up tests for Django and DRF

Structuring and naming our test cases

Setting up a database for tests

Writing basic tests in DRF

Writing tests for advanced use cases

Using Django runners

Learning best practices to write tests

Using unit tests more often

Avoiding time bomb test failures

Avoiding brittle tests

Using a reverse function for URL path in tests

Using authentication tests

Using test tags to group tests

Using Postman to create an integration test suite

Creating different types of tests

Avoiding tests

Exploring Test-Driven Development

Summary

10

Exploring Conventions in Django

Technical requirements

Code structuring for Django projects

Creating files as per functionalities

Avoiding circular dependencies

Creating a “common” app

Working with a settings file for production

Working with exceptions and errors

Using feature flags

Configuring Django for production

Setting up CORS

Exploring WSGI

Summary

Part 3 – Dockerizing and Setting Up a CI Pipeline for Django Application

11

Dockerizing Django Applications

Technical requirements

Learning the basics of Docker

Installing Docker

Testing Docker on your local system

Important commands for Docker

Working with the requirements.txt file

Creating a Dockerfile for a Django project

Composing services using docker-compose.yaml

Creating a .env file

Accessing environment variables in Django

Starting a Django application using Docker

Summary

12

Working with Git and CI Pipelines Using Django

Technical requirements

Using Git efficiently

Branching strategy for Git

Following good practices while using git commit

Tools with Git

Integrating Git hooks into a Django project

Using lefthook

Using git merge versus git rebase

Performing code release

Performing hot-fixing on code

Working with GitHub and GitHub Actions

Working with GitHub Actions for the CI pipeline

Setting up a CI pipeline for Django using GitHub Actions

Recommended GitHub Actions resources

Setting up code review guidelines

Context and description

Short code changes to review

Review when the code is ready

Good code reviewer

Summary

Part 4 – Deploying and Monitoring Django Applications in Production

13

Deploying Django in AWS

Technical requirements

Learning the basics of AWS

Creating an account in AWS

Identity and Access Management

EC2

Elastic Load Balancer (ELB)

Elastic Beanstalk

RDS for Postgres

ElastiCache for Redis

Security groups and network components

AWS Secrets Manager

Route 53

The AWS Billing console

CloudWatch

Integrating AWS Elastic Beanstalk to deploy Django

Integrating Beanstalk with a basic Django app

Deploying a Django application using GitHub Actions in Elastic Beanstalk

Following the best practices for the AWS infrastructure

Best practices for RDS

Best practices for ElastiCache

Best practices for Elastic Beanstalk

Best practices for IAM and security

Summary

14

Monitoring Django Application

Technical requirements

Integrating error monitoring tools

Integrating Rollbar into a Django project

Integrating Rollbar with Slack

Best practices while working with error monitoring tools

Integrating uptime monitoring

Adding a health check endpoint

Using BetterStack for uptime monitoring

Integrating APM tools

Integrating New Relic into the Django project

Exploring the New Relic dashboard

Creating New Relic alert conditions

Monitoring AWS EC2 instances with New Relic

Sending logs from Django to New Relic

Working with metrics and events using NRQL

Integrating messaging tools using Slack

Handling production incidents better

Blameless RCA for incidents

Summary

Index

Other Books You May Enjoy

Part 1 – Using Django and DRF to Build Modern Web Application

In the first part of the book, we will get an overview of how to use Django and Django Rest Framework (DRF) to create a modern web application. We can expect to learn all the concepts related to Django ORM and DRF serializers, which are crucial to building any modern web application. Django Admin and Authentication are one of the most widely appreciated features of Django. We will learn all the best practices that a developer should know about before using Django and DRF in production.

This part has the following chapters:

Chapter 1, Setting Up Django with DRFChapter 2, Exploring Django ORM, Models, and MigrationsChapter 3, Serializing Data with DRFChapter 4, Exploring Django Admin and Management CommandsChapter 5, Mastering Django Authentication and Authorization