<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by devang hingu on Medium]]></title>
        <description><![CDATA[Stories by devang hingu on Medium]]></description>
        <link>https://medium.com/@devang.hingu?source=rss-140605ee5e4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lfY3kqj-CSDsXMrMiU3STw.gif</url>
            <title>Stories by devang hingu on Medium</title>
            <link>https://medium.com/@devang.hingu?source=rss-140605ee5e4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:28:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@devang.hingu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The top 1% Technique: The Secret Weapon That Power Frameworks Like Django and SQLAlchemy]]></title>
            <link>https://medium.com/@devang.hingu/the-top-1-technique-the-secret-weapon-that-power-frameworks-like-django-and-sqlalchemy-69587844f78d?source=rss-140605ee5e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/69587844f78d</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sqlalchemy]]></category>
            <dc:creator><![CDATA[devang hingu]]></dc:creator>
            <pubDate>Thu, 28 Aug 2025 15:49:23 GMT</pubDate>
            <atom:updated>2025-08-28T16:44:13.226Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*6rnK6H1OEJ5tTqGwd7N8Xg.png" /></figure><p><strong>Ever wonder how Django and SQLAlchemy make Python feel like magic?</strong></p><p>You write user.name or session.query(User), and somehow, validation, lazy loading, and database magic just <em>happen</em>.</p><p>What if I told you this &quot;magic&quot; isn’t magic at all?</p><p>It’s a secret weapon hidden in plain sight: <strong>Python descriptors</strong>.</p><p>Most developers use them daily without realizing it. But the top 1%? They <em>weaponize</em> descriptors to build frameworks, slash boilerplate, and write code that feels like cheating.</p><p>In this deep dive, I’ll pull back the curtain on the technique that separates senior engineers from the rest. No fluff — just battle-tested patterns you can steal to level up your Python architecture, starting today.</p><h3>What Are Descriptors and Why Should You Care?</h3><p>If you’ve used Python for any length of time, you’ve definitely used descriptors, even if you didn’t realize it.</p><p>Properties, methods, class methods, static methods — they’re all implemented using descriptors. But what exactly are they?</p><p>In the simplest terms, a descriptor is an object attribute with “<strong>binding behavior,</strong>” one whose attribute access has been overridden by three special methods. These methods are __get__() __set__(), and __delete__(). If any of these methods are defined for an object, it’s said to be a descriptor.</p><p>Here’s where it gets interesting: <strong>descriptors give you complete control over how attributes are accessed, modified, and deleted. This isn’t just syntactic sugar — it’s a fundamental building block of Pyt</strong>hon’s object model that allows for incredibly elegant and powerful designs.</p><h3>The Descriptor Protocol Deep Dive</h3><p>Let’s roll up our sleeves and look at the descriptor protocol in detail:</p><pre>class Descriptor:<br>    def __get__(self, obj, obj_type=None):<br>        # called when the descriptor accessed<br>        pass<br>    <br>    def __set__(self, obj, value):<br>        #called when the descriptor is assigned to<br>        pass<br>    <br>    def __delete__(self, obj):<br>        # called the descriptor when it&#39;is deleted<br>        pass</pre><p>The magic happens in how Python resolves attribute access. When you access an attribute on an object (e.g., <strong>obj.attr</strong>), Python follows this lookup chain:</p><ol><li>Check if the attribute is a data descriptor in the class of the object</li><li>Check if the attribute exists in the object’s __dict__</li><li>Check if the attribute is a non-data descriptor in the class of the object</li><li>Check if the attribute exists in the parent classes</li><li>Raise AttributeError if not found</li></ol><p>the distinction between data descriptors (those with <strong>__set__</strong> or <strong>__delete__</strong>) and non-data descriptors (those with only <strong>__get__</strong>) is crucial. Data descriptors take precedence over instance attributes, while instance attributes take precedence over non-data descriptors.</p><h3>Practical Magic: Building a Validation Framework</h3><p>Let’s put theory into practice, here i will show you how to build a validation framework using descriptors that will make your code cleaner, more maintainable, and more robust.</p><pre>class ValidatedAttribute:<br>    def __init__(self, validator=None, default=None):<br>        self.validator = validator<br>        self.default = default<br>        self._name = None<br>    <br>    def __set_name__(self, owner, name):<br>        self._name = f&quot;_{name}&quot;<br>    <br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        return getattr(obj, self._name, self.default)<br>    <br>    def __set__(self, obj, value):<br>        if self.validator and not self.validator(value):<br>            raise ValueError(f&quot;Invalid value for {self._name[1:]}: {value}&quot;)<br>        setattr(obj, self._name, value)<br>    <br>    def __delete__(self, obj):<br>        if hasattr(obj, self._name):<br>            delattr(obj, self._name)<br><br>def is_positive(value):<br>    return isinstance(value, (int, float)) and value &gt; 0<br><br>def is_email(value):<br>    return isinstance(value, str) and &quot;@&quot; in value and &quot;.&quot; in value.split(&quot;@&quot;)[-1]<br><br>class User:<br>    age = ValidatedAttribute(validator=is_positive, default=18)<br>    email = ValidatedAttribute(validator=is_email)<br>    <br>    def __init__(self, email, age=None):<br>        self.email = email<br>        if age is not None:<br>            self.age = age<br><br>#Usage<br>try:<br>    user = User(&quot;invalid-email&quot;, -5)<br>except ValueError as e:<br>    print(e)  #print -&gt; &quot;invalid value for email: invalid-email&quot;</pre><p>notice how clean the User class is? All the validation logic is encapsulated in the descriptor, making it reusable across multiple classes. This is the power of descriptors — they allow you to extract cross-cutting concerns into reusable components.</p><h3>Advanced Descriptor Patterns</h3><p>Let’s explore some advanced patterns that showcase the true power of descriptors.</p><h4>Lazy Loading with Descriptors</h4><pre>class LazyProperty:<br>    def __init__(self, func):<br>        self._func = func<br>        self._name = func.__name__<br>    <br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        value = self._func(obj)<br>        setattr(obj, self._name, value)<br>        return value<br><br>class DataProcessor:<br>    def __init__(self, data):<br>        self.data = data<br>    <br>    @LazyProperty<br>    def processed_data(self):<br>        print(&quot;expensive computation happening.&quot;)<br>        # simulate expensive processing<br>        result = [x * 2 for x in self.data]<br>        return result<br><br>#Usage<br>processor = DataProcessor([1, 2, 3])<br>print(&quot;Processor created&quot;)<br>print(processor.processed_data)  # &quot;huge computation happen...&quot; then [2,4,6]<br>print(processor.processed_data)  # [2,4,6] (no computation this time)</pre><p>This pattern is very useful for expensive computations that should only be performed when needed and then cached for future access.</p><h4>Cached Methods with Expiration</h4><pre>import time<br><br>class CachedMethod:<br>    def __init__(self, ttl=60):<br>        self.ttl = ttl  # Time to live in seconds<br>        self._cache = {}<br>    <br>    def __call__(self, func):<br>        self._func = func<br>        return self<br>    <br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        <br>        def wrapper(*args, **kwargs):<br>            # Create a cache key based on the method name and arguments<br>            key = (self._func.__name__, args, frozenset(kwargs.items()))<br>            <br>            #check if we have a cached result and if it;s still valid<br>            if key in self._cache:<br>                result, timestamp = self._cache[key]<br>                if time.time() - timestamp &lt; self.ttl:<br>                    return result<br>            <br>            #process the result and cache it<br>            result = self._func(obj, *args, **kwargs)<br>            self._cache[key] = (result, time.time())<br>            return result<br>        <br>        return wrapper<br><br>class API:<br>    @CachedMethod(ttl=30)  # cache data till 30 seconds<br>    def get_user_data(self, user_id):<br>        print(f&quot;Fetching data for user {user_id}...&quot;)<br>        # Simulate API call<br>        time.sleep(1)<br>        return {&quot;user_id&quot;: user_id, &quot;data&quot;: &quot;some data&quot;}<br><br># usage<br>api = API()<br>print(api.get_user_data(123))  # &quot;fetching data....&quot; then the data<br>print(api.get_user_data(123))  # returns cached data immediately<br>time.sleep(31)<br>print(api.get_user_data(123))  # &quot;fetching data...&quot; again (cache has expired)</pre><p>This pattern is perfect for caching results of expensive operations like API calls, database queries, or complex computations.</p><h3>Descriptors vs. Properties: What’s the Difference?</h3><p>Many developers wonder why they should use descriptors when properties seem to do something similar. The key difference is re-usability. Properties are defined per class, while descriptors are reusable across multiple classes.</p><p>Consider this example:</p><pre># Using properties<br>class Person:<br>    def __init__(self, name):<br>        self._name = name<br>    <br>    @property<br>    def name(self):<br>        return self._name.title()<br>    <br>    @name.setter<br>    def name(self, value):<br>        if not isinstance(value, str):<br>            raise TypeError(&quot;Name must be in a string&quot;)<br>        self._name = value<br><br>class Product:<br>    def __init__(self, name):<br>        self._name = name<br>    <br>    @property<br>    def name(self):<br>        return self._name.title()<br>    <br>    @name.setter<br>    def name(self, value):<br>        if not isinstance(value, str):<br>            raise TypeError(&quot;Name must be in string&quot;)<br>        self._name = value</pre><p>Notice the duplication? Now let’s see how descriptors solve this:</p><pre>class NameAttribute:<br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        return obj._name.title()<br>    <br>    def __set__(self, obj, value):<br>        if not isinstance(value, str):<br>            raise TypeError(&quot;Name must be a string&quot;)<br>        obj._name = value<br><br>class Person:<br>    name = NameAttribute()<br>    <br>    def __init__(self, name):<br>        self._name = name<br><br>class Product:<br>    name = NameAttribute()<br>    <br>    def __init__(self, name):<br>        self._name = name</pre><p>Much cleaner and more maintainable!</p><h3>Descriptors in the Wild: Real-World Examples</h3><p>Descriptors aren’t just academic exercises — they’re used extensively in Python’s standard library and popular frameworks.</p><h3>SQLAlchemy’s ORM</h3><p>SQLAlchemy uses descriptors extensively for its ORM. When you define a column:</p><pre>class User(Base):<br>    __tablename__ = &#39;users&#39;<br>    <br>    id = Column(Integer, primary_key=True)<br>    name = Column(String)</pre><p>Those <strong>Column</strong> objects are descriptors that handle the translation between Python objects and database rows.</p><h3>Django’s ORM</h3><p>Similarly, Django uses descriptors for its model fields:</p><pre>class Person(models.Model):<br>    first_name = models.CharField(max_length=30)<br>    last_name = models.CharField(max_length=30)</pre><p>models.CharField is a descriptor that handles validation, database conversion, and more.</p><h3>Python’s <strong><em>property</em></strong></h3><p>Even Python’s built-in <strong><em>property</em></strong> is implemented using descriptors. In fact, it’s just a convenient way to create a data descriptor without having to define a full class.</p><h3>Performance Considerations</h3><p>One concern that often comes up with descriptors is performance. While it’s true that descriptor access is slightly slower than direct attribute access, the difference is negligible in most applications.</p><p>Let’s benchmark it:</p><pre>import timeit<br><br>class DirectAccess:<br>    def __init__(self):<br>        self.value = 42<br><br>class DescriptorAccess:<br>    def __init__(self):<br>        self._value = 42<br>    <br>    @property<br>    def value(self):<br>        return self._value<br>    <br>    @value.setter<br>    def value(self, v):<br>        self._value = v<br><br>direct = DirectAccess()<br>descriptor = DescriptorAccess()<br><br># Test direct access<br>direct_time = timeit.timeit(&#39;direct.value&#39;, globals=globals(), number=1000000)<br><br># Test descriptor access<br>descriptor_time = timeit.timeit(&#39;descriptor.value&#39;, globals=globals(), number=1000000)<br><br>print(f&quot;Direct access: {direct_time:.6f} seconds&quot;)<br>print(f&quot;Descriptor access: {descriptor_time:.6f} seconds&quot;)<br>print(f&quot;Ratio: {descriptor_time / direct_time:.2f}x slower&quot;)</pre><p>On my machine, descriptor access is about <strong>2–3x slower</strong> than direct access. While this sounds significant, remember that we’re doing a million accesses. In real-world applications, the benefits of descriptors often far outweigh this small performance cost.</p><h3>Common Pitfalls and How to Avoid Them</h3><p>After years of working with descriptors, I’ve seen developers make the same mistakes repeatedly. Here are the most common pitfalls and how to avoid them:</p><h3>1. Forgetting __set_name__</h3><p>In Python 3.6+, the <strong>__set_name__</strong> method is called automatically when a descriptor is created in a class definition. It’s essential for capturing the name of the attribute the descriptor is assigned to.</p><pre>class MyDescriptor:<br>    def __set_name__(self, owner, name):<br>        self.name = name  # save the attribute name<br>    <br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        return f&quot;Value of {self.name}&quot;</pre><h3>2. Mishandling instance vs. class access</h3><p>A common mistake is not properly handling the case when a descriptor is accessed on the class rather than an instance:</p><pre>class BrokenDescriptor:<br>    def __get__(self, obj, obj_type=None):<br>        return obj.some_attr  # this will fail if obj is None<br><br>class WorkingDescriptor:<br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self  # return the descriptor itself<br>        return obj.some_attr</pre><h3>3. Storing state in the descriptor itself</h3><p>Remember that descriptors are created once when the class is defined, not once per instance. If you need to store instance-specific state, store it in the instance:</p><pre>class WrongDescriptor:<br>    def __init__(self, default):<br>        self.value = default  # this is shared across all instances!<br>    <br>    def __get__(self, obj, obj_type=None):<br>        return self.value<br>    <br>    def __set__(self, obj, value):<br>        self.value = value  #this affects all instances!<br><br>class RightDescriptor:<br>    def __init__(self, default):<br>        self.default = default<br>    <br>    def __set_name__(self, owner, name):<br>        self.name = f&quot;_{name}&quot;<br>    <br>    def __get__(self, obj, obj_type=None):<br>        if obj is None:<br>            return self<br>        return getattr(obj, self.name, self.default)<br>    <br>    def __set__(self, obj, value):<br>        setattr(obj, self.name, value)  #store in the instance</pre><h3>Closing Thoughts: The Real Magic</h3><p>Descriptors aren’t an obscure trick. They’re a <strong>core part of Python’s design</strong>.</p><p>Once you understand them, you’ll see how <strong>Django</strong> and <strong>SQLAlchemy</strong> weave their magic — and you’ll realize you can do the same.</p><p>Start with something small, like validation or lazy loading. Then level up to caching, proxying, or even ORM-like abstractions.</p><p>Because the real magic of Python isn’t hidden in its frameworks.<br> It’s built right into the language — waiting for you to use it.</p><p><strong>Happy coding.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69587844f78d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Made My Django Rest API 3x Faster]]></title>
            <link>https://medium.com/@devang.hingu/how-i-made-my-django-rest-api-3x-faster-0f4733ee567b?source=rss-140605ee5e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0f4733ee567b</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[api-optimization]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[devang hingu]]></dc:creator>
            <pubDate>Tue, 19 Aug 2025 13:43:25 GMT</pubDate>
            <atom:updated>2025-08-19T13:43:25.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCwvP9mUQHBRcF5Aa5n-zw.png" /></figure><p>As a backend engineer, I’ve seen firsthand how a poorly optimized Django API can cripple an application. The good news is that many of the biggest performance gains come from applying a few core, battle-tested techniques.</p><p>Let’s dive into these strategies with concrete examples you can implement today to make your API faster, more efficient, and more scalable.</p><h3>1. Database Query Optimization (The Biggest Wins)</h3><p>The database is almost always the source of performance issues. By reducing the number of queries and the amount of data transferred, you can achieve massive improvements.</p><h4>Problem: The N+1 Query Problem</h4><p>This classic issue occurs when you execute a query to get a list of objects and then loop through that list, running a separate query for each object to fetch related data, and this will be expensive in terms of database transaction</p><pre># BAD: Triggers N+1 queries<br>authors = Author.objects.all()<br>for author in authors:<br>    # A new query is run for each author to get their books!<br>    print(author.books.all())</pre><h4>Solution: Use select_related and prefetch_related</h4><p>These two methods are your best friends for solving N+1 queries so data will fetch in single transaction instead of multiple transaction.</p><ul><li><strong>select_related</strong> is for <strong>one-to-one</strong> or <strong>many-to-one</strong> relationships (like a ForeignKey). It performs a single JOIN at the database level, fetching the related object&#39;s data in the initial query.</li><li><strong>prefetch_related</strong> is for <strong>many-to-many</strong> or <strong>reverse </strong><strong>ForeignKey</strong> relationships. It performs a separate query for each related table and then joins them together in Python, avoiding N+1.</li></ul><pre># GOOD: Uses a single JOIN to fetch publisher data<br># &#39;publisher&#39; is a ForeignKey on the Author model<br>authors = Author.objects.select_related(&#39;publisher&#39;).all()<br><br># GOOD: Runs two queries (one for authors, one for all related books)<br># &#39;books&#39; is a ManyToMany or reverse ForeignKey on the Author model<br>authors = Author.objects.prefetch_related(&#39;books&#39;).all()</pre><h3>Problem: Over-fetching Data</h3><p>By default, objects.all() fetches <strong>every column for every row</strong>. If you only need a few fields, you&#39;re transferring a lot of unnecessary data.</p><h4>Solution: Use only() or defer()</h4><ul><li><strong>only()</strong> specifies the exact fields you want to retrieve. All other fields will be lazily loaded with a separate query if you try to access them later.</li><li><strong>defer()</strong> specifies the fields you want to <strong>exclude</strong>. All other fields will be loaded normally. Use this for fields that are very large (e.g., a text-heavy content field).</li></ul><pre># GOOD: Only fetches &#39;title&#39; and &#39;author_id&#39; from the database<br>books = Book.objects.only(&#39;title&#39;, &#39;author_id&#39;).all()<br><br># GOOD: Defer loading the &#39;content&#39; and &#39;metadata&#39; fields<br># They will be fetched from the database only if you access them<br>books = Book.objects.defer(&#39;content&#39;, &#39;metadata&#39;).all()# GOOD: Only fetches &#39;title&#39; and &#39;author_id&#39; from the database<br>books = Book.objects.only(&#39;title&#39;, &#39;author_id&#39;).all()</pre><h4>Problem: Inefficient Filtering in Python</h4><p>Filtering data in Python after fetching everything from the database is highly inefficient, especially for large datasets.</p><pre># BAD: Fetches ALL books, then filters in Python<br>recent_books = [b for b in Book.objects.all() if b.publish_date &gt; &#39;2023-01-01&#39;]</pre><h4>Solution: Database-Level Filtering</h4><p>Let the database do the work. It’s built for it and is far more efficient at filtering large amounts of data.</p><pre><br># GOOD: The database handles the filtering efficiently<br>from datetime import date<br>recent_books = Book.objects.filter(publish_date__gt=date(2023, 1, 1))</pre><h3>2. Serializer Optimization (DRF Specific)</h3><p>The Django Rest Framework (DRF) is powerful but can introduce performance overhead if not used correctly.</p><h4>Problem: Nested Serialization Overhead</h4><p>Nested serializers can inadvertently trigger N+1 queries. If you have an AuthorSerializer that includes a BookSerializer for each book, you can end up with the same N+1 problem we just discussed.</p><pre># BAD: Triggers N+1 queries for books<br>class AuthorSerializer(serializers.ModelSerializer):<br>    books = BookSerializer(many=True)<br><br>    class Meta:<br>        model = Author<br>        fields = [&#39;name&#39;, &#39;books&#39;]</pre><h4>Solution: Prefetch + Selective Fields</h4><p>A common and efficient pattern is to <strong>prefetch</strong> the related data at the query level and then use a PrimaryKeyRelatedField in the serializer to display just the IDs. This provides the necessary data in an efficient way without over-fetching or creating extra queries in the serializer.</p><pre># GOOD: Prefetch related books and only fetch the author&#39;s &#39;name&#39;<br>queryset = Author.objects.prefetch_related(&#39;books&#39;).only(&#39;name&#39;)<br><br># GOOD: Use a PrimaryKeyRelatedField for books in the serializer<br>class AuthorSerializer(serializers.ModelSerializer):<br>    # This just shows the book IDs; it doesn&#39;t run a new query<br>    books = serializers.PrimaryKeyRelatedField(many=True, read_only=True)<br><br>    class Meta:<br>        model = Author<br>        fields = [&#39;name&#39;, &#39;books&#39;]</pre><h4>Problem: Heavy Calculations in Serializers</h4><p>Placing expensive operations, like a word count for a large body of text, inside a serializer’s SerializerMethodField can be very slow as it&#39;s run for every object.</p><pre># BAD: Expensive operation per object<br>class BookSerializer(serializers.ModelSerializer):<br>    word_count = serializers.SerializerMethodField()<br><br>    def get_word_count(self, obj):<br>        return len(obj.content.split())  # Slow for large content</pre><h4>Solution: Annotate at the Query Level</h4><p>Whenever possible, offload complex calculations to the database. The database can perform this operation in a single pass, which is far faster than Python’s row-by-row approach.</p><pre># GOOD: The database handles an approximate word count<br>from django.db.models import F, Value, IntegerField<br>from django.db.models.functions import Length, Replace<br><br>queryset = Book.objects.annotate(<br>    word_count=Length(F(&#39;content&#39;)) - Length(Replace(F(&#39;content&#39;), Value(&#39; &#39;), Value(&#39;&#39;))) + 1<br>)<br><br># GOOD: The serializer just retrieves the pre-calculated field<br>class BookSerializer(serializers.ModelSerializer):<br>    word_count = serializers.IntegerField(read_only=True)<br><br>    class Meta:<br>        model = Book<br>        fields = [&#39;title&#39;, &#39;word_count&#39;]</pre><h3>3. Caching Strategies</h3><p>Caching is the art of storing the results of expensive operations so you don’t have to recompute them on every request.</p><h4>Problem: Repeated Expensive Queries</h4><p>If you have a popular endpoint that runs the same complex query over and over, you’re wasting resources.</p><pre># BAD: Hits database every time<br>def get_popular_books():<br>    return Book.objects.filter(rating__gte=4.5).order_by(&#39;-views&#39;)[:10]</pre><h4>Solution: View-Level Caching</h4><p>For endpoints that don’t change often, use the @cache_page decorator. Django will cache the entire response for a specified duration, serving it directly from the cache without hitting your database or running any view code.</p><pre>from django.views.decorators.cache import cache_page<br><br>@cache_page(60 * 15)  # Cache for 15 minutes<br>def popular_books_api(request):<br>    books = Book.objects.filter(rating__gte=4.5).order_by(&#39;-views&#39;)[:10]<br>    # ... your serialization and response logic</pre><h4>Low-Level Caching for Complex Data</h4><p>For more granular control, use Django’s low-level cache API to store specific, expensive data snippets.</p><pre>from django.core.cache import cache<br><br>def get_expensive_report():<br>    cache_key = &#39;annual_sales_report_2023&#39;<br>    data = cache.get(cache_key)<br>    <br>    if not data:<br>        data = generate_complex_report()  # Expensive operation<br>        cache.set(cache_key, data, 3600)  # Cache for 1 hour<br>        <br>    return data<br><br><br></pre><h3>4. Pagination &amp; Data Limiting</h3><p>Returning a massive number of records in a single API response is a common performance killer.</p><h4>Problem: Massive Payloads</h4><pre># BAD: Returns all records, fetching unnecessary fields<br>from rest_framework.response import Response<br><br>def book_list(request):<br>    books = Book.objects.all()<br>    return Response({&#39;books&#39;: list(books.values())})</pre><h3>Solution: Cursor Pagination</h3><p>For very large datasets, cursor pagination is more efficient than offset-based pagination. Instead of calculating a total count and an offset, it uses a unique, ordered field (like a timestamp) to determine the next page’s starting point. Even you can customize pagination class based on your requirement.</p><pre># settings.py<br>REST_FRAMEWORK = {<br>    &#39;DEFAULT_PAGINATION_CLASS&#39;: &#39;rest_framework.pagination.CursorPagination&#39;,<br>    &#39;PAGE_SIZE&#39;: 20 # default size<br>}<br><br># views.py<br>from rest_framework.pagination import CursorPagination<br>from rest_framework.viewsets import ModelViewSet<br><br>class BookViewSet(ModelViewSet):<br>    queryset = Book.objects.all()<br>    serializer_class = BookSerializer<br>    pagination_class = CursorPagination</pre><p><em>Note</em>: CursorPagination is ideal for large datasets as it avoids counting total records, unlike offset-based pagination(<em>LimitOffsetPagination</em>).</p><h3>5. Asynchronous Processing</h3><p>Not all work needs to be done immediately. Offloading non-critical tasks to a background worker can make your API requests finish instantly.</p><h4>Problem: Blocking API Calls</h4><p>Blocking operations, like sending emails, can delay API responses and the further execution.</p><pre># BAD: Blocks request during email send<br>from rest_framework.response import Response<br><br>def create_user(request):<br>    user = User.objects.create(...)<br>    send_welcome_email(user.email)  # Blocks response!<br>    return Response(...)</pre><h4>Solution: Celery Background Tasks</h4><p>Use a task queue like Celery to handle long-running operations such as sending emails, generating reports, or processing images. This makes your API non-blocking and highly responsive.</p><pre># #tasks.py<br>from celery import shared_task<br><br>@shared_task<br>def send_welcome_email(user_id):<br>    user = User.objects.get(id=user_id)<br>    # Email sending logic<br><br># views.py<br>from rest_framework.response import Response<br><br>def create_user(request):<br>    user = User.objects.create(...)<br>    send_welcome_email.delay(user.id)  # Non-blocking<br>    # some other priority tasks/services will get executed parallelly <br>    return Response(...)</pre><h3>6. Connection Pooling &amp; Middleware</h3><h4>Problem: Database Connection Overhead</h4><p>Creating a new database connection for every single request is an expensive process.</p><h4>Solution: Persistent Connections</h4><p>Configure CONN_MAX_AGE in your settings to allow Django to reuse database connections, significantly reducing overhead.</p><pre># settings.py<br>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: &#39;django.db.backends.postgresql&#39;,<br>        &#39;CONN_MAX_AGE&#39;: 600,  # Reuse connections for 10 minutes<br>        # ... other settings<br>    }<br>}</pre><blockquote><em>Note</em>: Set CONN_MAX_AGE carefully, as keeping connections open too long can exhaust database resources.</blockquote><h3>7. Profiling &amp; Monitoring</h3><p>You can’t optimize what you can’t measure. Always start by identifying your bottlenecks.</p><h4>Essential Tools:</h4><ul><li><strong>Django Debug Toolbar</strong>: A must-have for development. It displays all queries executed per request, helping you spot N+1 issues and other inefficiencies.</li><li><strong>django-silk</strong>: A powerful tool for profiling requests in production or staging environments.</li><li><strong>Prometheus + Grafana</strong>: For robust, long-term monitoring of API performance metrics, server health, and more.</li></ul><p>Example silk setup:</p><pre># settings.py<br>MIDDLEWARE = [<br>    &#39;silk.middleware.SilkyMiddleware&#39;,<br>    # ... other middleware<br>]<br><br>INSTALLED_APPS = [<br>    &#39;silk&#39;,<br>    # ... other apps<br>]<br><br># urls.py<br>urlpatterns = [<br>    path(&#39;silk/&#39;, include(&#39;silk.urls&#39;)),<br>]</pre><h3>8. Advanced: Materialized Views</h3><p>For extremely complex, expensive, and frequently accessed reporting queries (PostgreSQL only), materialized views can be a game-changer. They pre-compute a query’s result and store it in a database table.</p><pre>-- Use RunSQL in a migration to create a materialized view<br>CREATE MATERIALIZED VIEW sales_summary AS<br>SELECT product_id, SUM(quantity) as total_sold<br>FROM orders<br>GROUP BY product_id;</pre><p>You’ll need to refresh the view periodically to update the data, often via a scheduled Celery task.</p><pre># tasks.py<br>from celery import shared_task<br>from django.db import connection<br><br>@shared_task<br>def refresh_sales_summary():<br>    with connection.cursor() as cursor:<br>        cursor.execute(&quot;REFRESH MATERIALIZED VIEW sales_summary&quot;)</pre><h3>Key Takeaways</h3><ol><li><strong>Profile First</strong>: Never guess where the bottleneck is. Use profiling tools to find the slowest part of your application.</li><li><strong>Database is King</strong>: The vast majority of performance gains come from optimizing your database queries.</li><li><strong>Cache Strategically</strong>: Cache expensive operations, but understand when and what to invalidate.</li><li><strong>Asynchronize</strong>: Offload non-critical work to background tasks to keep your API snappy.</li><li><strong>Monitor Continuously</strong>: Optimization is not a one-time task; it’s an ongoing process.</li></ol><h3>Real-World Impact</h3><p>Implementing these techniques with my team on a recent project resulted in some dramatic improvements:</p><ul><li>Some API response times dropped around <strong>70%</strong> (from 1200ms to 350ms) .</li><li>Database transaction load decreased by around 50<strong>%</strong>.</li><li>Server costs(on CPU, RAM, network bandwidth etc) reduced significantly through efficient resource usage.</li></ul><p>Remember: Optimization involves trade-offs. Always measure the impact of your changes and prioritize based on your application’s specific bottlenecks and scenario, Happy optimizing!</p><p>🚀 <strong>Your Turn</strong><br>Have you tried any of these techniques in your own Django projects? if yes, What kind of performance boosts did you see — or are you struggling with something not which is covered here?</p><p>💬 Share your thoughts in the comments — I’d love to hear your experiences and learn from your approaches.</p><p>👏 If this post helped you, don’t forget to <strong>clap, and share</strong> so more developers can discover these tips. It keeps the conversation going and motivates me to keep writing deep-dive guides like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0f4733ee567b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beginner guide for django-allauth]]></title>
            <link>https://medium.com/@devang.hingu/beginner-guide-for-django-allauth-59d528e6d99a?source=rss-140605ee5e4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/59d528e6d99a</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django-allauth]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[devang hingu]]></dc:creator>
            <pubDate>Sat, 21 May 2022 18:19:35 GMT</pubDate>
            <atom:updated>2022-05-21T18:19:35.425Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hi1wgkylmgnCELug5hb2Fg.jpeg" /></figure><p>When I started web development with Django. I thoroughly didn’t know about the <a href="https://github.com/pennersr/django-allauth"><em>django-allauth</em></a> package. I had knowledge of MVC and some core parts of Django. During college projects I had been working on a demo project and done user authentication and all manually. That time one of my seniors advised me to use <em>django-allauth</em>. I did some research and configured <em>django-allauth</em> with my project within a couple of minutes. For me it was an invigorating thing.</p><p>Because it saves lots of time for registration, login, forget &amp; reset passwords and user management. Also you can integrate a wide range of third party social authentication like <strong>Google, Facebook, LinkedIn, tumblr</strong> etc.</p><p>Here, I’ll show you how simple it is to integrate <em>django-allauth</em> with your Django project.</p><p>First thing, You need to setup a virtual environment using virtualenv and activate it, so all new python package installation goes to that environment instead of global installation.</p><p>Install and configure your basic Django application once you’ve completed the virtual environment setup.</p><p>After that, install latest <a href="https://github.com/pennersr/django-allauth"><em>django-allauth</em></a> package from the Python Package Index(pip) in your virtual environment.</p><pre>pip install django-allauth</pre><p>It’s ready to use in our project after a successful installation.</p><p>Configure allauth module in a INSTALLED_APPS in <strong>settings.py</strong> so INSTALLED_APPS will be look like,</p><pre>INSTALLED_APPS = [<br>   &#39;django.contrib.admin&#39;,<br>   &#39;django.contrib.auth&#39;,<br>   &#39;django.contrib.contenttypes&#39;,<br>   &#39;django.contrib.sessions&#39;,<br>   &#39;django.contrib.messages&#39;,<br>   &#39;django.contrib.staticfiles&#39;,</pre><pre># Add following thing on your code<br>   &#39;django.contrib.sites&#39;,<br>   &#39;allauth&#39;,<br>   &#39;allauth.account&#39;,<br>   &#39;allauth.socialaccount&#39;,<br>   # For extra provider i will write another post <br>]</pre><p>Add <strong>allauth back-end</strong> and site_id at end or anywhere in <strong>settings.py</strong>.</p><pre>AUTHENTICATION_BACKENDS = [<br>   # it required to login by username in django admin panel<br>   &#39;django.contrib.auth.backends.ModelBackend&#39;,</pre><pre>&#39;allauth.account.auth_backends.AuthenticationBackend&#39;,  <br>]<br># SITE_ID FROM django site framework<br>SITE_ID = 1</pre><pre># redirect url after successful login<br>LOGIN_REDIRECT_URL = &#39;index&#39;</pre><p>You will get information of SITE_ID from <a href="https://docs.djangoproject.com/en/3.1/ref/contrib/sites/">The “sites” framework</a>.<br> If you have no idea, <strong>What is site_id?</strong> Just go to the admin panel by creating a superuser. And go to the following URL <a href="http://localhost:8000/admin/sites/site/">http://localhost:8000/admin/sites/site/</a> (top level domain might be different in your case). probably it would be 1 If you have not deleted else add a new one with the same domain.</p><p>Now if you try to run your project you may see some pending migrations files on your project.</p><p>You can migrate it by running following management command therefore all <strong>all-auth</strong> related tables will be created.</p><pre>~$ python3 manage.py migrate</pre><p>Once all thing finished in settings.py, you need to setup all <strong>allauth</strong> related urls in project&#39;s urls.py</p><pre>from django.contrib import admin<br>from django.urls import path<br>from django.urls import include #added to include allauth urls</pre><pre>urlpatterns = [<br>   path(&#39;admin/&#39;, admin.site.urls),<br>   path(&#39;&#39;, include(&#39;src.core.urls&#39;)), # other apps URL</pre><pre># allauth urls<br>   path(&#39;accounts/&#39;, include(&#39;allauth.urls&#39;)), <br>]</pre><p>I added <em>accounts/</em> suffix for allauth urls based on <a href="https://django-allauth.readthedocs.io/en/latest/">documentation</a>. However, you are free to use any related name that meets the needs of your project.</p><p>Now your project is ready to test using <strong>django all-auth</strong>. just hit the url http://localhost:8000/accounts/signup/ from browser and it will show you built-in basic registration form like this</p><figure><img alt="Signup form of django allauth library" src="https://cdn-images-1.medium.com/max/648/0*Ewo3Jvy6Io17s8di.png" /></figure><p>At http://localhost:8000/accounts/ will display all urls which are available under our <strong>allauth</strong> apps while debug=True.</p><p>We can edit all the templates(HTML files) that are available under <strong>allauth</strong> by overriding into our template directory, that template customization &amp; social media integration will cover on upcoming post.</p><p>That’s it for this post.🚀</p><p>Comments are welcome and appreciated!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59d528e6d99a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>