Reader small image

You're reading from  Django in Production

Product typeBook
Published inApr 2024
Reading LevelIntermediate
PublisherPackt
ISBN-139781804610480
Edition1st Edition
Languages
Tools
Right arrow
Author (1)
Arghya Saha
Arghya Saha
author image
Arghya Saha

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.
Read more about Arghya Saha

Right arrow

Exploring Conventions in Django

In previous chapters, we learned about the different features of Django and how you can utilize these features to build a scalable Django application. Django is considered to be opinionated; it doesn’t give a lot of flexibility to developers. Being opinionated has led to a love-hate relationship between Django and the developer community, where a lot of developers love the fact that Django has a particular way of performing certain implementations and developers do not have to think too much about how to use Django to build a web service. However, many developers don’t like Django due to the lack of flexibility and its being too rigid about how a particular code should be written.

In this chapter, we will learn about certain conventions you can follow while working with Django. You should note that this chapter contains a lot of opinionated concepts that I have learned while working on numerous Django projects and consulting for different...

Technical requirements

We will learn the conventions of different Django topics we have covered so far in this book. You should be well versed in all the topics explained in earlier chapters.

Here is the GitHub repository that has all the code and instructions for this chapter: https://github.com/PacktPublishing/Django-in-Production/tree/main/Chapter10.

Code structuring for Django projects

When we start a new project in Django, the Django management command creates the basic files needed to create our Django project. In Chapter 1, we learned how we can set up our Django project and create different Django apps. In this section, we shall collate all the information we have gathered in previous chapters on using different files for different purposes in Django.

Creating files as per functionalities

As a first step in bifurcation, we have already learned that we should create multiple Django apps in our Django project. The splitting of a Django app depends on the business logic functionalities; for example, our blogging project can have blog and author as two different Django apps. Inside each app, we would split our code into multiple files. Here is the recommended list of files we should consider while working on Django:

  • urls.py: Each Django application should have a urls.py file that contains all the routing logic for...

Working with exceptions and errors

Developers should always think through all the corner cases possible and write code to handle all those corner cases. Unfortunately, bugs, exceptions, and errors can still slip into production, leading to our users having a bad experience. We have already learned, in Chapter 9, how test cases can help us catch these errors better in the development phase itself, and to improve the user experience, we should show appropriate error messages whenever something breaks. For example, if the server is expecting name to be present in the body of the request and it is missing, then we should send an error message explicitly saying name field is missing.

Here are a few important points we should follow while handling exceptions and errors:

  • Always send the appropriate status code. If the request body is missing certain information, then pass 400 and then pass a message explaining the missing information.
  • If the error is an authentication error...

Using feature flags

A feature flag is a technique to enable or disable certain functionalities in code during runtime without deploying new code. This helps developers to toggle different features in production at a much faster rate. For example, if a company has incorporated Stripe and PayPal payment gateways for payments in their app, but for some reason Stripe is down, then the team can quickly change their payment gateway to PayPal without any code change or deployment. This is very common for critical systems and also while building new systems.

In the following example code, we are storing the payment gateway configuration in our KeyValueStore database table. This helps us to control the payment gateway at runtime. KeyValueStore is a database model that is stored in the common/models.py file:

class KeyValueStore(models.Model):
    key = models.CharField(max_length=255, unique=True)
    value = models.JSONField()
   ...

Configuring Django for production

In this section, we will learn about a few key configurations we need to set before deploying to production. We will first discuss the configuration we need to update the settings.py file:

  • Update the SECRET_KEY value and pass it via the environment variable
  • Set DEBUG = False for production so that sensitive information via an error stacktrace is not shown, whenever there is an error in the Django app
  • Set ALLOWED_HOSTS = ["dip.com", "xyz.com"], and list all the domains that the Django project would be served on
  • Set APPEND_SLASH = True so that if any request is missing a slash at the end, Django can add a slash automatically
  • Set TIME_ZONE appropriately

There are a few more configurations that you can update in the Django settings. They depend on the Django project use case. Apart from the preceding mentioned settings, let’s learn about a couple of other configurations we need to perform:

    ...

Summary

In this chapter, we learned about different conventions we can implement in our Django project. We learned how we can create different files in our Django project and structure them properly to write scalable and maintainable code, as well as avoiding circular dependency errors as our project expands. Exception and error handling is an important concept that we have learned about in this chapter. We understood how error codes can help us debug properly in production.

We saw how feature flags can help us to have better control over our code and enable/disable certain functionalities during runtime without requiring any additional deployment of code to our servers. Then, we saw some tips and tricks to configure our Django application before deploying it to production. CORS and WSGI are critical specifications for web development, and we learned about them, as well as the django-cors-headers and gunicorn packages, in this chapter. We also learned about application development...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Django in Production
Published in: Apr 2024Publisher: PacktISBN-13: 9781804610480
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Arghya Saha

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.
Read more about Arghya Saha