choosing a Python framework for web development

Many programmers cannot come to a single correct answer when arguing about which is better: C+ or Python, writing an application with programming skills, or creating a program out of the box. Today this debate has not bypassed us: Django or FastAPI? About the details of frameworks – Anastasia Ivanova, technical writer MTS Exolve (part of the MTS ecosystem).

What is this framework called Django?

Django appeared in 2005. Programmers Adrian Golovatti and Simon Willson named their framework Django after guitar virtuoso Django Reinhardt. This software platform was given its famous name for a reason.

Just as a virtuoso musician has hundreds of transitions in the playing melody and ways to perform technically complex musical transcriptions, so this platform carries all the tools necessary for a programmer. In the Django suite you will find:

  • ORM and directory structure;

  • admin panel;

  • HTML templates;

  • internationalization system, it adapts the framework to linguistic and cultural regions;

  • a web server for creating and testing application functionality along with an internal Python testing platform shell;

  • tools for product security against cross-site scripting and password hacking.

Django is built entirely in the Python programming language. The developers distribute this platform as open source. This light and fast framework. It is designed for developing dynamic websites.

Django Features

The barrier to entry for writing code in the Python programming language in the Django framework is much higher than that of FastAPI. First of all, you must have a good understanding of programming basics in Python. Without a foundation from this language, you won’t be able to learn Django.

Since Django is a query language, you should be able to work with lists, tuples, and iterating over objects. Without them, you’ll have problems with query sets.

Functions, decorators, classes, packages – these are all things you need to know to write code in Django. All of the above constitute the fundamental foundations of the Python programming language.

In most cases, young developers and newbies to programming don’t want to bother learning all the Django tools. They choose the simpler and lighter FastAPI.

Django’s architecture is built on independent parts. Any module can be replaced and modified without affecting the others. The Django architecture model is built on three elements:

  • model. This is a set of methods and limits for working with data;

  • performance. This element shows the developer how information is displayed based on code changes;

  • controller. It processes the programmer’s actions and tells the model how it should change.

Another virtuosity of the Django platform lies in the way it works. Website developers use the DRY model when writing code. Don’t Repeat Yourself, translation – “Don’t repeat yourself”). The result is dry program code that is easy to read and expand.

The framework is completely universal. This means that you can develop websites and applications like:

  • video hosting;

  • social networks;

  • news resources.

This library is used by programmers from large companies: Pinterest, Spotify, Reddit and YouTube.

The platform developers update it monthly, check for errors, correct and stabilize its operation.

Advantages and disadvantages of the Django framework

pros

Minuses

Safe

High entry threshold

Scalable. The platform can withstand a large influx of traffic

Not used for developing small projects due to the fact that it is a high-level framework

Ability to use many plugins for customization

No support for multiple requests. Because of this, when adding a large number of plugins, the site may work slowly because it will not have enough speed to process many requests

SEO plugins, in particular the robot.txt tool. It improves search engine optimization

Django works most transparently with PostgreSQL and MySQL. With other databases, ORM functions may be less functional.

A community that helps the programmer while working

Unlike FastAPI, this framework is difficult to configure for developing an application interface using JSON

Some of Django’s little-noticed features:

  • object-relational mapping (ORM);

  • built-in authentication system;

  • administrative interface for managing application data;

  • software support for processing requests and responses;

  • template system for rendering HTML pages.

What is FastAPI

FastAPI is a fairly new and minimalistic platform. She was born in 2018. The framework is compatible with Python versions 3.6 and higher. Unlike the heavy and voluminous Django, this platform is easy to deploy, it is easier for beginners to understand, and this can be done in literally one month.

The FastAPI base is built on two libraries:

  • Starlette. This is an ASGI framework. It is needed for interaction between the client application and the web server;

  • Pydantic. It is needed to describe data schemas.

The framework actively uses decorators and annotations, which significantly reduces the weight and amount of boilerplate code.

Features of FastAPI

One of the features of FastAPI is the processing of multiple requests. The platform also benefits in the speed of project deployment. A programmer can deploy his work in five lines of code.

FastAPI offers many different features that are incredibly useful for creating APIs:

  • high performance thanks to asynchronous code;

  • automatic generation of API documentation using Swagger UI;

  • support for JSON and OpenAPI formats;

  • built-in testing tools for unit and integration testing.

Important: fast FastAPI, which according to benchmark tests showed superior to Django and Flask, considered the most popular framework for creating REST services. The ability to process asynchronous requests is the main advantage of FastAPI over other frameworks.

FastAPI is used to work on programs that require speed and asynchronous data processing. These include:

Advantages and disadvantages of the FastAPI framework

pros

Minuses

Popularity

Small community

Ease of learning

Few developments

Asynchronous processing

No built-in security system

There are no specific rules that would limit a developer from writing code

Few third-party plugins and extensions due to the fact that the framework is quite young

NoSQL database support

There is no built-in support for handling database schema migration. This is an important aspect for database management in production areas. You’ll have to use third party tools like Alembic or Django’s migration system

How Django works with communication APIs

Django and FastAPI can be used in the context of working with communication APIs like MTS Exolve to create web applications with functions for sending SMS, instant messages (chat), email and many others.

Let’s look at a code example for sending notifications using the Django framework. To do this, we need the requests library to send a POST request to the API. Please note that this is just a basic example and you may need additional customization depending on your specific case.

Install the requests library if it doesn’t already exist by running the command:

$ -m pip install requests

Create a Django view that will handle sending notifications:

# Your views.py

import json

import requests

from django.http import JsonResponse

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt # Disabling CSRF protection to simplify the example, it is better to use token validation

def send_notification(request):

if request method == 'POST':

# Here get the necessary data from the request, for example, phone number and notification text

phone_number = request.POST.get('phone_number’)

message = request.POST.get(‘message’)

# Replace with your API URL

api_url = ‘https://example.com/api/send_notification’

# Replace with your API token

api_token = 'your_api_token_here'

 

headers

‘Authorization‘: fBearer {apl_token}‘,

‘Content-Type‘:‘application/json’

}

data = {

‘phone_number': phone_number,

‘message’: message

}

response = requests post(api_uri, data=json.dumps(data), headers=headers)

ifresponse status_code == 200:

return JsonResponse({'status’ ‘success’, ‘message’ ‘Notification sent’})

else:

return JsonResponse({‘status’: ‘error’, ‘message’: ‘Falled to send notification’})

retum JsonResponse({‘status’: ‘error’, ‘message’: ’Invalid request method’})

Create a URL route for your view:

# Your urls.py

from django.uris import path

from . import views

uripatterns = [

path(‘send-notification/’, views.send_notification, name="send-notification’),

# Другие URL-маршруты…

]

It is clear that the code can be made shorter, but it will do for the example. Please note that you will need to configure the api_url and api_token according to your API access credentials. Also for implementation SMS APIYou may find Redis Queue useful for queuing jobs; this library is easy to integrate into your web stack.

Don’t forget to also add the necessary logic to receive data from the client and to handle errors. This code is intended as a starting point only and requires further development and testing.

To illustrate the differences between Django and FastAPI, let’s look at how to create a simple API with a different framework:

from fastapi import FastAPI

from pydantic import BaseModel

app = FastAPI()

class HelloRequest(BaseModel):

    name: str

@app.post("/hello")

def hello(request: HelloRequest):

    return {"message": f"Hello, {request.name}!

In this example, we define a FastAPI application with a single route that accepts a POST request with JSON. He responds with a message with a name. As you can see, the FastAPI example is much simpler than Django’s due to its focus on creating APIs.

conclusions

On GitHub Django earned 72,000 stars, and FastAPI — 60,900 stars. This can be interpreted as a victory for Django, despite the difficulty in learning and heaviness.

Parameter

Django

FastAPI

Complexity

+

Flexibility

+

Safety

+

Ability to develop Rest API

+

If you want to write a small application, have a limited budget and do not have servers to deploy a heavy framework, choose FastAPI. Since for small programs the use of large servers will be redundant.

To create a powerful and large-scale service and work with communications through MTS Exolve Django will do.

Thank you for your time for this article! What do you think is better, Django or FastAPI? Share your opinion in the comments to the article!

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *