04-Django Adv

Throttling - API rate limiting

Throttling

API rate limiting is a technique used to control the number of requests a user or client can make to an API within a specific time frame. In Django, you can implement rate limiting using third-party libraries like Django REST Framework’s (DRF) throttling or by integrating specialized libraries like django-ratelimit.

4.1 Using Django REST Framework (DRF) Throttling

DRF provides built-in throttling classes to enforce rate limits.

Period should be one of: (’s’, ‘sec’, ’m’, ‘min’, ‘h’, ‘hour’, ’d’, ‘day’)

[Read More]

03-Django Adv

Logging Works in Django

Logger

Print statement generally does not work in production so, to get message we use logger

What is Logging?

How Logging Works in Django

  • Django comes with Python's built-in logging module to leverage system logging.
    1. Loggers
    2. Handlers
    3. Filters
    4. Formatters

Loggers

  • Loggers are basically the entry point of the logging system.
  • If the log-level is same or exceeds the log-level of the logger, the message is sent to the handler for further processing.
DEBUG:		     10 --> Low-level system information
INFO:		     20 --> General system information
WARNING:	     30 --> Minor problems related information
ERROR/EXCEPTION: 40 --> Major problems related information
CRITICAL:	     50 --> Critical problems related information
dblogger.debug("Test Debug")

dblogger.info("Test Info")

dblogger.warning("Test Warning")
dblogger.warn("Test Warn")  # Depricated

dblogger.error("Test Error")
dblogger.exception("Test Exception")

dblogger.critical("Test Critical")

Handlers

Handlers basically determine what happens to each message in a logger eg: write to a file or console.

[Read More]

03-Django Adv

𝗖𝗿𝗼𝘀𝘀-𝗢𝗿𝗶𝗴𝗶𝗻 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 𝗦𝗵𝗮𝗿𝗶𝗻𝗴 (𝗖𝗢𝗥𝗦)

𝗖𝗿𝗼𝘀𝘀-𝗢𝗿𝗶𝗴𝗶𝗻 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲 𝗦𝗵𝗮𝗿𝗶𝗻𝗴 (𝗖𝗢𝗥𝗦)

CORS is a security mechanism enforced by web browsers to restrict cross-origin HTTP requests.

CORS is a mechanism implemented by browsers that block websites to request data from some other URL. When a browser makes a request, it adds an origin header to the request message. If it goes to the server of the exact origin, it is allowed by the browser; if it does not, the browser blocks it. gets error like Cross-Origin Request Blocked

[Read More]

01-Django Adv

Django postgres full text search

  • Unlike relational databases, full-text search is not standardized.
  • There are several open-source options like ElasticSearch, Solr, and Xapian.
  • For general uses
    • We can stick with the full-text search capabilities that many relational (like Postgres, MySQL, SQLite)
    • And non-relational databases (like MongoDB and CouchDB) offer.
  • In Django you’ll typically start by performing search queries with contains or icontains for exact matches.
  • The Q object can be used as well to add AND (&) or OR (|) logical operators.
  • Limitations
    • Only exact match is shown –> similar words excluded
    • Stop word(article) all has same weight
    • complex lookups not possible
from django.db.models import Q

ProductDetail.objects.filter(Q(name__icontains=query))

Quote.objects.filter(Q(name__icontains=query) | Q(quote__icontains=query))
  • Eg:
    • query = pony
    • then ponies != pony
  • To use the search lookup, django.contrib.postgres must be in your INSTALLED_APPS.
  • Used for Single Field Search
  • Advantage
    • It takes similar words into account
      • ponies, pony
INSTALLED_APPS += ['django.contrib.postgres']

ProductDetail.objects.filter(name__search=query)

SearchVector

  • To search against multiple fields and on related models, you can use the SearchVector
Entry.objects.annotate(search=SearchVector('body_text') + SearchVector('blog__tagline')).filter(search=query)

Quote.objects.annotate(search=SearchVector("name", "quote")).filter(search=query)

SearchQuery

SearchQuery translates the terms the user provides into a search query object that the database compares to a search vector. By default, all the words the user provides are passed through the stemming algorithms, and then it looks for matches for all of the resulting terms.

[Read More]

9. TokenAuthentication

Django-rest-auth, Dj-rest-auth

9. TokenAuthentication

The token authentication works by exchanging username and password for a token that will be used in all subsequent requests so to identify the user on the server side.

Token authentication is suitable for client-server applications, where the token is safely stored. You should never expose your token, as it would be (sort of) equivalent of a handing out your username and password.

[Read More]

6. DRF ViewSets & Routers

ViewSet, ModelViewSet, ReadOnlyModelViewSet, GenericViewSet

6.1 ViewSets

ViewSet classes are almost the same thing as View classes, except that they provide operations such as retrieve, or update, and not method handlers such as get or put.

In other word ViewSet class is simply a type of class-based View, that does not provide any method handlers such as .get() or .post(), and instead provides operations/actions such as .list() and .create().

[Read More]

4. DRF Function based View

Requests and Responses, Function based View

Request Object

REST framework introduces a Request object that extends the regular HttpRequest, and provides more flexible request parsing.

The core functionality of the Request object is the request.data attribute, which is similar to request.POST, but more useful for working with Web APIs.

  • request.POST
    • Only handles form data.
    • Only works for 'POST' method.
  • request.data
    • Handles arbitrary data.
    • Works for ‘POST’, ‘PUT’ and ‘PATCH’ methods.
[Read More]