<?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 Sunil Nepali on Medium]]></title>
        <description><![CDATA[Stories by Sunil Nepali on Medium]]></description>
        <link>https://medium.com/@sunilnepali844?source=rss-4ddbacb46008------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FjbZIcWOHLjaEADuG5cAtg.jpeg</url>
            <title>Stories by Sunil Nepali on Medium</title>
            <link>https://medium.com/@sunilnepali844?source=rss-4ddbacb46008------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:07:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunilnepali844/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 Complete Guide to Python Generics: From Beginner to Pro]]></title>
            <link>https://medium.com/@sunilnepali844/the-complete-guide-to-python-generics-from-beginner-to-pro-1d11d19b474c?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d11d19b474c</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-oops-concept]]></category>
            <category><![CDATA[python-generics]]></category>
            <category><![CDATA[type-safety]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 06:19:14 GMT</pubDate>
            <atom:updated>2025-08-26T06:19:14.609Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/444/1*Jfw1jn-btpVsqjTmxk6YxQ.png" /></figure><p>Python Generics might sound intimidating, but they’re actually one of the most powerful features for writing clean, reusable, and type-safe code. Whether you’re using Python 3.8 or the latest 3.12+, this comprehensive guide will teach you everything you need to know about Generics.</p><h3>Table of Contents</h3><ol><li>What Are Generics?</li><li>Why Do We Need Generics?</li><li>Python Version Differences</li><li>Generic Functions</li><li>Generic Classes</li><li>Advanced Generic Concepts</li><li>Real-World Examples</li><li>Best Practices</li><li>Common Pitfalls</li></ol><h3>What Are Generics?</h3><p>Generics allow you to write code that can work with different types while maintaining type safety. Think of them as templates or placeholders for types that get filled in when you actually use the code.</p><p>Imagine you have a box that can hold any type of item — books, toys, or electronics. Generics let you specify what type of item your box holds, ensuring you don’t accidentally put a book where you expect a toy.</p><h3>The Problem Generics Solve</h3><p>Without generics, you might write separate functions for different types:</p><pre># Without generics - repetitive and hard to maintain<br>def get_first_string(items: list[str]) -&gt; str:<br>    return items[0]<br><br>def get_first_int(items: list[int]) -&gt; int:<br>    return items[0]<br>def get_first_float(items: list[float]) -&gt; float:<br>    return items[0]</pre><p>With generics, you write one function that works for all types:</p><pre>from typing import TypeVar<br><br>T = TypeVar(&#39;T&#39;)<br>def get_first_item(items: list[T]) -&gt; T:<br>    return items[0]</pre><h3>Why Do We Need Generics?</h3><h3>1. Type Safety</h3><p>Generics help catch type errors before runtime:</p><pre>from typing import TypeVar, List</pre><pre>T = TypeVar(&#39;T&#39;)</pre><pre>def process_items(items: List[T]) -&gt; List[T]:<br>    # Your IDE will know the exact type and provide proper autocomplete<br>    return [item for item in items if item is not None]</pre><pre># Usage<br>numbers = [1, 2, None, 4]<br>result = process_items(numbers)  # Type checker knows result is List[int]</pre><h3>2. Code Reusability</h3><p>One generic implementation works for multiple types:</p><pre># One function, many types<br>strings = [&quot;hello&quot;, &quot;world&quot;]<br>numbers = [1, 2, 3]<br>booleans = [True, False, True]</pre><pre>first_string = get_first_item(strings)    # str<br>first_number = get_first_item(numbers)    # int<br>first_boolean = get_first_item(booleans)  # bool</pre><h3>3. Better Documentation</h3><p>Generics make your code self-documenting:</p><pre># Clear what types are expected and returned<br>def swap_pair(first: T, second: T) -&gt; tuple[T, T]:<br>    return second, first</pre><h3>Python Version Differences</h3><h3>Python 3.5–3.11 (Traditional Syntax)</h3><pre>from typing import TypeVar, Generic, List, Dict, Optional</pre><pre>T = TypeVar(&#39;T&#39;)<br>K = TypeVar(&#39;K&#39;)  # Key type<br>V = TypeVar(&#39;V&#39;)  # Value type</pre><pre># Generic function<br>def find_item(items: List[T], target: T) -&gt; Optional[int]:<br>    try:<br>        return items.index(target)<br>    except ValueError:<br>        return None</pre><pre># Generic class<br>class Cache(Generic[K, V]):<br>    def __init__(self) -&gt; None:<br>        self._data: Dict[K, V] = {}<br>    <br>    def get(self, key: K) -&gt; Optional[V]:<br>        return self._data.get(key)<br>    <br>    def set(self, key: K, value: V) -&gt; None:<br>        self._data[key] = value</pre><h3>Python 3.12+ (Modern Syntax)</h3><pre># No imports needed for basic types!</pre><pre># Generic function - cleaner syntax<br>def find_item[T](items: list[T], target: T) -&gt; int | None:<br>    try:<br>        return items.index(target)<br>    except ValueError:<br>        return None</pre><pre># Generic class - much cleaner<br>class Cache[K, V]:<br>    def __init__(self) -&gt; None:<br>        self._data: dict[K, V] = {}<br>    <br>    def get(self, key: K) -&gt; V | None:<br>        return self._data.get(key)<br>    <br>    def set(self, key: K, value: V) -&gt; None:<br>        self._data[key] = value</pre><h3>Generic Functions</h3><h3>Basic Generic Functions</h3><h4>Python 3.5–3.11 Version:</h4><pre>from typing import TypeVar, List, Optional, Callable<br><br>T = TypeVar(&#39;T&#39;)<br>def safe_get(items: List[T], index: int) -&gt; Optional[T]:<br>    &quot;&quot;&quot;Safely get an item from a list without raising IndexError&quot;&quot;&quot;<br>    if 0 &lt;= index &lt; len(items):<br>        return items[index]<br>    return None<br>def filter_items(items: List[T], predicate: Callable[[T], bool]) -&gt; List[T]:<br>    &quot;&quot;&quot;Filter items based on a predicate function&quot;&quot;&quot;<br>    return [item for item in items if predicate(item)]<br>def map_items(items: List[T], func: Callable[[T], T]) -&gt; List[T]:<br>    &quot;&quot;&quot;Apply a function to each item in the list&quot;&quot;&quot;<br>    return [func(item) for item in items]<br># Usage examples<br>numbers = [1, 2, 3, 4, 5]<br>words = [&quot;hello&quot;, &quot;world&quot;, &quot;python&quot;]<br># safe_get<br>print(safe_get(numbers, 2))    # Output: 3<br>print(safe_get(numbers, 10))   # Output: None<br># filter_items<br>even_numbers = filter_items(numbers, lambda x: x % 2 == 0)<br>print(even_numbers)  # Output: [2, 4]<br>long_words = filter_items(words, lambda w: len(w) &gt; 4)<br>print(long_words)    # Output: [&#39;hello&#39;, &#39;world&#39;, &#39;python&#39;]<br># map_items<br>squared = map_items(numbers, lambda x: x ** 2)<br>print(squared)       # Output: [1, 4, 9, 16, 25]</pre><h4>Python 3.12+ Version:</h4><pre>def safe_get[T](items: list[T], index: int) -&gt; T | None:<br>    &quot;&quot;&quot;Safely get an item from a list without raising IndexError&quot;&quot;&quot;<br>    if 0 &lt;= index &lt; len(items):<br>        return items[index]<br>    return None<br><br>def filter_items[T](items: list[T], predicate: callable[[T], bool]) -&gt; list[T]:<br>    &quot;&quot;&quot;Filter items based on a predicate function&quot;&quot;&quot;<br>    return [item for item in items if predicate(item)]<br>def map_items[T](items: list[T], func: callable[[T], T]) -&gt; list[T]:<br>    &quot;&quot;&quot;Apply a function to each item in the list&quot;&quot;&quot;<br>    return [func(item) for item in items]<br># Usage is identical to the older version</pre><h3>Multiple Type Variables</h3><p>Sometimes you need multiple generic types:</p><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Tuple, List<br><br>T = TypeVar(&#39;T&#39;)<br>U = TypeVar(&#39;U&#39;)<br>def zip_with_index(items: List[T]) -&gt; List[Tuple[int, T]]:<br>    &quot;&quot;&quot;Zip items with their indices&quot;&quot;&quot;<br>    return [(i, item) for i, item in enumerate(items)]<br>def transform_pair(first: T, second: U, func: Callable[[T, U], str]) -&gt; str:<br>    &quot;&quot;&quot;Transform a pair of items using a function&quot;&quot;&quot;<br>    return func(first, second)<br># Usage<br>words = [&quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>indexed = zip_with_index(words)<br>print(indexed)  # Output: [(0, &#39;apple&#39;), (1, &#39;banana&#39;), (2, &#39;cherry&#39;)]<br>result = transform_pair(5, &quot;items&quot;, lambda num, word: f&quot;{num} {word}&quot;)<br>print(result)  # Output: &quot;5 items&quot;</pre><h4>Python 3.12+:</h4><pre>def zip_with_index[T](items: list[T]) -&gt; list[tuple[int, T]]:<br>    &quot;&quot;&quot;Zip items with their indices&quot;&quot;&quot;<br>    return [(i, item) for i, item in enumerate(items)]<br><br>def transform_pair[T, U](first: T, second: U, func: callable[[T, U], str]) -&gt; str:<br>    &quot;&quot;&quot;Transform a pair of items using a function&quot;&quot;&quot;<br>    return func(first, second)<br># Usage is the same</pre><h3>Generic Classes</h3><p>Generic classes are where generics really shine. They let you create reusable data structures and containers.</p><h3>Basic Generic Classes</h3><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Generic, List, Optional<br><br>T = TypeVar(&#39;T&#39;)<br>class Stack(Generic[T]):<br>    &quot;&quot;&quot;A generic stack implementation&quot;&quot;&quot;<br>    <br>    def __init__(self) -&gt; None:<br>        self._items: List[T] = []<br>    <br>    def push(self, item: T) -&gt; None:<br>        &quot;&quot;&quot;Add an item to the top of the stack&quot;&quot;&quot;<br>        self._items.append(item)<br>    <br>    def pop(self) -&gt; T:<br>        &quot;&quot;&quot;Remove and return the top item&quot;&quot;&quot;<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self._items.pop()<br>    <br>    def peek(self) -&gt; T:<br>        &quot;&quot;&quot;Return the top item without removing it&quot;&quot;&quot;<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self._items[-1]<br>    <br>    def is_empty(self) -&gt; bool:<br>        &quot;&quot;&quot;Check if the stack is empty&quot;&quot;&quot;<br>        return len(self._items) == 0<br>    <br>    def size(self) -&gt; int:<br>        &quot;&quot;&quot;Return the number of items in the stack&quot;&quot;&quot;<br>        return len(self._items)<br># Usage<br>string_stack = Stack[str]()<br>string_stack.push(&quot;first&quot;)<br>string_stack.push(&quot;second&quot;)<br>print(string_stack.pop())    # Output: &quot;second&quot;<br>print(string_stack.peek())   # Output: &quot;first&quot;<br>number_stack = Stack[int]()<br>number_stack.push(1)<br>number_stack.push(2)<br>print(number_stack.size())   # Output: 2</pre><h4>Python 3.12+:</h4><pre>class Stack[T]:<br>    &quot;&quot;&quot;A generic stack implementation&quot;&quot;&quot;<br>    <br>    def __init__(self) -&gt; None:<br>        self._items: list[T] = []<br>    <br>    def push(self, item: T) -&gt; None:<br>        &quot;&quot;&quot;Add an item to the top of the stack&quot;&quot;&quot;<br>        self._items.append(item)<br>    <br>    def pop(self) -&gt; T:<br>        &quot;&quot;&quot;Remove and return the top item&quot;&quot;&quot;<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self._items.pop()<br>    <br>    def peek(self) -&gt; T:<br>        &quot;&quot;&quot;Return the top item without removing it&quot;&quot;&quot;<br>        if self.is_empty():<br>            raise IndexError(&quot;Stack is empty&quot;)<br>        return self._items[-1]<br>    <br>    def is_empty(self) -&gt; bool:<br>        &quot;&quot;&quot;Check if the stack is empty&quot;&quot;&quot;<br>        return len(self._items) == 0<br>    <br>    def size(self) -&gt; int:<br>        &quot;&quot;&quot;Return the number of items in the stack&quot;&quot;&quot;<br>        return len(self._items)<br><br># Usage is identical</pre><pre>Multiple Generic Types</pre><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Generic, Dict, Optional, List<br><br>K = TypeVar(&#39;K&#39;)  # Key type<br>V = TypeVar(&#39;V&#39;)  # Value type<br>class Repository(Generic[K, V]):<br>    &quot;&quot;&quot;A generic repository for storing key-value pairs with additional features&quot;&quot;&quot;<br>    <br>    def __init__(self) -&gt; None:<br>        self._data: Dict[K, V] = {}<br>        self._access_count: Dict[K, int] = {}<br>    <br>    def save(self, key: K, value: V) -&gt; None:<br>        &quot;&quot;&quot;Save a value with the given key&quot;&quot;&quot;<br>        self._data[key] = value<br>        self._access_count[key] = 0<br>    <br>    def find(self, key: K) -&gt; Optional[V]:<br>        &quot;&quot;&quot;Find a value by key&quot;&quot;&quot;<br>        if key in self._data:<br>            self._access_count[key] += 1<br>            return self._data[key]<br>        return None<br>    <br>    def delete(self, key: K) -&gt; bool:<br>        &quot;&quot;&quot;Delete a value by key&quot;&quot;&quot;<br>        if key in self._data:<br>            del self._data[key]<br>            del self._access_count[key]<br>            return True<br>        return False<br>    <br>    def get_all_keys(self) -&gt; List[K]:<br>        &quot;&quot;&quot;Get all keys&quot;&quot;&quot;<br>        return list(self._data.keys())<br>    <br>    def get_access_count(self, key: K) -&gt; int:<br>        &quot;&quot;&quot;Get how many times a key has been accessed&quot;&quot;&quot;<br>        return self._access_count.get(key, 0)<br>    <br>    def get_most_accessed(self) -&gt; Optional[K]:<br>        &quot;&quot;&quot;Get the most accessed key&quot;&quot;&quot;<br>        if not self._access_count:<br>            return None<br>        return max(self._access_count, key=self._access_count.get)<br># Usage<br>user_repo = Repository[int, str]()  # ID -&gt; Name<br>user_repo.save(1, &quot;Alice&quot;)<br>user_repo.save(2, &quot;Bob&quot;)<br>print(user_repo.find(1))  # Output: &quot;Alice&quot;<br>print(user_repo.find(1))  # Access it again<br>print(user_repo.get_access_count(1))  # Output: 2<br>product_repo = Repository[str, float]()  # Name -&gt; Price<br>product_repo.save(&quot;laptop&quot;, 999.99)<br>product_repo.save(&quot;mouse&quot;, 25.50)<br>print(product_repo.find(&quot;laptop&quot;))  # Output: 999.99</pre><h4>Python 3.12+:</h4><pre>class Repository[K, V]:<br>    &quot;&quot;&quot;A generic repository for storing key-value pairs with additional features&quot;&quot;&quot;<br>    <br>    def __init__(self) -&gt; None:<br>        self._data: dict[K, V] = {}<br>        self._access_count: dict[K, int] = {}<br>    <br>    def save(self, key: K, value: V) -&gt; None:<br>        &quot;&quot;&quot;Save a value with the given key&quot;&quot;&quot;<br>        self._data[key] = value<br>        self._access_count[key] = 0<br>    <br>    def find(self, key: K) -&gt; V | None:<br>        &quot;&quot;&quot;Find a value by key&quot;&quot;&quot;<br>        if key in self._data:<br>            self._access_count[key] += 1<br>            return self._data[key]<br>        return None<br>    <br>    def delete(self, key: K) -&gt; bool:<br>        &quot;&quot;&quot;Delete a value by key&quot;&quot;&quot;<br>        if key in self._data:<br>            del self._data[key]<br>            del self._access_count[key]<br>            return True<br>        return False<br>    <br>    def get_all_keys(self) -&gt; list[K]:<br>        &quot;&quot;&quot;Get all keys&quot;&quot;&quot;<br>        return list(self._data.keys())<br>    <br>    def get_access_count(self, key: K) -&gt; int:<br>        &quot;&quot;&quot;Get how many times a key has been accessed&quot;&quot;&quot;<br>        return self._access_count.get(key, 0)<br>    <br>    def get_most_accessed(self) -&gt; K | None:<br>        &quot;&quot;&quot;Get the most accessed key&quot;&quot;&quot;<br>        if not self._access_count:<br>            return None<br>        return max(self._access_count, key=self._access_count.get)</pre><pre># Usage is identical</pre><h3>Advanced Generic Concepts</h3><h3>Bounded Generics</h3><p>Sometimes you want to restrict what types can be used with your generic. This is called “bounded generics.”</p><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Protocol<br>from numbers import Number<br><br># Bound to a specific type<br>NumberType = TypeVar(&#39;NumberType&#39;, bound=Number)<br>def calculate_average(numbers: List[NumberType]) -&gt; float:<br>    &quot;&quot;&quot;Calculate average of numbers&quot;&quot;&quot;<br>    if not numbers:<br>        raise ValueError(&quot;Cannot calculate average of empty list&quot;)<br>    return sum(numbers) / len(numbers)<br># Usage<br>integers = [1, 2, 3, 4, 5]<br>floats = [1.1, 2.2, 3.3, 4.4, 5.5]<br>print(calculate_average(integers))  # Output: 3.0<br>print(calculate_average(floats))    # Output: 3.3000000000000003<br># This would cause a type error:<br># strings = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;]<br># calculate_average(strings)  # Type error!</pre><h4>Using Protocols for More Flexibility:</h4><pre>from typing import TypeVar, Protocol, List<br><br>class Comparable(Protocol):<br>    def __lt__(self, other) -&gt; bool: ...<br>    def __gt__(self, other) -&gt; bool: ...<br>    def __eq__(self, other) -&gt; bool: ...<br>ComparableType = TypeVar(&#39;ComparableType&#39;, bound=Comparable)<br>def find_max(items: List[ComparableType]) -&gt; ComparableType:<br>    &quot;&quot;&quot;Find the maximum item in a list&quot;&quot;&quot;<br>    if not items:<br>        raise ValueError(&quot;Cannot find max of empty list&quot;)<br>    <br>    max_item = items[0]<br>    for item in items[1:]:<br>        if item &gt; max_item:<br>            max_item = item<br>    return max_item<br>def sort_items(items: List[ComparableType]) -&gt; List[ComparableType]:<br>    &quot;&quot;&quot;Sort items in ascending order&quot;&quot;&quot;<br>    return sorted(items)<br># Usage<br>numbers = [3, 1, 4, 1, 5, 9, 2, 6]<br>words = [&quot;zebra&quot;, &quot;apple&quot;, &quot;banana&quot;, &quot;cherry&quot;]<br>print(find_max(numbers))  # Output: 9<br>print(find_max(words))    # Output: &quot;zebra&quot;<br>print(sort_items(numbers))  # Output: [1, 1, 2, 3, 4, 5, 6, 9]<br>print(sort_items(words))    # Output: [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;, &#39;zebra&#39;]</pre><h3>Generic Type Aliases</h3><p>You can create aliases for complex generic types:</p><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Dict, List, Tuple, Callable</pre><pre>T = TypeVar(&#39;T&#39;)<br>K = TypeVar(&#39;K&#39;)<br>V = TypeVar(&#39;V&#39;)</pre><pre># Type aliases<br>StringDict = Dict[str, str]<br>NumberList = List[int]<br>Processor = Callable[[T], T]<br>KeyValuePair = Tuple[K, V]<br>IndexedItems = List[Tuple[int, T]]</pre><pre>def process_config(config: StringDict) -&gt; StringDict:<br>    &quot;&quot;&quot;Process a configuration dictionary&quot;&quot;&quot;<br>    return {k.upper(): v.lower() for k, v in config.items()}</pre><pre>def apply_processor(items: List[T], processor: Processor[T]) -&gt; List[T]:<br>    &quot;&quot;&quot;Apply a processor function to all items&quot;&quot;&quot;<br>    return [processor(item) for item in items]</pre><pre># Usage<br>config = {&quot;name&quot;: &quot;MyApp&quot;, &quot;version&quot;: &quot;1.0&quot;, &quot;debug&quot;: &quot;True&quot;}<br>processed = process_config(config)<br>print(processed)  # Output: {&#39;NAME&#39;: &#39;myapp&#39;, &#39;VERSION&#39;: &#39;1.0&#39;, &#39;DEBUG&#39;: &#39;true&#39;}</pre><pre>numbers = [1, 2, 3, 4, 5]<br>doubled = apply_processor(numbers, lambda x: x * 2)<br>print(doubled)  # Output: [2, 4, 6, 8, 10]</pre><h3>Real-World Examples</h3><p>Let’s build some practical examples that you might use in real projects.</p><h3>Example 1: Generic Result Type</h3><p>A Result type that can represent either success or failure:</p><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Generic, Union, Optional, Callable<br>from enum import Enum</pre><pre>T = TypeVar(&#39;T&#39;)<br>E = TypeVar(&#39;E&#39;)</pre><pre>class ResultType(Enum):<br>    SUCCESS = &quot;success&quot;<br>    ERROR = &quot;error&quot;</pre><pre>class Result(Generic[T, E]):<br>    &quot;&quot;&quot;A generic Result type that represents either success or failure&quot;&quot;&quot;<br>    <br>    def __init__(self, value: Optional[T] = None, error: Optional[E] = None):<br>        if value is not None and error is not None:<br>            raise ValueError(&quot;Result cannot have both value and error&quot;)<br>        if value is None and error is None:<br>            raise ValueError(&quot;Result must have either value or error&quot;)<br>        <br>        self._value = value<br>        self._error = error<br>        self._type = ResultType.SUCCESS if value is not None else ResultType.ERROR<br>    <br>    @classmethod<br>    def success(cls, value: T) -&gt; &#39;Result[T, E]&#39;:<br>        &quot;&quot;&quot;Create a successful result&quot;&quot;&quot;<br>        return cls(value=value)<br>    <br>    @classmethod<br>    def error(cls, error: E) -&gt; &#39;Result[T, E]&#39;:<br>        &quot;&quot;&quot;Create an error result&quot;&quot;&quot;<br>        return cls(error=error)<br>    <br>    def is_success(self) -&gt; bool:<br>        &quot;&quot;&quot;Check if the result is successful&quot;&quot;&quot;<br>        return self._type == ResultType.SUCCESS<br>    <br>    def is_error(self) -&gt; bool:<br>        &quot;&quot;&quot;Check if the result is an error&quot;&quot;&quot;<br>        return self._type == ResultType.ERROR<br>    <br>    def get_value(self) -&gt; T:<br>        &quot;&quot;&quot;Get the value (raises exception if error)&quot;&quot;&quot;<br>        if self.is_error():<br>            raise ValueError(&quot;Cannot get value from error result&quot;)<br>        return self._value<br>    <br>    def get_error(self) -&gt; E:<br>        &quot;&quot;&quot;Get the error (raises exception if success)&quot;&quot;&quot;<br>        if self.is_success():<br>            raise ValueError(&quot;Cannot get error from success result&quot;)<br>        return self._error<br>    <br>    def map(self, func: Callable[[T], U]) -&gt; &#39;Result[U, E]&#39;:<br>        &quot;&quot;&quot;Transform the value if success, otherwise return the error&quot;&quot;&quot;<br>        if self.is_success():<br>            try:<br>                new_value = func(self.get_value())<br>                return Result.success(new_value)<br>            except Exception as e:<br>                return Result.error(e)<br>        return Result.error(self.get_error())<br>    <br>    def or_else(self, default: T) -&gt; T:<br>        &quot;&quot;&quot;Get the value or return a default if error&quot;&quot;&quot;<br>        return self.get_value() if self.is_success() else default</pre><pre># Example usage<br>def divide(a: float, b: float) -&gt; Result[float, str]:<br>    &quot;&quot;&quot;Divide two numbers, returning a Result&quot;&quot;&quot;<br>    if b == 0:<br>        return Result.error(&quot;Division by zero&quot;)<br>    return Result.success(a / b)</pre><pre>def safe_parse_int(text: str) -&gt; Result[int, str]:<br>    &quot;&quot;&quot;Parse a string to int safely&quot;&quot;&quot;<br>    try:<br>        return Result.success(int(text))<br>    except ValueError:<br>        return Result.error(f&quot;Cannot parse &#39;{text}&#39; as integer&quot;)</pre><pre># Usage<br>result1 = divide(10, 2)<br>if result1.is_success():<br>    print(f&quot;Result: {result1.get_value()}&quot;)  # Output: Result: 5.0<br>else:<br>    print(f&quot;Error: {result1.get_error()}&quot;)</pre><pre>result2 = divide(10, 0)<br>print(f&quot;Safe result: {result2.or_else(-1)}&quot;)  # Output: Safe result: -1</pre><pre># Chaining operations<br>parse_result = safe_parse_int(&quot;42&quot;)<br>doubled = parse_result.map(lambda x: x * 2)<br>if doubled.is_success():<br>    print(f&quot;Doubled: {doubled.get_value()}&quot;)  # Output: Doubled: 84</pre><h3>Example 2: Generic Cache with TTL (Time To Live)</h3><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Generic, Dict, Optional, NamedTuple<br>import time<br><br>K = TypeVar(&#39;K&#39;)<br>V = TypeVar(&#39;V&#39;)<br>class CacheEntry(NamedTuple):<br>    value: any<br>    expiry_time: float<br>class TTLCache(Generic[K, V]):<br>    &quot;&quot;&quot;A generic cache with Time To Live (TTL) functionality&quot;&quot;&quot;<br>    <br>    def __init__(self, default_ttl: float = 300.0):  # 5 minutes default<br>        self._cache: Dict[K, CacheEntry] = {}<br>        self._default_ttl = default_ttl<br>    <br>    def put(self, key: K, value: V, ttl: Optional[float] = None) -&gt; None:<br>        &quot;&quot;&quot;Store a value in the cache with optional TTL&quot;&quot;&quot;<br>        ttl = ttl or self._default_ttl<br>        expiry_time = time.time() + ttl<br>        self._cache[key] = CacheEntry(value=value, expiry_time=expiry_time)<br>    <br>    def get(self, key: K) -&gt; Optional[V]:<br>        &quot;&quot;&quot;Retrieve a value from the cache&quot;&quot;&quot;<br>        if key not in self._cache:<br>            return None<br>        <br>        entry = self._cache[key]<br>        if time.time() &gt; entry.expiry_time:<br>            # Entry has expired<br>            del self._cache[key]<br>            return None<br>        <br>        return entry.value<br>    <br>    def delete(self, key: K) -&gt; bool:<br>        &quot;&quot;&quot;Delete a key from the cache&quot;&quot;&quot;<br>        if key in self._cache:<br>            del self._cache[key]<br>            return True<br>        return False<br>    <br>    def clear_expired(self) -&gt; int:<br>        &quot;&quot;&quot;Remove all expired entries and return count of removed items&quot;&quot;&quot;<br>        current_time = time.time()<br>        expired_keys = [<br>            key for key, entry in self._cache.items()<br>            if current_time &gt; entry.expiry_time<br>        ]<br>        <br>        for key in expired_keys:<br>            del self._cache[key]<br>        <br>        return len(expired_keys)<br>    <br>    def size(self) -&gt; int:<br>        &quot;&quot;&quot;Get the current cache size&quot;&quot;&quot;<br>        return len(self._cache)<br>    <br>    def clear(self) -&gt; None:<br>        &quot;&quot;&quot;Clear all entries&quot;&quot;&quot;<br>        self._cache.clear()<br># Usage<br>user_cache = TTLCache[int, str](ttl=60.0)  # 1 minute TTL<br>user_cache.put(1, &quot;Alice&quot;)<br>user_cache.put(2, &quot;Bob&quot;, ttl=30.0)  # Custom TTL<br>print(user_cache.get(1))  # Output: &quot;Alice&quot;<br>print(user_cache.size())  # Output: 2<br># Wait for expiration (in real code)<br>time.sleep(1)  # Simulate time passing<br>expired_count = user_cache.clear_expired()<br>print(f&quot;Cleared {expired_count} expired entries&quot;)</pre><h3>Example 3: Generic Event System</h3><h4>Python 3.5–3.11:</h4><pre>from typing import TypeVar, Generic, List, Callable, Dict, Any<br>from abc import ABC, abstractmethod</pre><pre>T = TypeVar(&#39;T&#39;)</pre><pre>class Event(Generic[T]):<br>    &quot;&quot;&quot;Base generic event class&quot;&quot;&quot;<br>    <br>    def __init__(self, event_type: str, data: T):<br>        self.event_type = event_type<br>        self.data = data<br>        self.timestamp = time.time()</pre><pre>EventHandler = Callable[[Event[T]], None]</pre><pre>class EventBus(Generic[T]):<br>    &quot;&quot;&quot;Generic event bus for handling events&quot;&quot;&quot;<br>    <br>    def __init__(self):<br>        self._handlers: Dict[str, List[EventHandler[T]]] = {}<br>    <br>    def subscribe(self, event_type: str, handler: EventHandler[T]) -&gt; None:<br>        &quot;&quot;&quot;Subscribe to an event type&quot;&quot;&quot;<br>        if event_type not in self._handlers:<br>            self._handlers[event_type] = []<br>        self._handlers[event_type].append(handler)<br>    <br>    def unsubscribe(self, event_type: str, handler: EventHandler[T]) -&gt; bool:<br>        &quot;&quot;&quot;Unsubscribe from an event type&quot;&quot;&quot;<br>        if event_type in self._handlers:<br>            try:<br>                self._handlers[event_type].remove(handler)<br>                return True<br>            except ValueError:<br>                pass<br>        return False<br>    <br>    def publish(self, event: Event[T]) -&gt; None:<br>        &quot;&quot;&quot;Publish an event to all subscribers&quot;&quot;&quot;<br>        handlers = self._handlers.get(event.event_type, [])<br>        for handler in handlers:<br>            try:<br>                handler(event)<br>            except Exception as e:<br>                print(f&quot;Error in event handler: {e}&quot;)<br>    <br>    def clear_handlers(self, event_type: str) -&gt; None:<br>        &quot;&quot;&quot;Clear all handlers for an event type&quot;&quot;&quot;<br>        if event_type in self._handlers:<br>            self._handlers[event_type].clear()</pre><pre># Example usage with user events<br>class UserData(NamedTuple):<br>    user_id: int<br>    username: str<br>    email: str</pre><pre>user_bus = EventBus[UserData]()</pre><pre>def log_user_event(event: Event[UserData]) -&gt; None:<br>    print(f&quot;User event [{event.event_type}]: {event.data.username}&quot;)</pre><pre>def email_notification(event: Event[UserData]) -&gt; None:<br>    if event.event_type == &quot;user.created&quot;:<br>        print(f&quot;Sending welcome email to {event.data.email}&quot;)</pre><pre># Subscribe to events<br>user_bus.subscribe(&quot;user.created&quot;, log_user_event)<br>user_bus.subscribe(&quot;user.created&quot;, email_notification)<br>user_bus.subscribe(&quot;user.updated&quot;, log_user_event)</pre><pre># Publish events<br>new_user = UserData(1, &quot;alice&quot;, &quot;alice@example.com&quot;)<br>user_bus.publish(Event(&quot;user.created&quot;, new_user))</pre><pre>updated_user = UserData(1, &quot;alice_updated&quot;, &quot;alice@example.com&quot;)<br>user_bus.publish(Event(&quot;user.updated&quot;, updated_user))</pre><h3>Best Practices</h3><h3>1. Use Descriptive Type Variable Names</h3><pre># Good<br>T = TypeVar(&#39;T&#39;)  # For any type<br>K = TypeVar(&#39;K&#39;)  # For key types<br>V = TypeVar(&#39;V&#39;)  # For value types<br>ItemType = TypeVar(&#39;ItemType&#39;)  # More descriptive<br><br># Better for domain-specific code<br>UserType = TypeVar(&#39;UserType&#39;)<br>ProductType = TypeVar(&#39;ProductType&#39;)</pre><h3>2. Prefer Bounded Generics When Appropriate</h3><pre>from typing import TypeVar, Protocol</pre><pre>class Serializable(Protocol):<br>    def serialize(self) -&gt; str: ...</pre><pre>SerializableType = TypeVar(&#39;SerializableType&#39;, bound=Serializable)</pre><pre>def save_to_file(obj: SerializableType, filename: str) -&gt; None:<br>    with open(filename, &#39;w&#39;) as f:<br>        f.write(obj.serialize())  # Type checker knows this method exists</pre><h3>3. Use Generics for Container Types</h3><pre># Good - generic container<br>class Repository[T]:<br>    def save(self, item: T) -&gt; None: ...<br>    def find_by_id(self, id: int) -&gt; T | None: ...</pre><pre># Usage<br>user_repo = Repository[User]()<br>product_repo = Repository[Product]()</pre><h3>4. Keep Generic Interfaces Simple</h3><pre># Good - simple, focused interface<br>class Validator[T]:<br>    def validate(self, item: T) -&gt; bool: ...</pre><pre># Avoid - too many responsibilities<br>class ProcessorValidatorLogger[T]:<br>    def process(self, item: T) -&gt; T: ...<br>    def validate(self, item: T) -&gt; bool: ...<br>    def log(self, message: str) -&gt; None: ...</pre><h3>5. Use Type Aliases for Complex Generic Types</h3><pre># Python 3.5-3.11<br>from typing import TypeVar, Callable, List</pre><pre>T = TypeVar(&#39;T&#39;)<br>U = TypeVar(&#39;U&#39;)</pre><pre>Transformer = Callable[[T], U]<br>ItemProcessor = Callable[[List[T]], List[T]]<br>ValidationResult = tuple[bool, str]</pre><pre># Python 3.12+<br>type Transformer[T, U] = callable[[T], U]<br>type ItemProcessor[T] = callable[[list[T]], list[T]]<br>type ValidationResult = tuple[bool, str]</pre><h3>Common Pitfalls</h3><h3>Forgetting Type Bounds</h3><pre># Problematic - T could be any type<br>def add_items(a: T, b: T) -&gt; T:<br>    return a + b  # This might not work for all types!<br><br># Better - use bounds<br>from numbers import Number<br>NumberType = TypeVar(&#39;NumberType&#39;, bound=Number)<br>def add_numbers</pre><h3><strong>Conclusion</strong></h3><p><strong>Generics in Python</strong> are a way to write code that can work with different types while still providing type safety and better IDE/autocomplete support. They are used with <strong>type hints</strong> introduced in Python 3.5+ (via the typing module) and Python 3.9+ (updated syntax). Generics allow you to define classes, functions, and data structures that can work with <strong>any type</strong>, but still let you specify which type will be used when the class/function is instantiated.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d11d19b474c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Build a Custom SafeDelete Model in Django]]></title>
            <link>https://medium.com/@sunilnepali844/how-to-build-a-custom-safedelete-model-in-django-b9752214c8f0?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9752214c8f0</guid>
            <category><![CDATA[django-queryset]]></category>
            <category><![CDATA[django-safe-delete]]></category>
            <category><![CDATA[django-models]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-manager]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Mon, 21 Jul 2025 11:38:07 GMT</pubDate>
            <atom:updated>2025-07-21T11:39:14.728Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVKOLLX7wprRbHTl2IPDcQ.png" /></figure><p>In real-world applications, it’s common to <strong>“soft delete”</strong> records rather than permanently removing them from the database. This lets you preserve history, prevent accidental loss, and even allow recovery of deleted data.</p><h3>Understanding Django’s QuerySet and Manager</h3><p>Before diving into our SafeDelete implementation, let’s understand the key components we’ll be working with.</p><h4>What is a QuerySet?</h4><p>A QuerySet is a collection of database queries that Django uses to retrieve objects from your database. It’s lazy, meaning it doesn’t hit the database until you actually need the data. QuerySets allow you to:</p><ul><li>Filter data (filter(), exclude())</li><li>Order results (order_by())</li><li>Limit results ([:10])</li><li>Aggregate data (count(), sum())</li></ul><pre># Examples of QuerySet operations<br>users = User.objects.filter(is_active=True)  # Lazy - no DB hit yet<br>user_count = users.count()  # Now it hits the database</pre><p>This returns a QuerySet — not the actual data (yet).</p><h4>What is a Manager?</h4><p>A Manager is the interface through which database query operations are provided to Django models. Every model has at least one Manager, and by default, Django adds a Manager with the name objects to every model class.</p><p>The Manager is responsible for:</p><ul><li>Providing QuerySet methods to the model class</li><li>Defining the initial QuerySet that the model uses</li><li>Adding custom methods for database operations</li></ul><h4>✅ Default Manager Example</h4><pre>from django.db import models<br><br>class Product(models.Model):<br>    name = models.CharField(max_length=100)<br>    price = models.FloatField()<br><br># Usage<br>Product.objects.all()         # Returns all products<br>Product.objects.filter(price__lt=100)  # Filter by price</pre><p>✅ Custom Manager Example</p><p>Let’s say we want to hide deleted items (where deleted is not null) from.objects.all()</p><p>Step 1: Define the custom manager</p><pre>from django.db import models<br><br>class ActiveManager(models.Manager):<br>    def get_queryset(self):<br>        # Only return non-deleted records<br>        return super().get_queryset().filter(deleted__isnull=True)<br><br>    def deleted(self):<br>        # Returns deleted records<br>        return super().get_queryset().filter(deleted__isnull=False)</pre><p>Step 2: Use it in your model</p><pre>from django.utils.timezone import now<br><br>class Item(models.Model):<br>    name = models.CharField(max_length=100)<br>    deleted = models.DateTimeField(null=True, blank=True)<br><br>    # Set the custom manager<br>    objects = ActiveManager()<br><br>    # Optional: Add fallback manager to access all records<br>    all_objects = models.Manager()<br><br>    def soft_delete(self):<br>        self.deleted = now()<br>        self.save()</pre><h4>Building Our Custom SafeDelete System</h4><p>Now let’s build our SafeDelete system step by step.</p><h4>Step 1: Custom QuerySet for SafeDelete</h4><p>First, we’ll create a custom QuerySet that automatically excludes deleted objects:</p><pre>from django.db import models<br>from django.utils import timezone<br>from django.contrib.auth import get_user_model<br><br>User = get_user_model()<br><br>class SafeDeleteQuerySet(models.QuerySet):<br>    &quot;&quot;&quot;<br>    Custom QuerySet that provides soft delete functionality.<br>    &quot;&quot;&quot;<br>    <br>    def delete(self):<br>        &quot;&quot;&quot;<br>        Soft delete all objects in the queryset by setting deleted timestamp.<br>        &quot;&quot;&quot;<br>        return self.update(deleted=timezone.now())<br>    <br>    def hard_delete(self):<br>        &quot;&quot;&quot;<br>        Permanently delete objects from database.<br>        &quot;&quot;&quot;<br>        return super().delete()<br>    <br>    def active(self):<br>        &quot;&quot;&quot;<br>        Return only non-deleted objects.<br>        &quot;&quot;&quot;<br>        return self.filter(deleted__isnull=True)<br>    <br>    def deleted(self):<br>        &quot;&quot;&quot;<br>        Return only deleted objects.<br>        &quot;&quot;&quot;<br>        return self.filter(deleted__isnull=False)<br>    <br>    def restore(self):<br>        &quot;&quot;&quot;<br>        Restore deleted objects by setting deleted field to None.<br>        &quot;&quot;&quot;<br>        return self.update(deleted=None, deleted_by=None)</pre><h3>Step 2: Custom Manager for SafeDelete</h3><p>Next, we’ll create a Manager that uses our custom QuerySet.</p><pre>class BaseSafeDeleteManager(models.Manager):<br>    &quot;&quot;&quot;<br>    Base manager that contains ALL methods for SafeDelete functionality.<br>    Other managers inherit from this and just change the default get_queryset() behavior.<br>    &quot;&quot;&quot;<br>    <br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Base implementation - returns all objects.<br>        Subclasses override this to change default behavior.<br>        &quot;&quot;&quot;<br>        return SafeDeleteQuerySet(self.model, using=self._db)<br>   <br>    <br><br>class ActiveObjectsManager(BaseSafeDeleteManager):<br>    &quot;&quot;&quot;<br>    Manager that returns ONLY active (non-deleted) objects by default.<br>    Inherits all methods from BaseSafeDeleteManager.<br>    &quot;&quot;&quot;<br>    <br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Override to return only active objects by default.<br>        &quot;&quot;&quot;<br>        return super().get_queryset().active()<br><br><br>class AllObjectsManager(BaseSafeDeleteManager):<br>    &quot;&quot;&quot;<br>    Manager that returns ALL objects (active + deleted) by default.<br>    Inherits all methods from BaseSafeDeleteManager.<br>    &quot;&quot;&quot;<br>    <br>    def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Override to return all objects by default.<br>        &quot;&quot;&quot;<br>        return super().get_queryset()  # Returns all objects<br><br><br>class DeletedObjectsManager(BaseSafeDeleteManager):<br>    &quot;&quot;&quot;<br>    Manager that returns ONLY deleted objects by default.<br>    Inherits all methods from BaseSafeDeleteManager.<br>    &quot;&quot;&quot;<br>    <br>     def get_queryset(self):<br>        &quot;&quot;&quot;<br>        Return only deleted objects.<br>        &quot;&quot;&quot;<br>        return SafeDeleteQuerySet(self.model, using=self._db).deleted()<br>    <br>    def restore_all(self):<br>        &quot;&quot;&quot;<br>        Restore all deleted objects.<br>        &quot;&quot;&quot;<br>        return self.get_queryset().restore()<br>    <br>    def hard_delete_all(self):<br>        &quot;&quot;&quot;<br>        Permanently delete all deleted objects.<br>        &quot;&quot;&quot;<br>        return self.get_queryset().hard_delete()<br>   </pre><h4>Step 3: SafeDelete Model Base Class</h4><p>Now let’s create the base SafeDelete model:</p><pre>class SafeDeleteModel(models.Model):<br>    &quot;&quot;&quot;<br>    Abstract base class that provides soft delete functionality with three managers.<br>    <br>    Managers:<br>    - objects: Only active (non-deleted) objects<br>    - all_objects: All objects (active + deleted)<br>    - deleted_objects: Only deleted objects<br>    <br>    All managers inherit from BaseSafeDeleteManager and have access to all methods.<br>    &quot;&quot;&quot;<br>    <br>    deleted = models.DateTimeField(<br>        null=True, <br>        blank=True, <br>        help_text=&quot;Timestamp when this object was deleted&quot;,<br>        db_index=True  # Add index for better query performance<br>    )<br>    deleted_by = models.ForeignKey(<br>        User,<br>        on_delete=models.SET_NULL,<br>        null=True,<br>        blank=True,<br>        related_name=&quot;%(app_label)s_%(class)s_deleted_set&quot;,<br>        help_text=&quot;User who deleted this object&quot;<br>    )<br>    <br>    # THREE MANAGERS - All inherit from BaseSafeDeleteManager<br>    objects = ActiveObjectsManager()           # DEFAULT: Only active objects<br>    all_objects = AllObjectsManager()          # All objects (active + deleted)<br>    deleted_objects = DeletedObjectsManager()  # Only deleted objects<br>    <br>    class Meta:<br>        abstract = True<br>    <br>    def delete(self, user=None, using=None, keep_parents=False):<br>        &quot;&quot;&quot;<br>        Soft delete the object by setting deleted timestamp and user.<br>        <br>        Args:<br>            user: User instance who is deleting the object<br>            using: Database alias<br>            keep_parents: Whether to keep parent objects<br>        &quot;&quot;&quot;<br>        if self.is_deleted:<br>            raise ValueError(&quot;Object is already deleted&quot;)<br>            <br>        self.deleted = timezone.now()<br>        if user:<br>            self.deleted_by = user<br>        self.save(using=using, update_fields=[&#39;deleted&#39;, &#39;deleted_by&#39;])<br>    <br>    def hard_delete(self, using=None, keep_parents=False):<br>        &quot;&quot;&quot;<br>        Permanently delete the object from database.<br>        &quot;&quot;&quot;<br>        return super().delete(using=using, keep_parents=keep_parents)<br>    <br>    def restore(self):<br>        &quot;&quot;&quot;<br>        Restore a deleted object by clearing deleted fields.<br>        &quot;&quot;&quot;<br>        if not self.is_deleted:<br>            raise ValueError(&quot;Object is not deleted&quot;)<br>            <br>        self.deleted = None<br>        self.deleted_by = None<br>        self.save(update_fields=[&#39;deleted&#39;, &#39;deleted_by&#39;])<br>    <br>    @property<br>    def is_deleted(self):<br>        &quot;&quot;&quot;<br>        Check if object is deleted.<br>        &quot;&quot;&quot;<br>        return self.deleted is not None<br>    <br>    @property<br>    def is_active(self):<br>        &quot;&quot;&quot;<br>        Check if object is active (not deleted).<br>        &quot;&quot;&quot;<br>        return self.deleted is None<br>    <br>    def __str__(self):<br>        status = &quot; (DELETED)&quot; if self.is_deleted else &quot;&quot;<br>        return f&quot;{super().__str__()}{status}</pre><h3>Step 4: Example Model Implementation</h3><p>Here’s how to use the SafeDelete model:</p><pre>from django.db import models<br><br>class Category(SafeDeleteModel):<br>    &quot;&quot;&quot;<br>    Example model that inherits SafeDelete functionality.<br>    &quot;&quot;&quot;<br>    name = models.CharField(max_length=100)<br>    description = models.TextField(blank=True)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br>    <br>    def __str__(self):<br>        return self.name<br>    <br>    class Meta:<br>        verbose_name_plural = &quot;Categories&quot;<br><br>class Product(SafeDeleteModel):<br>    &quot;&quot;&quot;<br>    Another example model with foreign key relationships.<br>    &quot;&quot;&quot;<br>    name = models.CharField(max_length=200)<br>    category = models.ForeignKey(Category, on_delete=models.CASCADE)<br>    price = models.DecimalField(max_digits=10, decimal_places=2)<br>    is_active = models.BooleanField(default=True)<br>    <br>    def __str__(self):<br>        return self.name</pre><h3>Basic CRUD Operations</h3><pre># Create objects<br>category = Category.objects.create(name=&quot;Electronics&quot;, description=&quot;Electronic items&quot;)<br>product = Product.objects.create(name=&quot;Smartphone&quot;, category=category, price=599.99)<br><br># Normal queries (excludes deleted objects automatically)<br>active_categories = Category.objects.all()  # Only non-deleted<br>active_products = Product.objects.filter(category=category)  # Only non-deleted<br><br># Soft delete<br>category.delete(user=request.user)  # Marks as deleted<br>product.delete(user=request.user)   # Marks as deleted<br><br># After deletion, normal queries won&#39;t return these objects<br>active_categories = Category.objects.all()  # Empty queryset<br><br># Access deleted objects<br>deleted_categories = Category.objects.deleted_only()<br>all_categories = Category.objects.all_with_deleted()<br><br># Restore deleted objects<br>category.restore()<br>product.restore()<br><br># Hard delete (permanent)<br>category.hard_delete()  # Permanently removes from database</pre><h4>Step 5: Example using Django APIView</h4><pre>from rest_framework.views import APIView<br>from rest_framework.response import Response<br>from rest_framework import status<br>from rest_framework.permissions import IsAuthenticated<br>from django.shortcuts import get_object_or_404<br>from django.http import Http404<br>from .models import Product, Category<br>from .serializers import ProductSerializer, CategorySerializer<br><br><br>class ProductAPIView(APIView):<br>    &quot;&quot;&quot;<br>    Complete APIView demonstrating all SafeDelete operations<br>    &quot;&quot;&quot;<br>    permission_classes = [IsAuthenticated]<br>    <br>    def get(self, request, pk=None):<br>        &quot;&quot;&quot;<br>        GET: Retrieve products with different filters<br>        <br>        Query parameters:<br>        - filter: &#39;all&#39;, &#39;active&#39;, &#39;deleted&#39; (default: &#39;active&#39;)<br>        - pk: specific product ID<br>        &quot;&quot;&quot;<br>        filter_type = request.query_params.get(&#39;filter&#39;, &#39;active&#39;)<br>        <br>        if pk:<br>            # Get specific product<br>            try:<br>                if filter_type == &#39;all&#39;:<br>                    product = Product.all_objects.get(pk=pk)<br>                elif filter_type == &#39;deleted&#39;:<br>                    product = Product.deleted_objects.get(pk=pk)<br>                else:  # active<br>                    product = Product.objects.get(pk=pk)<br>                    <br>                serializer = ProductSerializer(product)<br>                return Response(serializer.data)<br>                <br>            except Product.DoesNotExist:<br>                return Response(<br>                    {&#39;error&#39;: f&#39;Product not found in {filter_type} objects&#39;}, <br>                    status=status.HTTP_404_NOT_FOUND<br>                )<br>        <br>        # Get list of products based on filter<br>        if filter_type == &#39;all&#39;:<br>            products = Product.all_objects.all()<br>        elif filter_type == &#39;deleted&#39;:<br>            products = Product.deleted_objects.all()<br>        elif filter_type == &#39;active&#39;:<br>            products = Product.objects.active()  # or just Product.objects.all()<br>        else:<br>            return Response(<br>                {&#39;error&#39;: &#39;Invalid filter. Use: all, active, or deleted&#39;}, <br>                status=status.HTTP_400_BAD_REQUEST<br>            )<br>            <br>        serializer = ProductSerializer(products, many=True)<br>        return Response({<br>            &#39;filter&#39;: filter_type,<br>            &#39;count&#39;: len(products),<br>            &#39;results&#39;: serializer.data<br>        })<br>    <br>    def post(self, request):<br>        &quot;&quot;&quot;<br>        POST: Create new product<br>        &quot;&quot;&quot;<br>        serializer = ProductSerializer(data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data, status=status.HTTP_201_CREATED)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>    <br>    def put(self, request, pk):<br>        &quot;&quot;&quot;<br>        PUT: Update existing product (only active products)<br>        &quot;&quot;&quot;<br>        try:<br>            product = Product.objects.get(pk=pk)  # Only active products<br>        except Product.DoesNotExist:<br>            return Response(<br>                {&#39;error&#39;: &#39;Product not found or is deleted&#39;}, <br>                status=status.HTTP_404_NOT_FOUND<br>            )<br>        <br>        serializer = ProductSerializer(product, data=request.data)<br>        if serializer.is_valid():<br>            serializer.save()<br>            return Response(serializer.data)<br>        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)<br>    <br>    def delete(self, request, pk):<br>        &quot;&quot;&quot;<br>        DELETE: Soft delete product (moves to deleted state)<br>        &quot;&quot;&quot;<br>        try:<br>            product = Product.objects.get(pk=pk)  # Only active products<br>        except Product.DoesNotExist:<br>            return Response(<br>                {&#39;error&#39;: &#39;Product not found or already deleted&#39;}, <br>                status=status.HTTP_404_NOT_FOUND<br>            )<br>        <br>        # Soft delete<br>        product.delete(user=request.user)<br>        return Response(<br>            {&#39;message&#39;: f&#39;Product &quot;{product.name}&quot; has been soft deleted&#39;}, <br>            status=status.HTTP_200_OK<br>        )<br><br><br>class ProductActionsAPIView(APIView):<br>    &quot;&quot;&quot;<br>    APIView for special SafeDelete actions: restore and hard_delete<br>    &quot;&quot;&quot;<br>    permission_classes = [IsAuthenticated]<br>    <br>    def patch(self, request, pk, action):<br>        &quot;&quot;&quot;<br>        PATCH: Perform restore or hard_delete actions<br>        <br>        Actions:<br>        - restore: Restore a deleted product<br>        - hard_delete: Permanently delete a product<br>        &quot;&quot;&quot;<br>        if action == &#39;restore&#39;:<br>            return self._restore_product(request, pk)<br>        elif action == &#39;hard_delete&#39;:<br>            return self._hard_delete_product(request, pk)<br>        else:<br>            return Response(<br>                {&#39;error&#39;: &#39;Invalid action. Use: restore or hard_delete&#39;}, <br>                status=status.HTTP_400_BAD_REQUEST<br>            )<br>    <br>    def _restore_product(self, request, pk):<br>        &quot;&quot;&quot;Restore a deleted product&quot;&quot;&quot;<br>        try:<br>            product = Product.deleted_objects.get(pk=pk)  # Only deleted products<br>        except Product.DoesNotExist:<br>            return Response(<br>                {&#39;error&#39;: &#39;Deleted product not found&#39;}, <br>                status=status.HTTP_404_NOT_FOUND<br>            )<br>        <br>        product.restore()<br>        serializer = ProductSerializer(product)<br>        return Response({<br>            &#39;message&#39;: f&#39;Product &quot;{product.name}&quot; has been restored&#39;,<br>            &#39;product&#39;: serializer.data<br>        }, status=status.HTTP_200_OK)<br>    <br>    def _hard_delete_product(self, request, pk):<br>        &quot;&quot;&quot;Permanently delete a product&quot;&quot;&quot;<br>        try:<br>            # Can hard delete from any state (active or deleted)<br>            product = Product.all_objects.get(pk=pk)<br>        except Product.DoesNotExist:<br>            return Response(<br>                {&#39;error&#39;: &#39;Product not found&#39;}, <br>                status=status.HTTP_404_NOT_FOUND<br>            )<br>        <br>        product_name = product.name<br>        product.hard_delete()  # Permanently delete<br>        return Response(<br>            {&#39;message&#39;: f&#39;Product &quot;{product_name}&quot; has been permanently deleted&#39;}, <br>            status=status.HTTP_200_OK<br>        )</pre><h3>Conclusion</h3><p>This SafeDelete implementation provides a robust foundation for soft delete functionality in Django applications. It offers:</p><ul><li><strong>Automatic soft delete behavior</strong> for models that inherit from SafeDeleteModel</li><li><strong>Flexible querying</strong> with options to include or exclude deleted objects</li><li><strong>User tracking</strong> to know who deleted what and when</li><li><strong>RESTful API support</strong> with proper ViewSet integration</li><li><strong>Restore functionality</strong> for undeleting objects</li><li><strong>Hard delete option</strong> when permanent removal is needed</li></ul><p>The system is extensible and can be customized further based on your specific requirements. Remember to consider performance implications, especially for applications with high delete volumes, and implement appropriate database indexing and archival strategies.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9752214c8f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding dispatch() method in Django Class based view.]]></title>
            <link>https://medium.com/@sunilnepali844/understanding-dispatch-method-in-django-class-based-view-a62f12c513e0?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/a62f12c513e0</guid>
            <category><![CDATA[django-views]]></category>
            <category><![CDATA[django-dispatch]]></category>
            <category><![CDATA[dispatches]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 03:55:44 GMT</pubDate>
            <atom:updated>2025-07-09T03:55:44.916Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re new to <strong>Django class-based views (CBVs)</strong>, you might have seen the word dispatch() and wondered:</p><ul><li>What is dispatch()?</li><li>What does it actually do?</li><li>Do I need to use it?</li><li>How can I handle GET, POST, PUT, PATCH, and DELETE methods?</li></ul><h3>🔹 What is dispatch() in Django?</h3><p>In Django, when you create a class-based view, <strong>dispatch() is the first method that runs</strong> when a request comes to that view.</p><p>Think of dispatch() as a <strong>traffic police officer</strong>.<br>When a request (GET, POST, etc.) comes in, the officer checks what kind of request it is and <strong>sends it to the right method</strong> (get(), post(), put(), etc.).</p><h3>🧠 In Simple Terms:</h3><blockquote><em>dispatch() is like a switchboard. It checks the request method and routes it to the correct function inside your class-based view.</em></blockquote><h3>🔹 How Django Handles Requests in Class-Based Views</h3><p>Let’s look at how Django works under the hood when you use a class-based view:</p><pre>from django.views import View<br>from django.http import HttpResponse<br><br>class MyView(View):<br>    def get(self, request):<br>        return HttpResponse(&quot;This is a GET request&quot;)<br><br>    def post(self, request):<br>        return HttpResponse(&quot;This is a POST request&quot;)</pre><p>When someone visits this view:</p><ul><li>If it’s a GET request → Django calls dispatch() → it runs get()</li><li>If it’s a POST request → Django calls dispatch() → it runs post()</li></ul><p>You don’t need to write dispatch() manually most of the time.<br>Django does it <strong>automatically</strong> in the background.</p><h3>🔹 What does dispatch() do exactly?</h3><p>Here’s a simplified version of what Django’s built-in dispatch() method looks like:</p><pre>def dispatch(self, request, *args, **kwargs):<br>    if request.method == &#39;GET&#39;:<br>        return self.get(request, *args, **kwargs)<br>    elif request.method == &#39;POST&#39;:<br>        return self.post(request, *args, **kwargs)<br>    elif request.method == &#39;PUT&#39;:<br>        return self.put(request, *args, **kwargs)<br>    elif request.method == &#39;PATCH&#39;:<br>        return self.patch(request, *args, **kwargs)<br>    elif request.method == &#39;DELETE&#39;:<br>        return self.delete(request, *args, **kwargs)<br>    else:<br>        return HttpResponseNotAllowed([&#39;GET&#39;, &#39;POST&#39;, &#39;PUT&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;])</pre><p>So basically, <strong>dispatch() checks the request method and calls the corresponding method inside your class</strong>.</p><h3>🔹 Why would you override dispatch()?</h3><p>Most of the time, you don’t need to touch dispatch().</p><p>But if you want to:</p><ul><li>Run code <strong>before or after</strong> any method (get(), post(), etc.)</li><li>Add <strong>permission checks</strong></li><li>Log request data</li><li>Restrict certain users or methods</li></ul><p>… then overriding dispatch() is very useful.</p><h3>🔹 Example: Custom dispatch() handling GET, POST, PUT, PATCH, DELETE</h3><p>Here’s a complete example where we handle all HTTP methods using dispatch():</p><pre>from django.views import View<br>from django.http import JsonResponse<br><br>class MyCustomView(View):<br>    def dispatch(self, request, *args, **kwargs):<br>        method = request.method.upper()<br><br>        if method == &#39;GET&#39;:<br>            return self.get(request, *args, **kwargs)<br>        elif method == &#39;POST&#39;:<br>            return self.post(request, *args, **kwargs)<br>        elif method == &#39;PUT&#39;:<br>            return self.put(request, *args, **kwargs)<br>        elif method == &#39;PATCH&#39;:<br>            return self.patch(request, *args, **kwargs)<br>        elif method == &#39;DELETE&#39;:<br>            return self.delete(request, *args, **kwargs)<br>        else:<br>            return JsonResponse({&quot;error&quot;: &quot;Method not allowed&quot;}, status=405)<br><br>    def get(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;GET request handled&quot;})<br><br>    def post(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;POST request handled&quot;})<br><br>    def put(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;PUT request handled&quot;})<br><br>    def patch(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;PATCH request handled&quot;})<br><br>    def delete(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;DELETE request handled&quot;})</pre><h3>🔹 Real-World Use Case: Adding a Login Check in dispatch()</h3><p>Let’s say you want to allow only <strong>logged-in users</strong> to access the view:</p><pre>from django.http import HttpResponseForbidden<br><br>class SecureView(View):<br>    def dispatch(self, request, *args, **kwargs):<br>        if not request.user.is_authenticated:<br>            return HttpResponseForbidden(&quot;You must be logged in&quot;)<br>        return super().dispatch(request, *args, **kwargs)<br><br>    def get(self, request, *args, **kwargs):<br>        return JsonResponse({&quot;message&quot;: &quot;Welcome, logged-in user!&quot;})</pre><h3>🔹 Summary — What You Should Remember</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*ul34_Z7v4UXhzla36hHhbA.png" /></figure><h3>🙋 Summary</h3><p>The dispatch() method is <strong>one of the most powerful tools</strong> in Django&#39;s class-based views. It gives you full control over how different types of HTTP requests are handled — all in one place.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a62f12c513e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging in Python Made Simple: Custom Loggers, Multiple Handlers, and File Output Explained]]></title>
            <link>https://medium.com/@sunilnepali844/logging-in-python-made-simple-custom-loggers-multiple-handlers-and-file-output-explained-5e83705a5922?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e83705a5922</guid>
            <category><![CDATA[django-logging]]></category>
            <category><![CDATA[logging-and-monitoring]]></category>
            <category><![CDATA[django-logger]]></category>
            <category><![CDATA[logger]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 11:07:56 GMT</pubDate>
            <atom:updated>2025-06-25T11:09:34.399Z</atom:updated>
            <content:encoded><![CDATA[<p>Logging is one of the most valuable tools in a developer’s toolbox — it lets you peek under the hood of your running application, see what’s happening, and diagnose problems before they spin out of control. Django ships with a powerful, flexible logging system built on Python’s standard logging module. In this post we’ll unpack every piece of a Django logging setup:</p><ol><li><strong>What is logging?</strong></li><li><strong>Log levels</strong></li><li><strong>Formatters</strong></li><li><strong>Handlers</strong></li><li><strong>Loggers</strong></li><li><strong>Putting it all together</strong></li><li><strong>Custom loggers and multiple configurations</strong></li></ol><p>By the end, even a total beginner will understand how to set up Django logging to capture debug messages, warnings, errors, and everything in between.</p><h3>1. What Is Logging?</h3><p>At its simplest, “logging” means writing messages about your application’s execution to some output: the console, a file, or even a remote server. Those messages can tell you:</p><ul><li><strong>What</strong> happened (e.g. “User 42 just logged in”)</li><li><strong>When</strong> it happened</li><li><strong>Where</strong> in your code it happened</li><li><strong>How serious</strong> it is (debug vs. warning vs. error)</li></ul><p>Unlike print() statements, logging is:</p><ul><li><strong>Configurable at runtime</strong> (you can turn on/off debug messages via settings — no code change needed)</li><li><strong>Hierarchical</strong> (different parts of your app can log under different names)</li><li><strong>Flexible</strong> (you can send logs to multiple destinations, each with its own format)</li></ul><h3>2. Log Levels</h3><p>Log messages carry a “level” that indicates their severity or importance. Django (via Python’s logging) understands five standard levels, in increasing severity:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*FLmkvKQmGdHhTd2Kmw-m-A.png" /></figure><p><strong>Key point:</strong> if your logger or handler is set to level ERROR, it will <strong>only</strong> record ERROR and CRITICAL messages. DEBUG, INFO, and WARNING will be ignored</p><h3>3. Formatters</h3><p>A <strong>formatter</strong> defines <strong>how</strong> each log message is rendered (show)— what fields get included and in what order. In Django’s LOGGING dict you might see:</p><pre>&#39;formatters&#39;: {<br>    &#39;simple&#39;: {<br>        &#39;format&#39;: &#39;{levelname} {asctime} {name} {message}&#39;,<br>        &#39;style&#39;: &#39;{&#39;,<br>    },<br>    &#39;detailed&#39;: {<br>        &#39;format&#39;: &#39;{levelname} {asctime} {module}:{lineno} {message}&#39;,<br>        &#39;style&#39;: &#39;{&#39;,<br>    },<br>},</pre><ul><li><strong>format</strong> is a template string.</li><li><strong>style</strong> tells Python which placeholder syntax to use (&#39;{&#39; for {levelname}, &#39;%&#39; for %-style, or &#39;$&#39; for $-style).</li></ul><p>You can define <strong>multiple formatters</strong>, then choose the right one for each handler. For example, a compact format for console output and a more detailed stack-trace style for your log files.</p><h3>4. Handlers</h3><p>A <strong>handler</strong> takes the formatted log record and sends it somewhere: to the console, to a file, to an email, to syslog, or even over the network. In Django you might configure:</p><pre>&#39;handlers&#39;: {<br>    &#39;console&#39;: {<br>        &#39;class&#39;: &#39;logging.StreamHandler&#39;,<br>        &#39;level&#39;: &#39;DEBUG&#39;,<br>        &#39;formatter&#39;: &#39;simple&#39;,<br>    },<br>    &#39;file&#39;: {<br>        &#39;class&#39;: &#39;logging.FileHandler&#39;,<br>        &#39;level&#39;: &#39;DEBUG&#39;,<br>        &#39;formatter&#39;: &#39;detailed&#39;,<br>        &#39;filename&#39;: os.path.join(BASE_DIR, &#39;django.log&#39;),<br>    },<br>},</pre><ul><li><strong>class</strong>: which handler class to use.</li><li><strong>level</strong>: the minimum message level this handler will emit.</li><li><strong>formatter</strong>: which formatter to use.</li><li><strong>filename</strong> (for FileHandler): where to write the logs.</li></ul><p>You can add <strong>multiple handlers</strong> (e.g. log to both console and file) by listing them under a logger.</p><h3>5. Loggers</h3><p>A <strong>logger</strong> is what your code actually calls when it wants to emit a message:</p><pre>import logging<br>logger = logging.getLogger(__name__)<br><br>def my_view(request):<br>    logger.debug(&quot;Entering view&quot;)<br>    ...<br>    logger.error(&quot;Something went wrong!&quot;)</pre><p>In your Django LOGGING dict, you bind handlers and levels to <strong>logger names</strong>:</p><pre>&#39;loggers&#39;: {<br>    # The root logger (empty string) catches all logs not handled by more specific loggers<br>    &#39;&#39;: {<br>        &#39;handlers&#39;: [&#39;file&#39;],<br>        &#39;level&#39;: &#39;ERROR&#39;,<br>        &#39;propagate&#39;: True,<br>    },<br>    # Django’s own request logger<br>    &#39;django.request&#39;: {<br>        &#39;handlers&#39;: [&#39;file&#39;],<br>        &#39;level&#39;: &#39;ERROR&#39;,<br>        &#39;propagate&#39;: False,<br>    },<br>    # Your project-specific logger<br>    &#39;project_name&#39;: {<br>        &#39;handlers&#39;: [&#39;file&#39;],<br>        &#39;level&#39;: &#39;DEBUG&#39;,<br>        &#39;propagate&#39;: True,<br>    },<br><br>  # logger for celerylogger<br>    &#39;celery&#39;: {<br>        &#39;handlers&#39;: [&#39;file&#39;],<br>        &#39;level&#39;: &#39;DEBUG&#39;,<br>        &#39;propagate&#39;: True,<br>    },<br>},</pre><ul><li><strong>Logger name</strong> ties to logging.getLogger(&#39;name&#39;).</li><li><strong>propagate</strong> controls whether log records bubble up to parent loggers.</li></ul><h3>Root logger vs. custom logger</h3><ul><li>The <strong>root logger</strong> (&#39;&#39;) catches everything that isn’t matched by a more specific logger.</li><li>A <strong>custom logger</strong> (e.g. &#39;project_name&#39;) is for messages you explicitly send there.</li></ul><p>If you set the root logger to ERROR, <strong>only</strong> errors will be logged by default. All your logger.info() or logger.debug() calls to other loggers will be dropped unless you configure them too.</p><h3>6. Putting It All Together</h3><p>A minimal example to capture all levels of your own code (project_name) and still log Django’s errors:</p><pre>LOGGING = {<br>    &#39;version&#39;: 1,<br>    &#39;disable_existing_loggers&#39;: False,<br><br>    &#39;formatters&#39;: {<br>        &#39;simple&#39;: {<br>            &#39;format&#39;: &#39;{levelname} {asctime} {name}: {message}&#39;,<br>            &#39;style&#39;: &#39;{&#39;,<br>        },<br>    },<br><br>    &#39;handlers&#39;: {<br>        &#39;file_debug&#39;: {<br>            &#39;class&#39;: &#39;logging.FileHandler&#39;,<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;formatter&#39;: &#39;simple&#39;,<br>            &#39;filename&#39;: os.path.join(BASE_DIR, &#39;project_name.log&#39;),<br>        },<br>        &#39;file_error&#39;: {<br>            &#39;class&#39;: &#39;logging.FileHandler&#39;,<br>            &#39;level&#39;: &#39;ERROR&#39;,<br>            &#39;formatter&#39;: &#39;simple&#39;,<br>            &#39;filename&#39;: os.path.join(BASE_DIR, &#39;errors.log&#39;),<br>        },<br>    },<br><br>    &#39;loggers&#39;: {<br>        # Django’s own request logger—only errors to errors.log<br>        &#39;django.request&#39;: {<br>            &#39;handlers&#39;: [&#39;file_error&#39;],<br>            &#39;level&#39;: &#39;ERROR&#39;,<br>            &#39;propagate&#39;: False,<br>        },<br>        # Your app—DEBUG+ to project_name.log, errors also go to errors.log (via propagate)<br>        &#39;project_name&#39;: {<br>            &#39;handlers&#39;: [&#39;file_debug&#39;],<br>            &#39;level&#39;: &#39;DEBUG&#39;,<br>            &#39;propagate&#39;: True,<br>        },<br>        # Root logger—catch-all (optional)<br>        &#39;&#39;: {<br>            &#39;handlers&#39;: [&#39;file_error&#39;],<br>            &#39;level&#39;: &#39;ERROR&#39;,<br>            &#39;propagate&#39;: True,<br>        },<br>    },<br>}</pre><ul><li><strong>project_name logger</strong> at DEBUG level means your logger.debug(), info(), etc. all get written to project_name.log.</li><li><strong>django.request</strong> at ERROR means only unhandled request exceptions go to errors.log.</li><li>You could add as many handlers and formatters as you like — e.g. a rotating file handler, an email handler, or a syslog handler.</li></ul><h3>7. Advanced: Multiple Loggers &amp; Custom Exception Handling</h3><p>You can define <strong>multiple loggers</strong> for different parts of your app:</p><pre>&#39;loggers&#39;: {<br>    &#39;project_name.api&#39;: {...},         # only API-related logs<br>    &#39;project_name.payments&#39;: {...},    # only payment module logs<br>    &#39;project_name.worker&#39;: {...},      # background task logs<br>}</pre><p>Each can have its own level and handlers. That way, you can route:</p><ul><li><strong>API debug</strong> to one file</li><li><strong>Worker warnings</strong> to another</li><li><strong>Critical alerts</strong> to email</li></ul><h3>Capturing exceptions in DRF</h3><p>If you override DRF’s exception handler :</p><pre>import logging<br>from rest_framework.views import exception_handler as drf_exception_handler<br>logger = logging.getLogger(&#39;project_name&#39;)<br>def custom_exception_handler(exc, context):<br>    # Log the full exception at debug level<br>    logger.debug(&quot;Exception in DRF view:&quot;, exc_info=exc)<br>    # Delegate to default handler for response formatting<br>    return drf_exception_handler(exc, context)</pre><p>Make sure your project_name logger is at DEBUG and its handler at DEBUG so you see those stack traces in your log.</p><h3>Wrapping Up</h3><ul><li><strong>Formatters</strong> shape the text of each log entry.</li><li><strong>Handlers</strong> decide where logs go (files, console, email, etc.) and what levels they accept.</li><li><strong>Loggers</strong> are named channels you call from your code; they tie to handlers and levels in your settings.</li></ul><p>By mixing and matching multiple formatters, handlers, and loggers, you can build a logging setup that:</p><ul><li>Writes <strong>debug</strong> information for your development sanity</li><li>Captures <strong>info</strong> events in production for auditing</li><li>Records <strong>warnings</strong> and <strong>errors</strong> separately</li><li>Sends <strong>critical</strong> issues directly to your team via email or Slack</li></ul><p>With Django’s dict-based configuration, you have complete control — no extra code or third-party libraries required. Once you’ve got this foundation in place, logging becomes an invaluable companion in building reliable, diagnosable Django projects.</p><h4>Bonus</h4><p>Use python builtin logging</p><pre># importing module<br>import logging<br><br># Create and configure logger<br>logging.basicConfig(filename=&quot;newfile.log&quot;,<br>                    format=&quot;%(name)s: %(asctime)s | %(levelname)s | %(filename)s%(lineno)s | %(process)d &gt;&gt;&gt; %(message)s&quot;,<br>                    filemode=&#39;w&#39;)<br><br># Creating an object<br>logger = logging.getLogger()<br><br># Setting the threshold of logger to DEBUG<br>logger.setLevel(logging.DEBUG)<br><br># Test messages<br>logger.debug(&quot;This is Debug&quot;)<br>logger.info(&quot;This is Info&quot;)<br>logger.warning(&quot;This is Warning&quot;)<br>logger.error(&quot;This is Error&quot;)<br>logger.critical(&quot;This is Critical&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e83705a5922" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Is Redis Cache and How to Use It in Python and Django]]></title>
            <link>https://medium.com/@sunilnepali844/what-is-redis-cache-and-how-to-use-it-in-python-and-django-23549d5ef38f?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/23549d5ef38f</guid>
            <category><![CDATA[django-redis]]></category>
            <category><![CDATA[python-redis]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[caching-memory]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Mon, 23 Jun 2025 06:32:55 GMT</pubDate>
            <atom:updated>2025-06-23T06:32:55.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wpMzPi-n8N_UC7wv9pu0Og.png" /></figure><p>Caching is a cornerstone of modern applications — it helps reduce latency, ease database load, and deliver blazing-fast responses to users. Redis, an in-memory data store, is one of the most popular caching engines in the world. In this comprehensive blog, we’ll explore:</p><ol><li><strong>What is Redis?</strong></li><li><strong>Redis as a Cache</strong></li><li><strong>Core Redis Data Types</strong></li><li><strong>Building a Custom Redis Cache in Python (Async + Retry)</strong></li></ol><ul><li>Line-by-line walkthrough of the example RedisClient code</li></ul><ol><li><strong>Using </strong><strong>django-redis in Django Projects</strong></li></ol><ul><li>Configuration</li><li>Basic usage</li><li>Advanced patterns</li></ul><p>By the end of this article, you’ll have all the knowledge you need to integrate Redis caching — either directly via redis-py or through the Django-native django-redis backend—without having to consult any other resource.</p><h3>1. What is Redis?</h3><p>Redis stands for <strong>RE</strong>mote <strong>DI</strong>ctionary <strong>S</strong>erver. It is an open-source, in-memory data structure store that can be used as:</p><ul><li><strong>Cache</strong>: Store frequently accessed data for rapid reads</li><li><strong>Database</strong>: It supports persistence to disk</li><li><strong>Message Broker</strong>: Pub/Sub and streams</li></ul><p>Key attributes:</p><ul><li><strong>In-memory</strong>: Data lives in RAM, delivering sub-millisecond reads/writes</li><li><strong>Data Structures</strong>: Strings, hashes, lists, sets, sorted sets, streams, hyperloglogs, and bitmaps</li><li><strong>Replication &amp; Clustering</strong>: Master-slave replication and clustering for high availability</li><li><strong>Persistence Options</strong>: RDB snapshots and AOF (Append-Only File)</li><li><strong>Atomic operations</strong>: All commands are atomic, ensuring consistency</li></ul><p>Redis’s blazing speed makes it ideal for caching database query results, session data, rate limiting, real-time analytics, and more.</p><h3>2. Redis as a Cache</h3><p>When used as a cache:</p><ul><li><strong>Set</strong>: Write data with a key and optional expiry (TTL)</li><li><strong>Get</strong>: Retrieve data by key</li><li><strong>Expire</strong>: Automatically evict stale entries when TTL elapses</li><li><strong>Delete</strong>: Manually remove entries when underlying data changes</li></ul><p>Benefits of Redis caching:</p><ul><li><strong>Reduced Latency</strong>: Reads from RAM are orders of magnitude faster than disk-based databases</li><li><strong>Lower DB Load</strong>: Frequent queries served from cache instead of hitting the primary database</li><li><strong>Flexible TTL</strong>: Per-key expiration prevents stale data</li><li><strong>Atomic Eviction</strong>: Expiry and deletion operations are atomic</li></ul><h3>3. Core Redis Data Types</h3><ol><li><strong>Strings</strong>: Simple key-value pairs (max 512 MB)</li><li><strong>Hashes</strong>: Maps between string fields and string values, great for storing objects</li><li><strong>Lists</strong>: Ordered collections of strings — useful for queues</li><li><strong>Sets</strong>: Unordered collections of unique strings — great for tags or membership</li><li><strong>Sorted Sets</strong>: Sets ordered by a score (float) for leaderboards</li><li><strong>Streams</strong>: Append-only log data structure, ideal for messaging</li><li><strong>HyperLogLog</strong>: Probabilistic data structure for cardinality estimation</li><li><strong>Bitmaps/Bitfields</strong>: Bit-level operations, useful for analytics</li></ol><p>Understanding these types will help you choose the right structure for your cache data.</p><h3>4. Building a Custom Redis Cache in Python</h3><p>In many cases, you want full control over how caching interacts with your application. The redis-py library (now with async support) lets you do exactly that. Below is an example RedisClient class:</p><pre>import json<br>from typing import Any, Optional<br>from redis import asyncio as redis<br>from redis.backoff import ExponentialBackoff<br>from redis.retry import Retry<br>from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError<br>from app.core.logger import logger<br><br>class RedisClient:<br>    _instance = None<br><br>    def __init__(self, redis_url: str):<br>        self.redis_url = redis_url<br>        self.redis_instance = None<br><br>    @classmethod<br>    async def get_instance(cls, redis_url: str) -&gt; &quot;RedisClient&quot;:<br>        if not cls._instance:<br>            cls._instance = cls(redis_url)<br>            await cls._instance.init_redis()<br>        return cls._instance<br><br>    async def init_redis(self):<br>        try:<br>            retry_policy = Retry(ExponentialBackoff(), 3)<br>            self.redis_instance = redis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20self.redis_url,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20socket_timeout=5,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20decode_responses=True,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20retry=retry_policy,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20retry_on_error=[BusyLoadingError,%20ConnectionError,%20TimeoutError]%3Cbr%3E)<br>            await self.redis_instance.ping()<br>            logger.info(&quot;Connected to redis&quot;)<br>        except (ConnectionError, TimeoutError, BusyLoadingError) as e:<br>            logger.error(f&quot;Failed to connect to redis. Error {e}&quot;)<br><br>        async def set_cache_key(self, key: str, data: Any, ex: Optional[int] = None):<br>            # Wrap python object as JSON, set with optional expiry (ex)<br>            try:<br>              value = json.dumps(data) if isinstance(data, dict) else str(data)<br>                #if data is dictionary convert into json else save as it.<br>                await self.redis_instance.set(<br>                    key,<br>                    json.dumps(data),<br>                    ex=ex<br>                )<br>            except Exception as e:<br>                logger.error(f&quot;Error setting cache for key {key}: {e}&quot;)<br><br>        async def get_cache_by_key(self, key: str):<br>            # Retrieve JSON and load back into Python object<br>            try:<br>                data = await self.redis_instance.get(key)<br>                if data:<br>                    return json.loads(data)<br>            except Exception as e:<br>                logger.error(f&quot;Error fetching cache for key {key}: {e}&quot;)<br><br>        async def set_all_cache_by_hash(self, key: str, value: dict, ex: Optional[int] = None):<br>            try:<br>                # HSET mapping: field-&gt;value<br>                await self.redis_instance.hset(key, mapping=value)<br>                if ex is not None:<br>                    await self.redis_instance.expire(key, ex)<br>            except Exception as e:<br>                logger.error(f&quot;Error setting hash data for key {key}: {e}&quot;)<br><br>        async def get_all_cache_by_hash(self, key: str):<br>            try:<br>                return await self.redis_instance.hgetall(key)<br>            except Exception as e:<br>                logger.error(f&quot;Error fetching hash data for key {key}: {e}&quot;)<br><br>        async def delete_key(self, key: str):<br>            await self.redis_instance.delete(key)<br><br>        async def expire(self, key: str, ttl: int):<br>            await self.redis_instance.expire(key, ttl)<br><br></pre><p>Explain:</p><h3>4.1. Singleton + Async Initialization</h3><pre>import json<br>from typing import Any, Optional<br>from redis import asyncio as redis<br>from redis.backoff import ExponentialBackoff<br>from redis.retry import Retry<br>from redis.exceptions import BusyLoadingError, ConnectionError, TimeoutError<br>from app.core.logger import logger<br><br>class RedisClient:<br>    _instance = None<br><br>    def __init__(self, redis_url: str):<br>        self.redis_url = redis_url<br>        self.redis_instance = None<br><br>    @classmethod<br>    async def get_instance(cls, redis_url: str) -&gt; &quot;RedisClient&quot;:<br>        if not cls._instance:<br>            cls._instance = cls(redis_url)<br>            await cls._instance.init_redis()<br>        return cls._instance<br><br>    async def init_redis(self):<br>        try:<br>            retry_policy = Retry(ExponentialBackoff(), 3)<br>            self.redis_instance = redis.from_url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20self.redis_url,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20socket_timeout=5,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20decode_responses=True,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20retry=retry_policy,%3Cbr%3E%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20retry_on_error=[BusyLoadingError,%20ConnectionError,%20TimeoutError]%3Cbr%3E)<br>            await self.redis_instance.ping()<br>            logger.info(&quot;Connected to redis&quot;)<br>        except (ConnectionError, TimeoutError, BusyLoadingError) as e:<br>            logger.error(f&quot;Failed to connect to redis. Error {e}&quot;)</pre><ul><li><strong>_instance</strong>: Ensures only one client exists (singleton pattern).</li><li><strong>get_instance</strong>: Async classmethod that returns the shared instance, initializing it on first call.</li><li><strong>init_redis</strong>: Builds the connection with:</li><li><strong>Retry(ExponentialBackoff(), 3)</strong>: Retry up to 3 times with exponential delays.</li><li><strong>decode_responses=True</strong>: Auto-decode bytes to strings.</li><li><strong>ping()</strong>: Verifies connectivity.</li></ul><h3>4.2. Basic Commands</h3><p>Continue in the same class:</p><pre>    async def set_cache_key(self, key: str, data: Any, ex: Optional[int] = None):<br>            # Wrap python object as JSON, set with optional expiry (ex)<br>            try:<br>              value = json.dumps(data) if isinstance(data, dict) else str(data)<br>                #if data is dictionary convert into json else save as it.<br>                await self.redis_instance.set(<br>                    key,<br>                    json.dumps(data),<br>                    ex=ex<br>                )<br>            except Exception as e:<br>                logger.error(f&quot;Error setting cache for key {key}: {e}&quot;)<br><br>    async def get_cache_by_key(self, key: str):<br>        # Retrieve JSON and load back into Python object<br>        try:<br>            data = await self.redis_instance.get(key)<br>            if data:<br>                return json.loads(data)<br>        except Exception as e:<br>            logger.error(f&quot;Error fetching cache for key {key}: {e}&quot;)</pre><ul><li><strong>set(..., ex=ttl)</strong>: Atomic set-with-ttl command.</li><li><strong>get()</strong>: Returns None if key missing—safe to check.</li><li><strong>JSON serialization</strong>: Makes caching of complex Python objects easy.</li></ul><h3>4.3. Hash Operations</h3><pre>    async def set_all_cache_by_hash(self, key: str, value: dict, ex: Optional[int] = None):<br>        try:<br>            # HSET mapping: field-&gt;value<br>            await self.redis_instance.hset(key, mapping=value)<br>            if ex is not None:<br>                await self.redis_instance.expire(key, ex)<br>        except Exception as e:<br>            logger.error(f&quot;Error setting hash data for key {key}: {e}&quot;)<br><br>    async def get_all_cache_by_hash(self, key: str):<br>        try:<br>            return await self.redis_instance.hgetall(key)<br>        except Exception as e:<br>            logger.error(f&quot;Error fetching hash data for key {key}: {e}&quot;)</pre><ul><li>Use <strong>hashes</strong> to store multiple related fields under one Redis key.</li><li><strong>hgetall</strong> returns a dict of all field→value pairs.</li></ul><h3>4.4. Other Helpers</h3><pre>    async def delete_key(self, key: str):<br>        await self.redis_instance.delete(key)<br><br>    async def expire(self, key: str, ttl: int):<br>        await self.redis_instance.expire(key, ttl)</pre><ul><li><strong>delete</strong> allows manual invalidation when underlying data mutates.</li><li><strong>expire</strong> lets you extend or shorten TTL after initial set.</li></ul><h3>5. Using django-redis in Django Projects</h3><p>For most Django apps, using a ready-made cache backend like django-redis is much simpler. You write less boilerplate and get Django’s cache API out of the box.</p><h3>5.1. Installation</h3><pre>pip install django-redis</pre><h3>5.2. Configuration in settings.py</h3><pre>CACHES = {<br>    &#39;default&#39;: {<br>        &#39;BACKEND&#39;: &#39;django_redis.cache.RedisCache&#39;,<br>        &#39;LOCATION&#39;: &#39;redis://127.0.0.1:6379/0&#39;,  # Using DB 0<br>        &#39;OPTIONS&#39;: {<br>            &#39;CLIENT_CLASS&#39;: &#39;django_redis.client.DefaultClient&#39;,<br>            # &#39;PASSWORD&#39;: &#39;yourpassword&#39;,  # if needed<br>            # &#39;CONNECTION_POOL_KWARGS&#39;: {&#39;max_connections&#39;: 50, &#39;retry_on_timeout&#39;: True},<br>        },<br>        &#39;TIMEOUT&#39;: 60 * 60,  # Default 1 hour<br>    }<br>}</pre><h3>5.3. Basic Cache Operations</h3><pre>from django.core.cache import cache<br><br># 1) Set with default timeout<br>cache.set(&#39;page:user:45&#39;, &#39;&lt;html&gt;…&lt;/html&gt;&#39;)<br><br># 2) Get<br>html = cache.get(&#39;page:user:45&#39;)<br><br># 3) Set custom TTL (seconds)<br>cache.set(&#39;obj:123&#39;, obj_dict, timeout=300)<br><br># 4) Delete manually<br>cache.delete(&#39;obj:123&#39;)<br><br># 5) Clear entire cache (careful!)<br>cache.clear()</pre><h3>5.4. Accessing the Raw Redis Client</h3><p>Under the hood, you can still issue any Redis command:</p><pre>from django_redis import get_redis_connection<br><br>r = get_redis_connection(&#39;default&#39;)<br>r.incr(&#39;stats:page_views&#39;)<br>r.hset(&#39;settings&#39;, &#39;feature_x&#39;, &#39;enabled&#39;)</pre><h3>5.5. View &amp; Template Caching</h3><p><strong>View caching</strong>:</p><pre>from django.views.decorators.cache import cache_page<br>@cache_page(60 * 5)<br>def my_view(request): <br>  #code</pre><p><strong>Template fragment caching</strong>:</p><pre>{% load cache %}<br>{% cache 300 sidebar request.user.id %}<br>  &lt;!-- expensive sidebar markup --&gt;<br>{% endcache %}</pre><p>Both use Redis automatically behind the scenes.</p><h3>Conclusion</h3><p>Redis is a powerful, versatile tool for caching and beyond. In this blog we covered:</p><ol><li><strong>What Redis is</strong> and why in-memory storage matters</li><li><strong>Core data types</strong> to help you structure your cache</li><li><strong>Building a custom Python wrapper</strong> for Redis with async, retries, JSON serialization, TTL, and manual deletion</li><li><strong>Integrating Redis into Django</strong> with django-redis, using Django’s cache API and raw Redis commands</li></ol><p>Armed with these patterns, you can:</p><ul><li>Speed up database-heavy endpoints</li><li>Implement rate limiting and analytics counters</li><li>Cache user sessions or template fragments</li><li>Have full control over expiry and invalidation.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23549d5ef38f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Regex in Python (For Beginners)]]></title>
            <link>https://medium.com/@sunilnepali844/mastering-regex-in-python-for-beginners-7622b528a192?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/7622b528a192</guid>
            <category><![CDATA[regular-expressions]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-regex]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Sun, 22 Jun 2025 06:51:38 GMT</pubDate>
            <atom:updated>2025-06-22T06:51:38.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoTz4tMNn8iUOzIKPy2vEA.png" /></figure><blockquote><strong><em>“Regex is like Google for text. It helps you search smartly.”</em></strong></blockquote><p>Whether you’re validating emails, extracting phone numbers, or replacing text in a document — <strong>regular expressions (regex)</strong> in Python are your best tool. This blog is a <strong>complete guide</strong> for beginners. No fluff, no jargon — just <strong>plain explanations with examples</strong>.</p><h3>✅ What is Regex?</h3><p><strong>Regex</strong> (short for <em>regular expression</em>) is a tool used to search, match, or manipulate text using <strong>patterns</strong>.</p><p>Imagine you want to find all phone numbers in a message, or check if a string is a valid email address. Regex lets you do that <strong>automatically and smartly</strong>.</p><h4>How to Use Regex in Python</h4><p>You use Python’s built-in re module.</p><pre>import re</pre><p>Here are the most common functions:</p><ol><li>re.match() = Checks if the pattern matches at the <strong>start</strong> of the string</li></ol><p>example:</p><p><em>Check if text starts with “Hello”</em></p><pre>import re<br>result = re.match(r&quot;Hello&quot;, &quot;Hello World&quot;)<br>print(result)  # Match object</pre><p>2. re.search() = Searches the <strong>entire string</strong> for a match</p><p>Find all digits in a string</p><pre>re.findall(r&quot;\d&quot;, &quot;I have 2 apples and 3 bananas&quot;) <br># Output: [&#39;2&#39;, &#39;3&#39;]</pre><blockquote><em>\d → any digit (0-9)</em></blockquote><p>3. re.findall() = Returns a list of <strong>all matches</strong></p><p>Extract all words</p><pre>re.findall(r&quot;\w+&quot;, &quot;I love Python_3!&quot;) <br># Output: [&#39;I&#39;, &#39;love&#39;, &#39;Python_3&#39;]</pre><blockquote><em>\w+ → word character (letter, number, underscore)</em></blockquote><p>4. re.sub() = Replaces matched patterns</p><p>Replace all spaces with hyphens</p><pre>re.sub(r&quot;\s&quot;, &quot;-&quot;, &quot;Hello world how are you&quot;)<br># Output: &quot;Hello-world-how-are-you&quot;</pre><blockquote><em>\s → any whitespace character (space, tab, newline)</em></blockquote><h3>📘 Basic Syntax (Regex Characters)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*kLxl9L2zsXZtgO0a7Fty5A.png" /></figure><h3>✅ 1. Literal Characters</h3><p>Matches the exact character.</p><pre>re.search(r&quot;cat&quot;, &quot;A black cat&quot;)  # ✅ matches &quot;cat&quot;</pre><h3>✅ 2. Dot .</h3><p>Matches <strong>any single character</strong> (except newline).</p><pre>re.search(r&quot;c.t&quot;, &quot;cut&quot;)   # ✅ matches &quot;cut&quot;<br>re.search(r&quot;c.t&quot;, &quot;cat&quot;)   # ✅ matches &quot;cat&quot;</pre><h3>✅ 3. Character Set [ ]</h3><p>Matches <strong>any one character</strong> inside the brackets.</p><pre>re.search(r&quot;[aeiou]&quot;, &quot;sky&quot;)   # ✅ matches &quot;y&quot; is not vowel, but will not match here<br>re.search(r&quot;[cb]at&quot;, &quot;cat&quot;)    # ✅ matches &quot;cat&quot;<br>re.search(r&quot;[cb]at&quot;, &quot;bat&quot;)    # ✅ matches &quot;bat&quot;</pre><h3>✅ 4. Negated Set [^ ]</h3><p>Matches any character <strong>NOT in</strong> the brackets.</p><pre>re.search(r&quot;[^0-9]&quot;, &quot;abc123&quot;)  # ✅ matches &quot;a&quot; (first non-digit)</pre><h3>✅ 5. Dash - for Ranges</h3><pre>re.search(r&quot;[a-z]&quot;, &quot;ABCxY&quot;)    # ✅ matches &quot;x&quot;</pre><h3>✅ 6. Quantifiers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*RUv0A7CB_oB3ZAAixTtSzw.png" /></figure><h3>Examples:</h3><pre>re.search(r&quot;a*&quot;, &quot;aaabc&quot;)   # ✅ matches &quot;aaa&quot;<br>re.search(r&quot;a+&quot;, &quot;aaabc&quot;)   # ✅ matches &quot;aaa&quot;<br>re.search(r&quot;a{2,3}&quot;, &quot;aaabc&quot;)  # ✅ matches &quot;aaa&quot;</pre><h3>✅ 7. Anchors ^ and $</h3><ul><li>^ = Start of string</li><li>$ = End of string</li></ul><pre>re.match(r&quot;^Hello&quot;, &quot;Hello world&quot;)  # ✅ match at beginning<br>re.search(r&quot;world$&quot;, &quot;Hello world&quot;) # ✅ match at end</pre><h3>✅ 8. OR | (Pipe)</h3><pre>re.search(r&quot;cat|dog&quot;, &quot;I love dogs&quot;)  # ✅ matches &quot;dog&quot;</pre><h3>✅ 9. Grouping ( )</h3><p>Used to group parts of a pattern.</p><pre>re.search(r&quot;(cat|dog)s?&quot;, &quot;dogs&quot;)  # ✅ matches &quot;dogs&quot;</pre><h3>✅ 10. Escape Special Characters \</h3><p>Use backslash \ to escape special characters like . ^ $ * + ? { } [ ] \ | ( )</p><pre>re.search(r&quot;\.com&quot;, &quot;google.com&quot;)  # ✅ matches &quot;.com&quot;</pre><h3>📘 Part 2: Shorthand Character Classes</h3><p>Python regex provides <strong>shortcuts</strong> to common character sets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*LHjIjZ8PMtNz9cnSbRi-mQ.png" /></figure><h3>✅ Validate Nepalese Phone Number</h3><p>Starts with 98, 97, 96, or 99 and has 10 digits:</p><pre>pattern = r&quot;^9[6-9]\d{8}$&quot;<br>re.fullmatch(pattern, &quot;9801234567&quot;)  # ✅ Valid</pre><h3>✅ Extract All Numbers from Text</h3><pre>text = &quot;There are 2 cats and 3 dogs.&quot;<br>re.findall(r&quot;\d+&quot;, text)  # [&#39;2&#39;, &#39;3&#39;]</pre><h3>✅ Replace Whitespace with Hyphen</h3><pre>re.sub(r&quot;\s&quot;, &quot;-&quot;, &quot;Hello world&quot;)  # &quot;Hello-world&quot;</pre><h3>✅ Find All Words</h3><pre>re.findall(r&quot;\w+&quot;, &quot;Python_3 is cool!&quot;)  # [&#39;Python_3&#39;, &#39;is&#39;, &#39;cool&#39;]</pre><h3>🧪 Pro Tip: Combine Everything</h3><pre>text = &quot;My email is hello.world123@gmail.com and my number is 9801234567.&quot;<br>emails = re.findall(r&quot;[\w\.-]+@[\w\.-]+\.\w+&quot;, text)<br>phones = re.findall(r&quot;9[6-9]\d{8}&quot;, text)<br><br>print(&quot;Emails:&quot;, emails)<br>print(&quot;Phone Numbers:&quot;, phones)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7622b528a192" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to Encryption and Decryption in Python (For Beginners)]]></title>
            <link>https://medium.com/@sunilnepali844/complete-guide-to-encryption-and-decryption-in-python-for-beginners-61c2343c3f2b?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/61c2343c3f2b</guid>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Thu, 19 Jun 2025 12:21:02 GMT</pubDate>
            <atom:updated>2025-06-19T12:21:02.117Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re starting your journey into <strong>Python security</strong>, learning <strong>encryption and decryption</strong> is a must. Whether you’re building a messaging app, securing user data, or protecting your API, encryption plays a vital role.</p><p>This blog covers <strong>everything you need to know about encryption and decryption in Python</strong>. It’s beginner-friendly and includes clear code examples. By the end, you won’t need to Google another guide!</p><h3>🧠 What is Encryption and Decryption?</h3><ul><li><strong>Encryption</strong>: Turning readable data (called <em>plaintext</em>) into unreadable text (called <em>ciphertext</em>) using a key.</li><li><strong>Decryption</strong>: Converting the ciphertext back to plaintext using the key.</li></ul><p>Encryption ensures that sensitive data can’t be read by anyone except the intended recipient.</p><h3>🔑 Types of Encryption</h3><p>There are <strong>two main types</strong>:</p><h3>1. Symmetric Encryption</h3><ul><li>Uses the <strong>same key</strong> for both encryption and decryption.</li><li>Fast and efficient.</li></ul><h3>2. Asymmetric Encryption</h3><ul><li>Uses a <strong>pair of keys</strong>: one public, one private.</li><li>More secure for communication, but slower.</li></ul><h3>🧪 Popular Encryption Algorithms in Python</h3><p>Let’s dive into the most used algorithms and how to use them in Python.</p><h3>🔁 Symmetric Encryption Algorithms</h3><h3>1. AES (Advanced Encryption Standard)</h3><p><strong>🔧 Installation</strong>:</p><pre>pip install pycryptodome</pre><p><strong>✅ Code:</strong></p><pre>from Crypto.Cipher import AES<br>from Crypto.Random import get_random_bytes<br>from Crypto.Util.Padding import pad, unpad<br><br>key = get_random_bytes(16)<br>cipher = AES.new(key, AES.MODE_CBC)<br>data = b&quot;Secret Message&quot;<br>ciphertext = cipher.encrypt(pad(data, AES.block_size))<br>cipher_dec = AES.new(key, AES.MODE_CBC, cipher.iv)<br>plaintext = unpad(cipher_dec.decrypt(ciphertext), AES.block_size)<br>print(&quot;Decrypted:&quot;, plaintext.decode())</pre><p><strong>🧾 Explanation:</strong></p><ul><li>We import AES cipher and utility functions for padding.</li><li>A 16-byte (128-bit) key is generated randomly.</li><li>The message is padded and encrypted using CBC mode.</li><li>The same key and IV are used to decrypt and recover the original message.</li></ul><h3>2. Fernet (Easy AES + HMAC)</h3><p><strong>🔧 Installation</strong>:</p><pre>pip install cryptography</pre><p><strong>✅ Code:</strong></p><pre>from cryptography.fernet import Fernet<br><br>key = Fernet.generate_key()<br>f = Fernet(key)<br>ciphertext = f.encrypt(b&quot;Hello world!&quot;)<br>print(&quot;Encrypted:&quot;, ciphertext)<br>plaintext = f.decrypt(ciphertext)<br>print(&quot;Decrypted:&quot;, plaintext.decode())</pre><p><strong>🧾 Explanation:</strong></p><ul><li>Fernet uses AES encryption under the hood and includes integrity checks (HMAC).</li><li>It handles key generation, IV management, and padding automatically.</li><li>It’s great for beginners and secure enough for many applications.</li></ul><h3>🔓 Asymmetric Encryption Algorithm: RSA</h3><h3>✅ RSA (Public/Private Keys)</h3><p><strong>🔧 Installation</strong>:</p><pre>pip install cryptography</pre><p><strong>✅ Code:</strong></p><pre>from cryptography.hazmat.primitives.asymmetric import rsa, padding<br>from cryptography.hazmat.primitives import hashes<br><br>private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)<br>public_key = private_key.public_key()<br>message = b&quot;My secret message&quot;<br>ciphertext = public_key.encrypt(<br>    message,<br>    padding.OAEP(<br>        mgf=padding.MGF1(algorithm=hashes.SHA256()),<br>        algorithm=hashes.SHA256(),<br>        label=None<br>    )<br>)<br>plaintext = private_key.decrypt(<br>    ciphertext,<br>    padding.OAEP(<br>        mgf=padding.MGF1(algorithm=hashes.SHA256()),<br>        algorithm=hashes.SHA256(),<br>        label=None<br>    )<br>)<br>print(&quot;Decrypted:&quot;, plaintext.decode())</pre><p><strong>🧾 Explanation:</strong></p><ul><li>We generate an RSA private key and get its corresponding public key.</li><li>The message is encrypted using the public key and OAEP padding (secure method).</li><li>Only the private key can decrypt the ciphertext.</li><li>This is commonly used to encrypt small messages or share symmetric keys securely.</li></ul><h3>🚫 SHA256 Is Not Encryption (It’s Hashing!)</h3><p><strong>✅ Code:</strong></p><pre>import hashlib</pre><pre>password = &quot;mypassword&quot;<br>hashed = hashlib.sha256(password.encode()).hexdigest()<br>print(&quot;SHA256 Hashed:&quot;, hashed)</pre><p><strong>🧾 Explanation:</strong></p><ul><li>Hashing transforms data into a fixed-length value (digest).</li><li>It’s a one-way function: you can’t decrypt a hash.</li><li>Commonly used for storing passwords or verifying data integrity.</li></ul><h3>🤔 Which One Should You Use?</h3><p>Goal Recommended Algorithm Encrypt large files AES, Fernet Easy encryption Fernet Secure communication RSA High-performance on mobile ChaCha20 Store passwords securely SHA256 + salt (hashing)</p><h3>🔐 Real-World Tip: Use Hybrid Encryption</h3><ul><li>Encrypt AES key with RSA (for secure key exchange)</li><li>Encrypt large data with AES (fast!)</li></ul><p>This is how HTTPS works under the hood.</p><h3>✅ Summary</h3><ul><li>Symmetric = one key (AES, Fernet, ChaCha20)</li><li>Asymmetric = public/private keys (RSA)</li><li>Use <strong>Fernet</strong> for simple secure encryption.</li><li>Use <strong>AES</strong> for more control.</li><li>Use <strong>RSA</strong> for secure key exchange.</li><li>Use <strong>SHA256</strong> for hashing, not encryption.</li><li>Never use outdated algorithms like DES in production.</li></ul><h3>Commom question:</h3><p><strong>can we decrypt data encrypted with AES using another algorithm</strong></p><p>No, <strong>you cannot decrypt data encrypted with AES using another algorithm.</strong></p><h3>Here’s why:</h3><p>AES (Advanced Encryption Standard) is a <strong>symmetric encryption algorithm</strong> — it uses the <strong>same key</strong> for both <strong>encryption</strong> and <strong>decryption</strong>.</p><h3>🔒 Why can’t another algorithm be used for decryption?</h3><p>Encryption algorithms are not just about scrambling data — they follow <strong>very specific mathematical rules</strong> and <strong>transformation steps</strong>. These rules are tightly coupled with the encryption algorithm’s design.</p><p>So:</p><ul><li><strong>If you encrypt with AES</strong>, only the <strong>AES decryption process</strong> (with the same key and mode, like CBC, GCM, etc.) can reverse the process.</li><li>Trying to decrypt AES-encrypted data with something like <strong>RSA, DES, or Blowfish</strong> will just return <strong>garbage data</strong> — it won’t work at all.</li></ul><pre>from Crypto.Cipher import AES<br>from Crypto.Random import get_random_bytes<br><br># Encrypt with AES<br>key = get_random_bytes(16)  # 128-bit key<br>cipher = AES.new(key, AES.MODE_EAX)<br>ciphertext, tag = cipher.encrypt_and_digest(b&quot;Secret Message&quot;)<br><br># Try to decrypt with Fernet (different algorithm)<br>from cryptography.fernet import Fernet<br>fernet_key = Fernet.generate_key()<br>f = Fernet(fernet_key)<br>f.decrypt(ciphertext)  # This will raise an error!</pre><h3>✅ Summary:</h3><ul><li>❌ You <strong>cannot</strong> decrypt AES data using another algorithm.</li><li>✅ You <strong>must</strong> use AES decryption with the <strong>same key and mode</strong>.</li></ul><h3>🔒 General Rule:</h3><blockquote><strong><em>You can only decrypt data using the same algorithm, key, and configuration that was used to encrypt it.</em></strong></blockquote><h3>📌 Why?</h3><p>Encryption and decryption are <strong>mathematical inverses</strong> of each other — they’re designed as a <strong>matched pair</strong>. Each algorithm (AES, RSA, Blowfish, Fernet, etc.) has its own:</p><ul><li>Key structure and length requirements</li><li>Block size and mode of operation (e.g., CBC, GCM, ECB)</li><li>Padding mechanisms</li><li>Initialization vectors (IVs) or nonces</li></ul><p>Using a different algorithm (or even the same algorithm with different mode or key) will not correctly reverse the encryption process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61c2343c3f2b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Dates, Times, and Timezones in Python and Django]]></title>
            <link>https://medium.com/@sunilnepali844/working-with-dates-times-and-timezones-in-python-and-django-e8bab0f415ed?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8bab0f415ed</guid>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[timezone]]></category>
            <category><![CDATA[python-time-series]]></category>
            <category><![CDATA[python-datetime]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Tue, 20 May 2025 11:23:02 GMT</pubDate>
            <atom:updated>2025-06-23T10:56:42.957Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aoTz4tMNn8iUOzIKPy2vEA.png" /></figure><h3>What is datetime?</h3><p>Python’s datetime module provides classes to work with:</p><ul><li><strong>Dates</strong> (year, month, day)</li><li><strong>Times</strong> (hour, minute, second, microsecond)</li><li><strong>Combined Date + Time</strong></li><li><strong>Time intervals</strong></li><li><strong>Time zones</strong></li></ul><p>Importing the module</p><pre>import datetime<br>from datetime import datetime, date, time, timedelta</pre><h3>1. datetime.date — Just Date (No Time)</h3><h3>✅ Creating a date object:</h3><pre>from datetime import date<br><br>d = date(2025, 5, 20)<br>print(d)  # 2025-05-20</pre><h3>✅ Today’s date:</h3><pre>today = date.today()<br>print(today)</pre><h3>✅ Accessing parts:</h3><pre>print(today.year, today.month, today.day)</pre><h3>2. datetime.time — Just Time (No Date)</h3><pre>from datetime import time<br><br>t = time(14, 30, 45)<br>print(t)  # 14:30:45</pre><h3>✅ Accessing parts:</h3><pre>print(t.hour, t.minute, t.second)</pre><h3>3. datetime.datetime — Date + Time Combined</h3><h3>✅Creating manually:</h3><pre>from datetime import datetime<br><br>dt = datetime(2025, 5, 20, 14, 30, 0)<br>print(dt)  # 2025-05-20 14:30:00</pre><h3>✅ Current date and time:</h3><pre>now = datetime.now()<br>utc_now = datetime.utcnow()  # UTC time (no timezone info)</pre><h3>4. Parsing and Formatting Dates/Times</h3><h3>✅ strptime — Parse string to datetime object:</h3><pre>dt = datetime(2025, 5, 20, 14, 30, 0)<br>dt = datetime.strptime(&quot;2025-05-20 14:30&quot;, &quot;%Y-%m-%d %H:%M&quot;)<br>print(dt)</pre><h3>✅ strftime — Format datetime object to string:</h3><h3>What is strptime?</h3><p>strptime <strong>parses a date string</strong> and <strong>converts it into a </strong><strong>datetime object</strong>, based on a <strong>specified format</strong>.</p><p>It stands for: <strong>str</strong>ing <strong>p</strong>arse <strong>t</strong>ime</p><p>Syntax</p><pre>from datetime import datetime<br><br>datetime.strptime(date_string, format_string)</pre><h3>Example Code</h3><pre>#Example 1<br>from datetime import datetime<br><br>date_string = &quot;2025-05-20&quot;<br>format_string = &quot;%Y-%m-%d&quot;<br><br>date_object = datetime.strptime(date_string, format_string)<br><br>print(&quot;Parsed datetime object:&quot;, date_object)<br><br>#Output Parsed datetime object: 2025-05-20 00:00:00<br><br>#Example 2<br>from datetime import datetime<br><br>date_str = &quot;20/05/2025 14:30:45&quot;<br>format_str = &quot;%d/%m/%Y %H:%M:%S&quot;<br><br>dt = datetime.strptime(date_str, format_str)<br><br>print(dt)<br><br>#Output<br>2025-05-20 14:30:45<br><br>#Example 3<br>dt = datetime.now()<br>formatted = dt.strftime(&quot;%d %B %Y, %I:%M %p&quot;)<br>print(formatted)  # Example: 20 May 2025, 02:30 PM</pre><h3>🧾 Common format codes:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*E_NgpYhOzJvFsxvbjmYjGQ.png" /></figure><h3>5. datetime.timedelta — Time Difference</h3><h3>✅Basic usage:</h3><pre>from datetime import timedelta<br><br>delta = timedelta(days=5, hours=3)<br>print(delta)  # 5 days, 3:00:00</pre><h3>✅ Adding/subtracting:</h3><pre>now = datetime.now()<br>future = now + timedelta(days=10)<br>past = now - timedelta(days=3)</pre><h3>✅ Difference between dates:</h3><pre>d1 = date(2025, 5, 25)<br>d2 = date(2025, 5, 20)<br>diff = d1 - d2<br>print(diff.days)  # 5</pre><h3>6. Timezones (datetime.timezone, pytz, zoneinfo)</h3><h3>✅ Basic timezone support:</h3><pre>from datetime import datetime, timezone, timedelta<br><br>dt = datetime.now(timezone.utc)<br>print(dt)  # 2025-05-20T14:30:00+00:00</pre><h3>✅ Convert to local time:</h3><pre>local_time = dt.astimezone()</pre><h3>✅ Using zoneinfo (Python 3.9+):</h3><pre>from zoneinfo import ZoneInfo<br><br>dt = datetime.now(ZoneInfo(&quot;Asia/Kolkata&quot;))<br>print(dt)</pre><h3>✅ If using pytz to change timezone:</h3><p>In this example i change current time into Asia/Kathmandu</p><pre>import pytz<br><br>ktm_timezone = pytz.timezone(&quot;Asia/Kathmandu&quot;)<br>dt = datetime.now(ktm_timezone)</pre><h4>Bonus Tip</h4><p>If you are using django</p><p>in settings.py</p><pre><br>TIME_ZONE = &#39;UTC&#39;<br><br>USE_TZ = True</pre><p><strong>datetime.now():</strong></p><p>When you use datetime.now() <strong>(from the standard </strong><strong>datetime module)</strong>, it gives the server&#39;s local time, which in Singapore would be UTC+8.</p><p>if you are in local it gives your current <a href="http://localhost/">localhost</a> server current time</p><p><strong>timezone.now():</strong></p><p>from django.utils import timezone</p><p>So, <strong>if you use </strong><strong>timezone.now() and </strong><strong>USE_TZ = True,</strong> then <strong>Django return the time in UTC.</strong>— no matter where your server is.</p><h4>to get current specific timezone datetime</h4><p>datetime.now(pytz.timezone(“Asia/Kathmandu”))</p><h4>convert timezone</h4><p>dt= datetime.now()</p><p>nepal_time = dt.astimezone(pytz.timezone(‘Asia/Kathmandu’))</p><h3>7. Comparing Dates &amp; Times</h3><pre>d1 = datetime(2025, 5, 20, 10, 0)<br>d2 = datetime(2025, 5, 20, 12, 0)<br><br>print(d1 &lt; d2)       # True<br>print(d2 - d1)       # timedelta of 2 hours</pre><h3>8. ISO Format (for APIs, JSON)</h3><h3>✅ Convert to ISO string:</h3><pre>dt = datetime.now()<br>iso_string = dt.isoformat()<br>print(iso_string)  # 2025-05-20T14:30:00</pre><h3>✅ Parse from ISO string:</h3><pre>dt = datetime.fromisoformat(&quot;2025-05-20T14:30:00&quot;)</pre><h3>9. make_aware</h3><h3>What is make_aware?</h3><p>make_aware is a function used to <strong>convert a naive datetime into an aware datetime</strong> by attaching a <strong>timezone</strong>.</p><p><strong>Naive datetime</strong>: No timezone info.</p><pre>datetime(2025, 5, 20, 12, 0)  # Naive<br></pre><p><strong>Aware datetime</strong>: Has timezone info attached.</p><pre>datetime(2025, 5, 20, 12, 0, tzinfo=ZoneInfo(&quot;Asia/Kolkata&quot;))  # Aware</pre><h3>✅ When and Why Use make_aware</h3><h4>Situation:</h4><p>You’re working with user input or logs that are in <strong>local time</strong> but have <strong>no timezone info</strong></p><p>You’re storing timestamps in a timezone-aware system (like Django with USE_TZ=True)</p><h4>Why You Use make_aware:</h4><p>You need to “tell Python” which timezone this naive time is in.</p><p>Datetimes must be aware to avoid errors and keep time consistent across timezones.</p><h4>Example in Django</h4><pre>from datetime import datetime<br>from django.utils.timezone import make_aware<br>from zoneinfo import ZoneInfo  # Python 3.9+<br><br># Naive datetime (no timezone)<br>naive_dt = datetime(2025, 5, 20, 12, 0)<br><br># Make it aware using system timezone<br>aware_dt = make_aware(naive_dt, timezone=ZoneInfo(&quot;Asia/Kolkata&quot;))<br><br>print(aware_dt)<br><br>#Output<br>2025-05-20 12:00:00+05:30</pre><h3>10. Useful Tips &amp; Utilities</h3><h3>✅ Get start of day:</h3><pre>today_start = datetime.combine(date.today(), time.min) # 00:00:00</pre><h3>✅ Get end of day:</h3><pre>today_end = datetime.combine(date.today(), time.max) # 12:60:60</pre><h3>✅ Get first/last day of the month:</h3><pre>from calendar import monthrange<br><br>year, month = 2025, 5<br>first = date(year, month, 1)<br>last = date(year, month, monthrange(year, month)[1])</pre><h3>✅Changing Timezone WITHOUT Changing the Time</h3><p>Sometimes, you want to <strong>relabel</strong> a datetime’s timezone, but keep the exact clock time.</p><h3>❌ Wrong: This changes the time</h3><pre>dt.astimezone(ZoneInfo(&quot;Asia/Kathmandu&quot;))</pre><h3>✅ Right: This keeps the same clock time</h3><pre>from datetime import datetime<br>from zoneinfo import ZoneInfo<br><br># Say this is 4:31 in US time, but you want it to be 4:31 in Nepal time<br>naive = datetime(2025, 5, 20, 4, 31)<br>relabelled = naive.replace(tzinfo=ZoneInfo(&quot;Asia/Kathmandu&quot;))</pre><blockquote>This is useful for manual event creation or when user input is already in local time.</blockquote><h3>✅ Reusable Python Helper (Bonus)</h3><pre>from datetime import datetime<br>from zoneinfo import ZoneInfo<br>from django.utils.timezone import make_aware<br><br>def parse_date_with_timezone(date_str, fmt=&quot;%Y-%m-%d %H:%M&quot;, tz=&quot;Asia/Kathmandu&quot;):<br>    naive = datetime.strptime(date_str, fmt)<br>    return make_aware(naive, timezone=ZoneInfo(tz))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*36a9qWhdhkv0lgzduR6omw.png" /></figure><h3>11. Dates and Times Between Frontend and Backend</h3><h3>✅ Query Parameters (e.g., from the URL)</h3><p>When you send dates in the URL (query params), they come in as <strong>strings</strong>:</p><p>?created_date=2024–01–01,2024–01–31</p><h4>On the Django Backend:</h4><pre>from datetime import datetime<br><br>created_date = self.request.query_params.get(&quot;created_date&quot;, None)<br><br>if created_date:<br>    start_str, end_str = created_date.split(&#39;,&#39;)<br>    start_date = datetime.strptime(start_str, &quot;%Y-%m-%d&quot;).date()<br>    end_date = datetime.strptime(end_str, &quot;%Y-%m-%d&quot;).date()<br>    queryset = queryset.filter(created_on__range=[start_date, end_date])</pre><blockquote>strptime is used to <strong>parse a string into a datetime object</strong>.</blockquote><h3>✅ Sending Date in Request Body (JSON)</h3><p>On the frontend (JavaScript), if you’re sending a date in the request body:</p><pre>class DateUtils {<br>  formatFullDate(date) {<br>    return moment(date).format(&#39;YYYY-MM-DD&#39;);<br>  }<br>}</pre><pre>created_date: dateUtils.formatFullDate(values.created_date)</pre><p>If your form field is already a JavaScript Date object, you <strong>should still format it</strong> before sending to the backend as a string. Python expects strings unless using serializers that parse it automatically.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8bab0f415ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complete Guide to Working with CSV Files in Python]]></title>
            <link>https://medium.com/@sunilnepali844/complete-guide-to-working-with-csv-files-in-python-d85036ec5715?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/d85036ec5715</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas-csv]]></category>
            <category><![CDATA[dataframe-to-csv-python]]></category>
            <category><![CDATA[csv-file]]></category>
            <category><![CDATA[csv]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Sun, 11 May 2025 04:21:59 GMT</pubDate>
            <atom:updated>2025-05-11T16:06:26.991Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EEmSg0YVErnBMkUyGe7lpA.jpeg" /></figure><h3>Introduction</h3><p>CSV (Comma-Separated Values) files are simple text files where data is organized in rows and columns, with commas separating each value. They’re like simplified spreadsheets that can be opened in programs like Excel, but they’re also easy to work with in programming languages like Python.</p><p>In this guide, we’ll cover everything you need to know about working with CSV files in Python — from reading and writing basic files to handling more complex scenarios. By the end, you’ll be a CSV-wrangling pro!</p><h3>Table of Contents</h3><ol><li>What is a CSV File?</li><li>Setting Up Your Python Environment</li><li>Reading CSV Files</li><li>Writing CSV Files (Using writerow() Using writerows())</li><li>Working with Headers</li><li>Handling Different Delimiters</li><li>Dealing with Special Characters and Quotes</li><li>CSV with Pandas</li><li>Real-World Examples</li><li>Common Errors and Troubleshooting</li><li>Best Practices</li></ol><h3>What is a CSV File?</h3><p>A CSV file is exactly what its name suggests — a file where values are separated by commas. Each line in the file represents a row of data, and the values within each line are separated by commas.</p><p>Here’s what a simple CSV file might look like:</p><pre>name,age,city<br>John,25,New York<br>Sarah,30,San Francisco<br>Mike,22,Chicago</pre><p>This represents a table with 3 rows of data (plus a header row) and 3 columns: name, age, and city.</p><h3>Setting Up Your Python Environment</h3><p>To work with CSV files in Python, you’ll need the built-in csv module, which comes standard with any Python installation. No additional installations needed!</p><p>Simply import it at the beginning of your Python script:</p><pre>import csv</pre><h3>Reading CSV Files</h3><p>Let’s start with the basics — reading data from a CSV file. Here’s a step-by-step approach:</p><h3>Simple CSV Reading</h3><pre>import csv<br><br># Open the CSV file<br>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    # Create a CSV reader object<br>    csv_reader = csv.reader(file)<br>    <br>    # Read and print each row<br>    for row in csv_reader:<br>        print(row)</pre><p>When you run this code, you’ll see each row printed as a list of values.</p><h3>Reading into a List</h3><p>If you want to store all the CSV data in memory as a list:</p><pre>import csv<br><br># Open the CSV file<br>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    # Create a CSV reader object<br>    csv_reader = csv.reader(file)<br>    <br>    # Convert to list<br>    data = list(csv_reader)<br>    <br>print(data)  # This will be a list of lists</pre><h3>Reading with DictReader</h3><p>A more convenient way to read CSV files is to use csv.DictReader. This treats the first row as headers and returns each row as a dictionary:</p><pre>import csv<br><br>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    csv_reader = csv.DictReader(file)<br>    <br>    for row in csv_reader:<br>        # Each row is now a dictionary where keys are the column names<br>        print(f&quot;Name: {row[&#39;name&#39;]}, Age: {row[&#39;age&#39;]}, City: {row[&#39;city&#39;]}&quot;)</pre><p>This approach is much more readable when working with files that have headers.</p><h3>Writing CSV Files</h3><p>Now let’s look at writing data to CSV files. There are two main methods: writerow() for writing a single row, and writerows() for writing multiple rows at once.</p><h3>Using writerow()</h3><p>The writerow() method writes a single row to a CSV file. Here&#39;s how to use it:</p><pre>import csv<br><br># Data to write<br>header = [&#39;Name&#39;, &#39;Age&#39;, &#39;City&#39;]<br>row1 = [&#39;John&#39;, 25, &#39;New York&#39;]<br>row2 = [&#39;Sarah&#39;, 30, &#39;San Francisco&#39;]<br>row3 = [&#39;Mike&#39;, 22, &#39;Chicago&#39;]<br># Open a file for writing<br>with open(&#39;new_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Create a CSV writer object<br>    writer = csv.writer(file)<br>    <br>    # Write the header<br>    writer.writerow(header)<br>    <br>    # Write individual rows<br>    writer.writerow(row1)<br>    writer.writerow(row2)<br>    writer.writerow(row3)<br>print(&quot;CSV file has been created successfully.&quot;)</pre><p>Important notes about the code above:</p><ul><li>We use newline=&#39;&#39; when opening the file to avoid extra blank lines between rows (especially important on Windows).</li><li>The writerow() method takes a list or any iterable as an argument.</li></ul><h3>Using writerows()</h3><p>If you have multiple rows to write, you can use writerows() to write them all at once:</p><pre>import csv<br><br># Data to write<br>header = [&#39;Name&#39;, &#39;Age&#39;, &#39;City&#39;]<br>rows = [<br>    [&#39;John&#39;, 25, &#39;New York&#39;],<br>    [&#39;Sarah&#39;, 30, &#39;San Francisco&#39;],<br>    [&#39;Mike&#39;, 22, &#39;Chicago&#39;]<br>]<br># Open a file for writing<br>with open(&#39;new_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Create a CSV writer object<br>    writer = csv.writer(file)<br>    <br>    # Write the header<br>    writer.writerow(header)<br>    <br>    # Write all rows at once<br>    writer.writerows(rows)<br>print(&quot;CSV file has been created successfully.&quot;)</pre><p>The writerows() method takes a list of lists (or any iterable of iterables) and writes each inner list as a row in the CSV file.</p><h3>Writing with DictWriter</h3><p>Similar to DictReader, Python also provides a DictWriter for writing rows as dictionaries:</p><pre>import csv<br><br># Data to write<br>data = [<br>    {&#39;Name&#39;: &#39;John&#39;, &#39;Age&#39;: 25, &#39;City&#39;: &#39;New York&#39;},<br>    {&#39;Name&#39;: &#39;Sarah&#39;, &#39;Age&#39;: 30, &#39;City&#39;: &#39;San Francisco&#39;},<br>    {&#39;Name&#39;: &#39;Mike&#39;, &#39;Age&#39;: 22, &#39;City&#39;: &#39;Chicago&#39;}<br>]<br># Field names (column headers)<br>fieldnames = [&#39;Name&#39;, &#39;Age&#39;, &#39;City&#39;]<br># Open a file for writing<br>with open(&#39;dict_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Create a DictWriter object<br>    writer = csv.DictWriter(file, fieldnames=fieldnames)<br>    <br>    # Write the header<br>    writer.writeheader()<br>    <br>    # Write rows from list of dictionaries<br>    writer.writerows(data)<br>print(&quot;CSV file has been created successfully.&quot;)</pre><p>This approach is very convenient when your data is already in dictionary format or when column names are complex.</p><h3>Working with Headers</h3><p>Headers are the first row in a CSV file that describe what each column represents. Here’s how to handle them properly:</p><h3>Skipping Headers When Reading</h3><p>If you need to skip the header row when reading:</p><pre>import csv<br><br>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    csv_reader = csv.reader(file)<br>    <br>    # Skip the header row<br>    next(csv_reader)<br>    <br>    # Now process the data rows<br>    for row in csv_reader:<br>        print(row)</pre><h3>Extracting Headers Separately</h3><p>If you want to extract the headers separately:</p><pre>import csv<br><br>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    csv_reader = csv.reader(file)<br>    <br>    # Get the header row<br>    headers = next(csv_reader)<br>    print(f&quot;Headers: {headers}&quot;)<br>    <br>    # Process the data rows<br>    for row in csv_reader:<br>        print(row)</pre><h3>Handling Different Delimiters</h3><p>Not all CSV files use commas as separators. Some use tabs, semicolons, or other characters.</p><h3>Reading Files with Different Delimiters</h3><pre>import csv<br><br># For tab-separated values (TSV)<br>with open(&#39;data.tsv&#39;, &#39;r&#39;) as file:<br>    tsv_reader = csv.reader(file, delimiter=&#39;\t&#39;)<br>    <br>    for row in tsv_reader:<br>        print(row)<br># For semicolon-separated values<br>with open(&#39;data_semicolon.csv&#39;, &#39;r&#39;) as file:<br>    csv_reader = csv.reader(file, delimiter=&#39;;&#39;)<br>    <br>    for row in csv_reader:<br>        print(row)</pre><h3>Writing Files with Different Delimiters</h3><pre>import csv<br><br>data = [<br>    [&#39;Name&#39;, &#39;Age&#39;, &#39;City&#39;],<br>    [&#39;John&#39;, 25, &#39;New York&#39;],<br>    [&#39;Sarah&#39;, 30, &#39;San Francisco&#39;]<br>]<br># Writing tab-separated values<br>with open(&#39;output.tsv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    tsv_writer = csv.writer(file, delimiter=&#39;\t&#39;)<br>    tsv_writer.writerows(data)<br># Writing semicolon-separated values<br>with open(&#39;output_semicolon.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    csv_writer = csv.writer(file, delimiter=&#39;;&#39;)<br>    csv_writer.writerows(data)</pre><h3>Dealing with Special Characters and Quotes</h3><p>CSV files can get complicated when the data itself contains commas, quotes, or newlines.</p><h3>Handling Quoting</h3><p>Python’s CSV module handles quoting for you, but you can control how it works:</p><pre>import csv<br><br>data = [<br>    [&#39;Name&#39;, &#39;Description&#39;],<br>    [&#39;Product A&#39;, &#39;This is a &quot;special&quot; product&#39;],<br>    [&#39;Product B&#39;, &#39;This product costs $10,000&#39;]<br>]<br>with open(&#39;quoted_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Use QUOTE_MINIMAL (default) - only quote fields that need it<br>    writer = csv.writer(file, quoting=csv.QUOTE_MINIMAL)<br>    writer.writerows(data)<br>with open(&#39;all_quoted_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Quote all fields regardless<br>    writer = csv.writer(file, quoting=csv.QUOTE_ALL)<br>    writer.writerows(data)</pre><p>Available quoting options:</p><ul><li>csv.QUOTE_MINIMAL: Quote fields only if they contain special characters</li><li>csv.QUOTE_ALL: Quote all fields</li><li>csv.QUOTE_NONNUMERIC: Quote fields that don&#39;t contain numbers</li><li>csv.QUOTE_NONE: Never quote fields (must provide escapechar)</li></ul><h3>Escaping Characters</h3><p>If your data contains the delimiter character, you might need to escape it:</p><pre>import csv<br><br>data = [<br>    [&#39;ID&#39;, &#39;Text with, comma&#39;],<br>    [1, &#39;This text has a, comma in it&#39;]<br>]<br>with open(&#39;escaped_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.writer(file, escapechar=&#39;\\&#39;)<br>    writer.writerows(data)</pre><h3>CSV with Pandas</h3><p>For more advanced data processing, the Pandas library offers excellent support for CSV files:</p><pre>import pandas as pd<br><br># Reading a CSV file into a DataFrame<br>df = pd.read_csv(&#39;data.csv&#39;)<br># Display the first 5 rows<br>print(df.head())<br># Perform some operations<br># For example, filter rows where age &gt; 25<br>filtered_df = df[df[&#39;age&#39;] &gt; 25]<br>print(filtered_df)<br># Write the DataFrame back to a CSV file<br>filtered_df.to_csv(&#39;filtered_data.csv&#39;, index=False)</pre><p>Pandas is particularly useful when you need to:</p><ul><li>Handle large CSV files</li><li>Perform data analysis</li><li>Clean and transform data</li><li>Filter, sort, and aggregate values</li></ul><h3>Real-World Examples</h3><p>Let’s put everything together with some practical examples:</p><h3>Example 1: Processing Sales Data</h3><pre>import csv<br>from datetime import datetime<br><br># Read sales data and calculate total sales by product<br>sales_by_product = {}<br>with open(&#39;sales_data.csv&#39;, &#39;r&#39;) as file:<br>    reader = csv.DictReader(file)<br>    <br>    for row in reader:<br>        product = row[&#39;product_name&#39;]<br>        quantity = int(row[&#39;quantity&#39;])<br>        price = float(row[&#39;price&#39;])<br>        sale_amount = quantity * price<br>        <br>        if product in sales_by_product:<br>            sales_by_product[product] += sale_amount<br>        else:<br>            sales_by_product[product] = sale_amount<br># Write the results to a new CSV file<br>with open(&#39;sales_summary.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    writer = csv.writer(file)<br>    <br>    # Write header<br>    writer.writerow([&#39;Product&#39;, &#39;Total Sales&#39;])<br>    <br>    # Write data rows<br>    for product, total in sales_by_product.items():<br>        writer.writerow([product, f&quot;${total:.2f}&quot;])<br>print(&quot;Sales summary has been created.&quot;)</pre><h3>Example 2: Converting Between CSV Formats</h3><pre>import csv<br><br># Convert a semicolon-separated file to a comma-separated one<br>with open(&#39;european_data.csv&#39;, &#39;r&#39;) as infile:<br>    # European format often uses semicolons and commas for decimal points<br>    reader = csv.reader(infile, delimiter=&#39;;&#39;)<br>    data = list(reader)<br>with open(&#39;us_format_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as outfile:<br>    writer = csv.writer(outfile)<br>    writer.writerows(data)<br>print(&quot;File format conversion complete.&quot;)</pre><h3>Example 3: Merging Multiple CSV Files</h3><pre>import csv<br>import glob<br><br># Get all CSV files in a directory<br>csv_files = glob.glob(&#39;data/*.csv&#39;)<br># Prepare the merged data<br>all_data = []<br>header_saved = False<br>for file in csv_files:<br>    with open(file, &#39;r&#39;) as infile:<br>        reader = csv.reader(infile)<br>        <br>        # Get header from first file only<br>        if not header_saved:<br>            header = next(reader)<br>            all_data.append(header)<br>            header_saved = True<br>        else:<br>            next(reader)  # Skip header in subsequent files<br>        <br>        # Add all rows from this file<br>        for row in reader:<br>            all_data.append(row)<br># Write all data to a single merged file<br>with open(&#39;merged_data.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as outfile:<br>    writer = csv.writer(outfile)<br>    writer.writerows(all_data)<br>print(f&quot;Successfully merged {len(csv_files)} CSV files.&quot;)</pre><h3>Common Errors and Troubleshooting</h3><p>Here are some common issues you might encounter when working with CSV files and how to solve them:</p><h3>1. Extra Blank Lines in Output</h3><p><strong>Problem</strong>: Your CSV file has extra blank lines between data rows.</p><p><strong>Solution</strong>: Use newline=&#39;&#39; when opening files for writing:</p><pre>with open(&#39;output.csv&#39;, &#39;w&#39;, newline=&#39;&#39;) as file:<br>    # Your code here</pre><h3>2. Encoding Issues</h3><p><strong>Problem</strong>: Special characters appear as garbled text.</p><p><strong>Solution</strong>: Specify the file encoding:</p><pre>with open(&#39;data.csv&#39;, &#39;r&#39;, encoding=&#39;utf-8&#39;) as file:<br>    # Your code here</pre><h3>3. Inconsistent Number of Columns</h3><p><strong>Problem</strong>: Some rows have more or fewer columns than others.</p><p><strong>Solution</strong>: Use the strictfieldcount parameter (Python 3.8+) or handle the exception:</p><pre>try:<br>    with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>        reader = csv.reader(file)<br>        for row in reader:<br>            # Process row<br>except csv.Error as e:<br>    print(f&quot;Error in row {reader.line_num}: {e}&quot;)</pre><h3>4. Issues with Quotes or Delimiters in Data</h3><p><strong>Problem</strong>: Data with quotes or commas causes parsing errors.</p><p><strong>Solution</strong>: Configure the dialect or quoting options:</p><pre>with open(&#39;data.csv&#39;, &#39;r&#39;) as file:<br>    reader = csv.reader(<br>        file,<br>        quoting=csv.QUOTE_ALL,<br>        escapechar=&#39;\\&#39;<br>    )<br>    # Your code here</pre><h3>Best Practices</h3><p>Follow these guidelines to make your CSV handling code more robust:</p><ol><li><strong>Always use the </strong><strong>with statement</strong> when opening files to ensure they are properly closed.</li><li><strong>Specify </strong><strong>newline=&#39;&#39;</strong> when opening files for writing to prevent platform-specific line ending issues.</li><li><strong>Consider using </strong><strong>DictReader and </strong><strong>DictWriter</strong> for more readable code, especially when working with headers.</li><li><strong>Handle exceptions</strong> that might occur during file operations.</li><li><strong>Validate your data</strong> before writing it to CSV files.</li><li><strong>Use Pandas for complex operations</strong> like filtering, sorting, or transforming data.</li><li><strong>Document your CSV format</strong> including the delimiter, quoting rules, and column definitions.</li><li><strong>For large files</strong>, consider processing the data in chunks rather than loading everything into memory.</li></ol><h3>Conclusion</h3><p>Working with CSV files in Python is straightforward thanks to the built-in csv module. You can easily read from and write to CSV files with just a few lines of code. For more complex data manipulation, consider using the Pandas library which builds on top of these basics.</p><p>Remember that CSV is a simple but powerful format for data exchange. With the techniques covered in this guide, you’ll be well-equipped to handle nearly any CSV-related task that comes your way.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d85036ec5715" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Anonymous User Sessions in Django: A Complete Guide]]></title>
            <link>https://medium.com/@sunilnepali844/handling-anonymous-user-sessions-in-django-a-complete-guide-78fb563a28b2?source=rss-4ddbacb46008------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fb563a28b2</guid>
            <category><![CDATA[user-session]]></category>
            <category><![CDATA[ecommerce-cart]]></category>
            <category><![CDATA[anonymous-user]]></category>
            <category><![CDATA[django-sessions]]></category>
            <dc:creator><![CDATA[Sunil Nepali]]></dc:creator>
            <pubDate>Sat, 10 May 2025 11:55:41 GMT</pubDate>
            <atom:updated>2025-05-10T11:55:41.794Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HVKOLLX7wprRbHTl2IPDcQ.png" /></figure><p>Have you ever wondered how websites remember your shopping cart even before you log in? Or how your to-do list persists after you create an account? This “magic” happens through session management — a critical but often confusing aspect of web development.</p><p>In this comprehensive guide, I’ll explain how to handle anonymous user sessions in Django, using practical examples from e-commerce carts and to-do apps. By the end, you’ll know exactly how to implement this in development and production environments.</p><h3>What Are Sessions and Why Do They Matter?</h3><p>A session is a way to store data specific to a user across multiple requests. Unlike cookies that store data in the user’s browser, sessions store the data on the server side, with only a session ID stored in the cookie.</p><p>For applications like shopping carts or to-do lists, sessions are crucial because they allow you to:</p><ul><li>Track anonymous users before they create accounts</li><li>Maintain state across page visits</li><li>Transfer data when an anonymous user logs in or registers</li></ul><h3>Setting Up Django Sessions</h3><p>Django has built-in session management, but configuring it correctly requires attention to detail.</p><h3>Development Environment Configuration</h3><p>Let’s start with a development setup that allows cross-origin requests (useful when your frontend runs on a different port):</p><pre># settings.py (Development)<br><br># Security settings<br>DEBUG = True<br>SESSION_COOKIE_SECURE = False      # allow over HTTP<br>CSRF_COOKIE_SECURE = False         # allow over HTTP<br># Cross-origin settings<br>SESSION_COOKIE_SAMESITE = &#39;None&#39;   # necessary for cross-site AJAX<br>CSRF_COOKIE_SAMESITE = &#39;None&#39;      # ditto<br>SESSION_COOKIE_DOMAIN = &#39;localhost&#39;  # match your frontend host<br>CSRF_COOKIE_DOMAIN = &#39;localhost&#39;<br># Protection settings<br>SESSION_COOKIE_HTTPONLY = True     # protect against XSS<br>CSRF_COOKIE_HTTPONLY = True<br># CORS configuration<br>INSTALLED_APPS += [&#39;corsheaders&#39;]<br>MIDDLEWARE = [&#39;corsheaders.middleware.CorsMiddleware&#39;, ...other middleware...]<br>CORS_ALLOWED_ORIGINS = [<br>    &quot;http://localhost:5173&quot;,       # your frontend URL<br>]<br>CORS_ALLOW_CREDENTIALS = True      # allow cookies in cross-origin requests</pre><ul><li>Disabling Secure lets cookies travel over HTTP <a href="https://medium.com/%40ayoubennaoui20/building-a-shopping-cart-in-django-a-step-by-step-guide-d696439ec6e5?utm_source=chatgpt.com">Medium</a>.</li><li>SameSite=None plus CORS_ALLOW_CREDENTIALS=True ensures the browser sends sessionid on AJAX calls to your API</li></ul><h3>Production Environment Configuration</h3><p>In production, you’ll want stricter security:</p><pre># settings.py (Production)<br><br>DEBUG = False<br>SESSION_COOKIE_SECURE = True       # require HTTPS<br>CSRF_COOKIE_SECURE = True          # require HTTPS<br>SESSION_COOKIE_SAMESITE = &#39;Lax&#39;    # more secure, but some cross-site flows may break<br>CSRF_COOKIE_SAMESITE = &#39;Lax&#39;       # more secure<br>SESSION_COOKIE_DOMAIN = &#39;.example.com&#39;  # allow subdomains<br>CSRF_COOKIE_DOMAIN = &#39;.example.com&#39;     # allow subdomains<br># Keep HttpOnly protection<br>SESSION_COOKIE_HTTPONLY = True<br>CSRF_COOKIE_HTTPONLY = True<br># Still need CORS if your frontend is separate<br>CORS_ALLOWED_ORIGINS = [<br>    &quot;https://www.example.com&quot;,<br>    &quot;https://app.example.com&quot;,<br>]<br>CORS_ALLOW_CREDENTIALS = True</pre><ul><li>Secure=True guarantees cookies only go over an encrypted channels.</li><li>Using SameSite=&#39;Lax&#39; is a balanced default; if you need full cross-site, switch to None but remember it mandates Secure=True</li></ul><h3>Frontend Setup: Making Axios Work with Sessions</h3><p>For the frontend to properly handle sessions, your API requests must include credentials. Using Axios (a popular HTTP client for JavaScript), here’s how to set it up:</p><pre>// customAxios.ts<br>import axios from &#39;axios&#39;;<br><br>const CustomAxios = axios.create({<br>    baseURL: process.env.REACT_APP_API_URL || &#39;http://localhost:8000&#39;,<br>    withCredentials: true,  // THIS IS CRUCIAL for sessions to work!<br>    headers: {<br>        &#39;Content-Type&#39;: &#39;application/json&#39;,<br>    }<br>});<br>// Add interceptors for logging/debugging if needed<br>CustomAxios.interceptors.request.use(<br>    (config) =&gt; {<br>        console.log(&#39;Sending request with cookies:&#39;, document.cookie);<br>        return config;<br>    },<br>    (error) =&gt; Promise.reject(error)<br>);<br>export default CustomAxios;<br>// Using it:<br>const getCart = async () =&gt; {<br>    const response = await CustomAxios.get(&#39;/api/cart/current/&#39;);<br>    return response.data;<br>};<br>const addToCart = async (productId, quantity) =&gt; {<br>    const response = await CustomAxios.post(&#39;/api/cart/items/&#39;, {<br>        product: productId,<br>        quantity: quantity<br>    });<br>    return response.data;<br>};</pre><p>The most important line here is withCredentials: true - without this, your browser won&#39;t send the session cookie back to the server!</p><h3>Practical Example: E-commerce Cart</h3><p>Let’s implement a typical e-commerce cart that works for both anonymous and logged-in users.</p><h3>1. Cart Model</h3><pre># models.py<br>from django.db import models<br>from django.contrib.auth.models import User<br><br>class Cart(models.Model):<br>    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)<br>    session_id = models.CharField(max_length=255, null=True, blank=True)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    updated_at = models.DateTimeField(auto_now=True)<br>    is_active = models.BooleanField(default=True)<br>    def __str__(self):<br>        return f&quot;Cart {self.id} - {self.user or self.session_id}&quot;<br>class CartItem(models.Model):<br>    cart = models.ForeignKey(Cart, related_name=&#39;cart_items&#39;, on_delete=models.CASCADE)<br>    product = models.ForeignKey(&#39;Product&#39;, on_delete=models.CASCADE)<br>    quantity = models.PositiveIntegerField(default=1)<br>    price = models.DecimalField(max_digits=10, decimal_places=2)<br>    <br>    def __str__(self):<br>        return f&quot;{self.quantity} x {self.product.name} in Cart {self.cart.id}&quot;</pre><h3>2. Cart View Logic</h3><pre># views.py<br>from rest_framework import viewsets, status<br>from rest_framework.decorators import action<br>from rest_framework.response import Response<br>from .models import Cart, CartItem<br>from .serializers import CartSerializer, CartItemSerializer<br><br>class CartViewSet(viewsets.ModelViewSet):<br>    queryset = Cart.objects.all()<br>    serializer_class = CartSerializer<br>    <br>    def get_or_create_cart(self, request):<br>        &quot;&quot;&quot;Get existing cart or create a new one based on user status&quot;&quot;&quot;<br>        if request.user.is_authenticated:<br>            # Logged in user - get cart by user<br>            cart, created =   Cart.objects.prefetch_related(&#39;cart_items&#39;).get_or_create(<br>                user=request.user,<br>                is_active=True,<br>                defaults={&#39;user&#39;: request.user}<br>            )<br>        else:<br>            # Anonymous user - get cart by session<br>            session_key = request.session.session_key<br>            # If no session exists yet, create one<br>            if not session_key:<br>                request.session.create()<br>                request.session.save()  # Make sure the session is saved<br>                session_key = request.session.session_key<br>            # Get or create cart with this session ID<br>            cart, created = Cart.objects.prefetch_related(&#39;cart_items&#39;).get_or_create(<br>                session_id=session_key,<br>                is_active=True,<br>                defaults={&#39;session_id&#39;: session_key}<br>            )<br>        return cart<br>    @action(detail=False, methods=[&#39;get&#39;])<br>    def current(self, request):<br>        &quot;&quot;&quot;Get the current user&#39;s cart&quot;&quot;&quot;<br>        # Ensure session exists for anonymous users<br>        if not request.user.is_authenticated and not                    request.session.session_key:<br>            request.session.create()<br>            request.session.save()  # Make sure the session is saved<br>            <br>        print(f&quot;Session key: {request.session.session_key}&quot;)<br>        cart = self.get_or_create_cart(request)<br>        serializer = self.get_serializer(cart)<br>        return Response(serializer.data)<br>    <br>    @action(detail=False, methods=[&#39;post&#39;])<br>    def add_item(self, request):<br>        &quot;&quot;&quot;Add item to cart&quot;&quot;&quot;<br>        product_id = request.data.get(&#39;product&#39;)<br>        quantity = int(request.data.get(&#39;quantity&#39;, 1))<br>        <br>        # Get or create cart<br>        cart = self.get_or_create_cart(request)<br>        <br>        # Add logic to add item to cart<br>        # ...<br>        <br>        serializer = self.get_serializer(cart)<br>        return Response(serializer.data)</pre><h3>3. Merging Carts When User Logs In</h3><p>This is where the magic happens! When a user logs in, we want to transfer their anonymous cart to their account:</p><pre># signals.py<br>from django.contrib.auth.signals import user_logged_in<br>from django.dispatch import receiver<br>from .models import Cart, CartItem<br><br>@receiver(user_logged_in)<br>def user_logged_in_handler(sender, request, user, **kwargs):<br>    &quot;&quot;&quot;When user logs in, transfer their anonymous cart&quot;&quot;&quot;<br>    # Only proceed if we have a session key (anonymous cart may exist)<br>    if not request.session.session_key:<br>        return<br>        <br>    session_key = request.session.session_key<br>    <br>    try:<br>        # Find the anonymous cart<br>        anonymous_cart = Cart.objects.get(<br>            session_id=session_key,<br>            user__isnull=True,<br>            is_active=True<br>        )<br>        <br>        # Find or create the user&#39;s cart<br>        user_cart, created = Cart.objects.get_or_create(<br>            user=user,<br>            is_active=True,<br>            defaults={&#39;user&#39;: user}<br>        )<br>        <br>        if anonymous_cart.id != user_cart.id:  # Don&#39;t merge if same cart (shouldn&#39;t happen)<br>            # Get all items from anonymous cart<br>            anonymous_items = CartItem.objects.filter(cart=anonymous_cart)<br>            <br>            # For each anonymous item<br>            for anon_item in anonymous_items:<br>                # Check if this product is already in user&#39;s cart<br>                existing_item = CartItem.objects.filter(<br>                    cart=user_cart,<br>                    product=anon_item.product<br>                ).first()<br>                <br>                if existing_item:<br>                    # Update quantity if product already in user&#39;s cart<br>                    existing_item.quantity += anon_item.quantity<br>                    existing_item.save()<br>                else:<br>                    # Move item to user&#39;s cart<br>                    anon_item.cart = user_cart<br>                    anon_item.save()<br>            <br>            # Deactivate the anonymous cart<br>            anonymous_cart.is_active = False<br>            anonymous_cart.save()<br>            <br>        print(f&quot;Cart merged successfully for user {user.username}&quot;)<br>        <br>    except Cart.DoesNotExist:<br>        # No anonymous cart exists<br>        pass</pre><p>Don’t forget to connect your signals in your app’s __init__.py or apps.py:</p><pre># __init__.py or apps.py<br>default_app_config = &#39;myapp.apps.MyAppConfig&#39;<br><br># apps.py<br>from django.apps import AppConfig<br>class MyAppConfig(AppConfig):<br>    name = &#39;myapp&#39;<br>    <br>    def ready(self):<br>        import myapp.signals  # noqa</pre><h3>Another Example: ToDo App</h3><p>Let’s see how this works with a simpler app like a to-do list:</p><h3>1. Todo Model</h3><pre># models.py<br>from django.db import models<br>from django.contrib.auth.models import User<br><br>class TodoList(models.Model):<br>    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)<br>    session_id = models.CharField(max_length=255, null=True, blank=True)<br>    name = models.CharField(max_length=100, default=&quot;My List&quot;)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    <br>    def __str__(self):<br>        owner = self.user.username if self.user else f&quot;Anonymous ({self.session_id})&quot;<br>        return f&quot;{self.name} - {owner}&quot;<br>class TodoItem(models.Model):<br>    todo_list = models.ForeignKey(TodoList, related_name=&#39;items&#39;, on_delete=models.CASCADE)<br>    title = models.CharField(max_length=200)<br>    completed = models.BooleanField(default=False)<br>    created_at = models.DateTimeField(auto_now_add=True)<br>    <br>    def __str__(self):<br>        return self.title</pre><h3>2. Todo View Logic</h3><pre># views.py<br>from rest_framework import viewsets<br>from rest_framework.decorators import action<br>from rest_framework.response import Response<br>from .models import TodoList, TodoItem<br>from .serializers import TodoListSerializer, TodoItemSerializer<br><br>class TodoListViewSet(viewsets.ModelViewSet):<br>    serializer_class = TodoListSerializer<br>    <br>    def get_queryset(self):<br>        if self.request.user.is_authenticated:<br>            return TodoList.objects.filter(user=self.request.user)<br>        elif self.request.session.session_key:<br>            return TodoList.objects.filter(session_id=self.request.session.session_key)<br>        return TodoList.objects.none()<br>    <br>    def perform_create(self, serializer):<br>        if self.request.user.is_authenticated:<br>            serializer.save(user=self.request.user)<br>        else:<br>            # Ensure session exists<br>            if not self.request.session.session_key:<br>                self.request.session.create()<br>                self.request.session.save()<br>            <br>            serializer.save(session_id=self.request.session.session_key)<br>    <br>    @action(detail=False, methods=[&#39;get&#39;])<br>    def current(self, request):<br>        &quot;&quot;&quot;Get or create the user&#39;s default todo list&quot;&quot;&quot;<br>        if request.user.is_authenticated:<br>            todo_list, created = TodoList.objects.get_or_create(<br>                user=request.user,<br>                defaults={&#39;user&#39;: request.user}<br>            )<br>        else:<br>            # Ensure session exists<br>            if not request.session.session_key:<br>                request.session.create()<br>                request.session.save()<br>            <br>            session_key = request.session.session_key<br>            todo_list, created = TodoList.objects.get_or_create(<br>                session_id=session_key,<br>                defaults={&#39;session_id&#39;: session_key}<br>            )<br>        <br>        serializer = self.get_serializer(todo_list)<br>        return Response(serializer.data)</pre><h3>3. Merging Todo Lists When User Logs In</h3><pre># signals.py<br>from django.contrib.auth.signals import user_logged_in<br>from django.dispatch import receiver<br>from .models import TodoList, TodoItem<br><br>@receiver(user_logged_in)<br>def merge_todo_lists(sender, request, user, **kwargs):<br>    &quot;&quot;&quot;Merge anonymous todo list with user todo list on login&quot;&quot;&quot;<br>    if not request.session.session_key:<br>        return<br>        <br>    session_key = request.session.session_key<br>    <br>    try:<br>        # Find anonymous todo lists<br>        anonymous_lists = TodoList.objects.filter(<br>            session_id=session_key,<br>            user__isnull=True<br>        )<br>        <br>        if not anonymous_lists.exists():<br>            return<br>            <br>        # Find or create user&#39;s default list<br>        user_list, created = TodoList.objects.get_or_create(<br>            user=user,<br>            defaults={&#39;user&#39;: user, &#39;name&#39;: &quot;My List&quot;}<br>        )<br>        <br>        # For each anonymous list<br>        for anon_list in anonymous_lists:<br>            # Move all items to the user&#39;s list<br>            TodoItem.objects.filter(todo_list=anon_list).update(todo_list=user_list)<br>            <br>            # Delete the anonymous list<br>            anon_list.delete()<br>            <br>        print(f&quot;Todo lists merged for user {user.username}&quot;)<br>        <br>    except Exception as e:<br>        print(f&quot;Error merging todo lists: {e}&quot;)</pre><h3>Common Issues and Solutions</h3><h3>1. “Session ID is always None”</h3><p>Make sure you’re:</p><ul><li>Creating the session with request.session.create()</li><li>Saving it with request.session.save()</li><li>Setting withCredentials: true in your frontend API client</li></ul><h3>2. “Session works in development but not production”</h3><p>Check these settings:</p><ul><li>SESSION_COOKIE_SECURE = True requires HTTPS</li><li>SESSION_COOKIE_DOMAIN must match your actual domain</li><li>CORS settings need to match your production URLs</li></ul><h3>3. “Session is lost between requests”</h3><p>Common causes:</p><ul><li>Frontend not sending cookies (withCredentials issue)</li><li>Session middleware not configured correctly</li><li>Session backend (database) issues</li></ul><h3>4. “CORS errors in the console”</h3><p>Make sure:</p><ul><li>corsheaders is installed and configured</li><li>The correct origins are in CORS_ALLOWED_ORIGINS</li><li>CORS_ALLOW_CREDENTIALS = True is set</li></ul><h3>Testing Your Session Implementation</h3><p>Here’s a simple test plan:</p><ol><li>As an anonymous user, add items to cart</li><li>Check browser cookies to verify session ID is set</li><li>Log in with a user account</li><li>Verify the cart items are still present</li><li>Log out and back in with a different account</li><li>Verify no items are in the cart (they should remain with the first account)</li></ol><h3>Final Tips</h3><ol><li><strong>Debug with console logs</strong>: Add logging to both frontend and backend to track session IDs.</li><li><strong>Use Django Debug Toolbar</strong>: It shows session data during development.</li><li><strong>Test cross-browser</strong>: Safari in particular has stricter cookie policies.</li><li><strong>Consider security</strong>: Balance convenience with security appropriate for your application.</li><li><strong>Database impact</strong>: Sessions create database records, so consider cleanup for inactive sessions.</li></ol><h3>Conclusion</h3><p>Properly handling anonymous user sessions is crucial for a seamless user experience. With the right configuration and code structure, you can ensure users never lose their data when transitioning from anonymous to authenticated.</p><p>The key takeaways:</p><ul><li>Configure Django session settings appropriately for your environment</li><li>Always use withCredentials: true in frontend requests</li><li>Use signals to merge anonymous data when users log in</li><li>Test thoroughly across different scenarios.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fb563a28b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>