<?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"><channel><title><![CDATA[Deven's Blog]]></title><description><![CDATA[Passionate software developer driven by a love for technology and a constant desire to explore and learn new skills. Constantly striving to push the limits and ]]></description><link>https://devendraadhikari.com.np</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1770643015794/088c8031-e38e-4fe0-9108-c192922d9a9d.png</url><title>Deven&apos;s Blog</title><link>https://devendraadhikari.com.np</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 18:35:14 GMT</lastBuildDate><atom:link href="https://devendraadhikari.com.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Context Manager Python]]></title><description><![CDATA[A context manager is an object that defines a runtime context and provides methods to establish and clean up the context. It is used with the with statement in Python to manage resources effectively and ensure that necessary cleanup (like closing a f...]]></description><link>https://devendraadhikari.com.np/context-manager-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/context-manager-python</guid><category><![CDATA[Python]]></category><category><![CDATA[context-manager]]></category><category><![CDATA[with-statement]]></category><category><![CDATA[resource management]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sat, 22 Jun 2024 15:16:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1719069444141/7b56cd6d-4dde-4a15-817a-8fd1941ae59b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A context manager is an object that defines a runtime context and provides methods to establish and clean up the context. It is used with the <code>with</code> statement in Python to manage resources effectively and ensure that necessary cleanup (like closing a file or releasing a lock) happens automatically.  </p>
<p><strong>Basic Use of Context Managers</strong></p>
<p>The most common use of a context manager is with the <code>with</code> statement, which simplifies resource management by automatically handling the setup and teardown.</p>
<h4 id="heading-example-file-handling">Example: File Handling</h4>
<pre><code class="lang-yaml"><span class="hljs-string">with</span> <span class="hljs-string">open('example.txt',</span> <span class="hljs-string">'w'</span><span class="hljs-string">)</span> <span class="hljs-attr">as file:</span>
    <span class="hljs-string">file.write('Hello,</span> <span class="hljs-string">World!')</span>
<span class="hljs-comment"># The file is automatically closed here, even if an error occurs</span>
</code></pre>
<p><strong>Creating Custom Context Managers</strong><br />You can create custom context managers using two primary methods:</p>
<ol>
<li><p><strong>Classes</strong> with <code>__enter__</code> and <code>__exit__</code> methods.</p>
</li>
<li><p><strong>Functions</strong> using the <code>contextlib</code> module.</p>
</li>
</ol>
<h4 id="heading-1-context-managers-using-classes">1. Context Managers Using Classes</h4>
<p>To create a context manager using a class, you need to define the <code>__enter__</code> and <code>__exit__</code> methods.</p>
<ul>
<li><p><code>__enter__(self)</code>: This method is executed when the <code>with</code> block is entered. It returns the resource to be managed.</p>
</li>
<li><p><code>__exit__(self, exc_type, exc_val, exc_tb)</code>: This method is executed when the <code>with</code> block is exited. It handles any cleanup and can process exceptions.</p>
</li>
</ul>
<h5 id="heading-example">Example:</h5>
<pre><code class="lang-yaml"><span class="hljs-attr">class ManagedResource:</span>
    <span class="hljs-string">def</span> <span class="hljs-string">__init__(self,</span> <span class="hljs-string">name):</span>
        <span class="hljs-string">self.name</span> <span class="hljs-string">=</span> <span class="hljs-string">name</span>

    <span class="hljs-string">def</span> <span class="hljs-string">__enter__(self):</span>
        <span class="hljs-string">print(f"Acquiring</span> <span class="hljs-attr">resource:</span> {<span class="hljs-string">self.name</span>}<span class="hljs-string">")
        return self  # This value will be bound to the target specified in the with statement

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(f"</span><span class="hljs-attr">Releasing resource:</span> {<span class="hljs-string">self.name</span>}<span class="hljs-string">")
        # Handle exceptions if necessary
        if exc_type:
            print(f"</span><span class="hljs-attr">An error occurred:</span> {<span class="hljs-string">exc_val</span>}<span class="hljs-string">")
        return False  # Do not suppress exceptions

# Usage
with ManagedResource('Database Connection') as resource:
    print(f"</span><span class="hljs-attr">Using resource:</span> {<span class="hljs-string">resource.name</span>}<span class="hljs-string">")</span>
</code></pre>
<p>Output:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Acquiring resource:</span> <span class="hljs-string">Database</span> <span class="hljs-string">Connection</span>
<span class="hljs-attr">Using resource:</span> <span class="hljs-string">Database</span> <span class="hljs-string">Connection</span>
<span class="hljs-attr">Releasing resource:</span> <span class="hljs-string">Database</span> <span class="hljs-string">Connection</span>
</code></pre>
<ul>
<li><strong>Explanation</strong>: The <code>__enter__</code> method acquires the resource, and the <code>__exit__</code> method releases it. The <code>with</code> block ensures these methods are called automatically.</li>
</ul>
<h4 id="heading-2-context-managers-using-the-contextlib-module">2. Context Managers Using the <code>contextlib</code> Module</h4>
<p>The <code>contextlib</code> module provides utilities for creating context managers, including the <code>contextmanager</code> decorator, which allows you to write context managers as generator functions.</p>
<h5 id="heading-example-1">Example:</h5>
<pre><code class="lang-yaml"><span class="hljs-string">from</span> <span class="hljs-string">contextlib</span> <span class="hljs-string">import</span> <span class="hljs-string">contextmanager</span>

<span class="hljs-string">@contextmanager</span>
<span class="hljs-string">def</span> <span class="hljs-string">managed_resource(name):</span>
    <span class="hljs-string">print(f"Acquiring</span> <span class="hljs-attr">resource:</span> {<span class="hljs-string">name</span>}<span class="hljs-string">")
    yield name  # The value to bind to the target specified in the with statement
    print(f"</span><span class="hljs-attr">Releasing resource:</span> {<span class="hljs-string">name</span>}<span class="hljs-string">")

# Usage
with managed_resource('File Handler') as resource:
    print(f"</span><span class="hljs-attr">Using resource:</span> {<span class="hljs-string">resource</span>}<span class="hljs-string">")</span>
</code></pre>
<p>Output:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Acquiring resource:</span> <span class="hljs-string">File</span> <span class="hljs-string">Handler</span>
<span class="hljs-attr">Using resource:</span> <span class="hljs-string">File</span> <span class="hljs-string">Handler</span>
<span class="hljs-attr">Releasing resource:</span> <span class="hljs-string">File</span> <span class="hljs-string">Handler</span>
</code></pre>
<ul>
<li><strong>Explanation</strong>: The <code>yield</code> statement in the generator function marks the point where the <code>with</code> block starts. The code before <code>yield</code> runs when entering the <code>with</code> block, and the code after <code>yield</code> runs upon exiting.</li>
</ul>
<h3 id="heading-advanced-use-cases">Advanced Use Cases</h3>
<p>Context managers are not limited to simple file handling or resource management. They can be used in various complex scenarios:</p>
<h4 id="heading-1-managing-database-connections">1. Managing Database Connections</h4>
<pre><code class="lang-yaml"><span class="hljs-attr">class DatabaseConnection:</span>
    <span class="hljs-string">def</span> <span class="hljs-string">__init__(self,</span> <span class="hljs-string">db_url):</span>
        <span class="hljs-string">self.db_url</span> <span class="hljs-string">=</span> <span class="hljs-string">db_url</span>

    <span class="hljs-string">def</span> <span class="hljs-string">__enter__(self):</span>
        <span class="hljs-string">self.connection</span> <span class="hljs-string">=</span> <span class="hljs-string">self.connect_to_database()</span>
        <span class="hljs-string">return</span> <span class="hljs-string">self.connection</span>

    <span class="hljs-string">def</span> <span class="hljs-string">__exit__(self,</span> <span class="hljs-string">exc_type,</span> <span class="hljs-string">exc_val,</span> <span class="hljs-string">exc_tb):</span>
        <span class="hljs-string">self.close_database_connection(self.connection)</span>
        <span class="hljs-attr">if exc_type:</span>
            <span class="hljs-string">print(f"An</span> <span class="hljs-attr">error occurred:</span> {<span class="hljs-string">exc_val</span>}<span class="hljs-string">")

    def connect_to_database(self):
        print(f"</span><span class="hljs-string">Connecting</span> <span class="hljs-string">to</span> <span class="hljs-string">database</span> <span class="hljs-string">at</span> {<span class="hljs-string">self.db_url</span>}<span class="hljs-string">")
        return "</span><span class="hljs-string">db_connection"</span>  <span class="hljs-comment"># Simulating a database connection</span>

    <span class="hljs-string">def</span> <span class="hljs-string">close_database_connection(self,</span> <span class="hljs-string">connection):</span>
        <span class="hljs-string">print(f"Closing</span> <span class="hljs-attr">database connection:</span> {<span class="hljs-string">connection</span>}<span class="hljs-string">")

# Usage
with DatabaseConnection('sqlite:///:memory:') as db_conn:
    print(f"</span><span class="hljs-attr">Using database connection:</span> {<span class="hljs-string">db_conn</span>}<span class="hljs-string">")</span>
</code></pre>
<p>Output:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Connecting to database at sqlite:///:memory:</span>
<span class="hljs-attr">Using database connection:</span> <span class="hljs-string">db_connection</span>
<span class="hljs-attr">Closing database connection:</span> <span class="hljs-string">db_connection</span>
</code></pre>
<h4 id="heading-2-temporary-file-handling">2. Temporary File Handling</h4>
<pre><code class="lang-yaml"><span class="hljs-string">import</span> <span class="hljs-string">tempfile</span>
<span class="hljs-string">import</span> <span class="hljs-string">os</span>

<span class="hljs-string">@contextmanager</span>
<span class="hljs-string">def</span> <span class="hljs-string">temporary_file():</span>
    <span class="hljs-string">fd,</span> <span class="hljs-string">path</span> <span class="hljs-string">=</span> <span class="hljs-string">tempfile.mkstemp()</span>  <span class="hljs-comment"># Create a temporary file</span>
    <span class="hljs-attr">try:</span>
        <span class="hljs-string">yield</span> <span class="hljs-string">path</span>  <span class="hljs-comment"># Provide the file path to the with block</span>
    <span class="hljs-attr">finally:</span>
        <span class="hljs-string">os.close(fd)</span>  <span class="hljs-comment"># Close the file descriptor</span>
        <span class="hljs-string">os.remove(path)</span>  <span class="hljs-comment"># Remove the file</span>

<span class="hljs-comment"># Usage</span>
<span class="hljs-string">with</span> <span class="hljs-string">temporary_file()</span> <span class="hljs-attr">as temp_path:</span>
    <span class="hljs-string">print(f"Using</span> <span class="hljs-attr">temporary file at:</span> {<span class="hljs-string">temp_path</span>}<span class="hljs-string">")
    with open(temp_path, 'w') as file:
        file.write('Temporary data')

    # The temporary file is automatically removed after the with block</span>
</code></pre>
<p>Output:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Using temporary file at:</span> <span class="hljs-string">/tmp/tmpabcd1234</span>
</code></pre>
<h4 id="heading-3-timing-code-execution">3. Timing Code Execution</h4>
<pre><code class="lang-yaml"><span class="hljs-string">import</span> <span class="hljs-string">time</span>

<span class="hljs-string">@contextmanager</span>
<span class="hljs-string">def</span> <span class="hljs-string">timer():</span>
    <span class="hljs-string">start_time</span> <span class="hljs-string">=</span> <span class="hljs-string">time.time()</span>
    <span class="hljs-string">yield</span>
    <span class="hljs-string">end_time</span> <span class="hljs-string">=</span> <span class="hljs-string">time.time()</span>
    <span class="hljs-string">print(f"Elapsed</span> <span class="hljs-attr">time:</span> {<span class="hljs-string">end_time</span> <span class="hljs-bullet">-</span> <span class="hljs-string">start_time</span>} <span class="hljs-string">seconds")</span>

<span class="hljs-comment"># Usage</span>
<span class="hljs-string">with</span> <span class="hljs-string">timer():</span>
    <span class="hljs-comment"># Simulate a time-consuming task</span>
    <span class="hljs-string">time.sleep(2)</span>
</code></pre>
<p>Output:</p>
<pre><code class="lang-yaml"><span class="hljs-attr">Elapsed time:</span> <span class="hljs-number">2.0001</span> <span class="hljs-string">seconds</span>
</code></pre>
<h3 id="heading-best-practices-and-tips">Best Practices and Tips</h3>
<ol>
<li><p><strong>Resource Management</strong>: Use context managers to handle resources like files, network connections, or locks. This ensures that resources are released properly even if an error occurs.</p>
</li>
<li><p><strong>Exception Handling</strong>: The <code>__exit__</code> method can handle exceptions that occur within the <code>with</code> block. Returning <code>True</code> from <code>__exit__</code> suppresses the exception; otherwise, it propagates.</p>
</li>
<li><p><strong>Reusability</strong>: Design your context managers to be reusable and modular. This makes your code cleaner and easier to maintain.</p>
</li>
<li><p><strong>Avoid Complexity</strong>: If a context manager becomes too complex, consider breaking it into simpler components or using multiple context managers nested or combined using <code>contextlib.ExitStack</code>.</p>
</li>
<li><p><strong>Nesting Context Managers</strong>: Python 3.1 introduced the ability to use multiple context managers in a single <code>with</code> statement, which can be more concise and readable.</p>
<pre><code class="lang-yaml"> <span class="hljs-string">with</span> <span class="hljs-string">open('file1.txt',</span> <span class="hljs-string">'r'</span><span class="hljs-string">)</span> <span class="hljs-string">as</span> <span class="hljs-string">f1,</span> <span class="hljs-string">open('file2.txt',</span> <span class="hljs-string">'w'</span><span class="hljs-string">)</span> <span class="hljs-attr">as f2:</span>
     <span class="hljs-string">f2.write(f1.read())</span>
</code></pre>
</li>
<li><p><strong>Debugging</strong>: Use <code>print</code> statements or logging inside <code>__enter__</code> and <code>__exit__</code> methods to help debug and understand the flow of your context managers.</p>
</li>
</ol>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Context managers are a powerful feature of Python that provide a robust and clean way to manage resources. By mastering context managers, you can write more reliable and maintainable code. Whether you're handling files, managing connections, or timing code execution, understanding and using context managers will make your Python code more professional and resilient.</p>
]]></content:encoded></item><item><title><![CDATA[Optimization in Django]]></title><description><![CDATA[Optimizing a Django application is crucial for ensuring that it runs efficiently, especially under heavy load or with large datasets. There are various aspects of a Django application you can optimize, including database interactions, middleware, sta...]]></description><link>https://devendraadhikari.com.np/optimization-in-django</link><guid isPermaLink="true">https://devendraadhikari.com.np/optimization-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[optimization]]></category><category><![CDATA[Python]]></category><category><![CDATA[django orm]]></category><category><![CDATA[DjangoRestFramework]]></category><category><![CDATA[django master]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sun, 09 Jun 2024 10:34:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717929195110/e1288732-66e0-43af-bde3-5a46d50bde8a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Optimizing a Django application is crucial for ensuring that it runs efficiently, especially under heavy load or with large datasets. There are various aspects of a Django application you can optimize, including database interactions, middleware, static files, and overall code efficiency. Below are detailed strategies and practices to help you optimize your Django application:</p>
<h3 id="heading-1-database-optimization">1. Database Optimization</h3>
<h4 id="heading-a-efficient-queries">a. Efficient Queries</h4>
<ul>
<li><p><strong>Use Select Related and Prefetch Related</strong>:</p>
<ul>
<li><p><code>select_related</code>: Reduces the number of database queries by performing a SQL join and including the fields of the related object.</p>
</li>
<li><p><code>prefetch_related</code>: Performs a separate lookup for each relationship and performs the join in Python.</p>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Using select_related for foreign key relationships</span>
    books = Book.objects.select_related(<span class="hljs-string">'author'</span>).all()

    <span class="hljs-comment"># Using prefetch_related for many-to-many relationships</span>
    books = Book.objects.prefetch_related(<span class="hljs-string">'categories'</span>).all()
</code></pre>
<ul>
<li><p><strong>Avoid N+1 Query Problems</strong>:</p>
<ul>
<li>Ensure you're not performing queries inside a loop that could be done with a single query.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Inefficient way</span>
    <span class="hljs-keyword">for</span> book <span class="hljs-keyword">in</span> Book.objects.all():
        print(book.author.name)  <span class="hljs-comment"># This performs a separate query for each book</span>

    <span class="hljs-comment"># Efficient way</span>
    books = Book.objects.select_related(<span class="hljs-string">'author'</span>).all()
    <span class="hljs-keyword">for</span> book <span class="hljs-keyword">in</span> books:
        print(book.author.name)  <span class="hljs-comment"># Single query with join</span>
</code></pre>
<ul>
<li><p><strong>Use</strong> <code>.only()</code> and <code>.defer()</code>:</p>
<ul>
<li>Load only the fields you need to save memory and speed up queries.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Load only specific fields</span>
    books = Book.objects.only(<span class="hljs-string">'title'</span>, <span class="hljs-string">'published_date'</span>).all()

    <span class="hljs-comment"># Load all fields except specified ones</span>
    books = Book.objects.defer(<span class="hljs-string">'content'</span>).all()
</code></pre>
<ul>
<li><p><strong>Database Indexing</strong>:</p>
<ul>
<li>Use database indexes on columns that are frequently searched or used in filters.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Book</span>(<span class="hljs-params">models.Model</span>):</span>
        title = models.CharField(max_length=<span class="hljs-number">255</span>, db_index=<span class="hljs-literal">True</span>)
        <span class="hljs-comment"># or add index in the migration</span>
        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
            indexes = [
                models.Index(fields=[<span class="hljs-string">'title'</span>]),
            ]
</code></pre>
<h4 id="heading-b-query-aggregation">b. Query Aggregation</h4>
<ul>
<li><p>Use Django’s aggregation functions to perform operations like <code>SUM</code>, <code>AVG</code>, <code>COUNT</code>, directly in the database.</p>
<pre><code class="lang-python">  <span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> Sum

  total_pages = Book.objects.aggregate(Sum(<span class="hljs-string">'pages'</span>))
</code></pre>
</li>
</ul>
<h3 id="heading-2-caching">2. Caching</h3>
<ul>
<li><p><strong>Database Query Caching</strong>:</p>
<ul>
<li>Use Django’s caching framework to cache results of expensive queries.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.core.cache <span class="hljs-keyword">import</span> cache

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_books</span>():</span>
        books = cache.get(<span class="hljs-string">'all_books'</span>)
        <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> books:
            books = Book.objects.all()
            cache.set(<span class="hljs-string">'all_books'</span>, books, <span class="hljs-number">300</span>)  <span class="hljs-comment"># Cache for 5 minutes</span>
        <span class="hljs-keyword">return</span> books
</code></pre>
<ul>
<li><p><strong>View Caching</strong>:</p>
<ul>
<li>Use <code>cache_page</code> decorator to cache entire views.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.views.decorators.cache <span class="hljs-keyword">import</span> cache_page

<span class="hljs-meta">    @cache_page(60 * 15)  # Cache for 15 minutes</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_view</span>(<span class="hljs-params">request</span>):</span>
        ...
</code></pre>
<ul>
<li><p><strong>Template Fragment Caching</strong>:</p>
<ul>
<li>Cache parts of your templates that don't change often.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    {% load cache %}
    {% cache <span class="hljs-number">600</span> sidebar %}
        ... sidebar content ...
    {% endcache %}
</code></pre>
<h3 id="heading-3-middleware-optimization">3. Middleware Optimization</h3>
<ul>
<li><p><strong>Reduce Middleware</strong>:</p>
<ul>
<li>Only use the middleware that is absolutely necessary to minimize processing time for each request.</li>
</ul>
</li>
<li><p><strong>Custom Middleware</strong>:</p>
<ul>
<li>Implement your own lightweight middleware if you need specific functionality.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CustomHeaderMiddleware</span>:</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, get_response</span>):</span>
            self.get_response = get_response

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, request</span>):</span>
            response = self.get_response(request)
            response[<span class="hljs-string">'X-Custom-Header'</span>] = <span class="hljs-string">'Value'</span>
            <span class="hljs-keyword">return</span> response
</code></pre>
<h3 id="heading-4-static-files-and-media">4. Static Files and Media</h3>
<ul>
<li><p><strong>Use a CDN</strong>:</p>
<ul>
<li>Serve static and media files through a CDN to offload traffic and reduce latency.</li>
</ul>
</li>
<li><p><strong>Static File Compression</strong>:</p>
<ul>
<li>Use tools like <code>whitenoise</code> or Django’s <code>ManifestStaticFilesStorage</code> to compress static files.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># settings.py</span>
    STATICFILES_STORAGE = <span class="hljs-string">'whitenoise.storage.CompressedManifestStaticFilesStorage'</span>
</code></pre>
<ul>
<li><p><strong>Optimize Images</strong>:</p>
<ul>
<li>Use optimized image formats and tools to compress images without losing quality.</li>
</ul>
</li>
</ul>
<h3 id="heading-5-code-optimization">5. Code Optimization</h3>
<ul>
<li><p><strong>Use Django's Built-in Functions and Utilities</strong>:</p>
<ul>
<li>Django provides a lot of utilities that are optimized and battle-tested. Avoid reinventing the wheel.</li>
</ul>
</li>
<li><p><strong>Optimize Algorithm and Data Structures</strong>:</p>
<ul>
<li>Review and optimize your algorithms and data structures to ensure they are efficient.</li>
</ul>
</li>
<li><p><strong>Reduce Complexity</strong>:</p>
<ul>
<li>Simplify complex code structures to make them easier to understand and maintain.</li>
</ul>
</li>
<li><p><strong>Lazy Loading</strong>:</p>
<ul>
<li>Use Django’s lazy loading to defer database accesses until necessary.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.utils.functional <span class="hljs-keyword">import</span> lazy

    lazy_function = lazy(your_function, str)
</code></pre>
<ul>
<li><p><strong>Avoid Unnecessary Object Creation</strong>:</p>
<ul>
<li>Be mindful of creating unnecessary objects or data structures that can be avoided.</li>
</ul>
</li>
</ul>
<h3 id="heading-6-django-settings-optimization">6. Django Settings Optimization</h3>
<ul>
<li><p><strong>Debug Mode</strong>:</p>
<ul>
<li>Always turn off <code>DEBUG</code> mode in production to improve performance and security.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    DEBUG = <span class="hljs-literal">False</span>
</code></pre>
<ul>
<li><p><strong>Database Connection Pooling</strong>:</p>
<ul>
<li>Use connection pooling for better database performance.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># settings.py example using django-db-geventpool</span>
    DATABASES = {
        <span class="hljs-string">'default'</span>: {
            <span class="hljs-string">'ENGINE'</span>: <span class="hljs-string">'django.db.backends.postgresql'</span>,
            <span class="hljs-string">'NAME'</span>: <span class="hljs-string">'yourdbname'</span>,
            <span class="hljs-string">'USER'</span>: <span class="hljs-string">'yourdbuser'</span>,
            <span class="hljs-string">'PASSWORD'</span>: <span class="hljs-string">'yourdbpassword'</span>,
            <span class="hljs-string">'HOST'</span>: <span class="hljs-string">'localhost'</span>,
            <span class="hljs-string">'PORT'</span>: <span class="hljs-string">'5432'</span>,
            <span class="hljs-string">'OPTIONS'</span>: {
                <span class="hljs-string">'MAX_CONNS'</span>: <span class="hljs-number">20</span>,
            }
        }
    }
</code></pre>
<ul>
<li><p><strong>Gzip Compression</strong>:</p>
<ul>
<li>Enable Gzip middleware to compress responses and reduce bandwidth.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    MIDDLEWARE = [
        <span class="hljs-string">'django.middleware.security.SecurityMiddleware'</span>,
        <span class="hljs-string">'django.middleware.gzip.GZipMiddleware'</span>,
        ...
    ]
</code></pre>
<h3 id="heading-7-asynchronous-processing">7. Asynchronous Processing</h3>
<ul>
<li><p><strong>Use Celery for Background Tasks</strong>:</p>
<ul>
<li>Offload long-running or resource-intensive tasks to Celery to keep your web requests fast.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> shared_task

<span class="hljs-meta">    @shared_task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">long_running_task</span>(<span class="hljs-params">arg1, arg2</span>):</span>
        <span class="hljs-comment"># perform the task</span>
</code></pre>
<ul>
<li><p><strong>Async Views</strong>:</p>
<ul>
<li>Use Django’s support for async views to handle I/O-bound operations more efficiently.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_async_view</span>(<span class="hljs-params">request</span>):</span>
        <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">1</span>)  <span class="hljs-comment"># Simulating an async operation</span>
        <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'status'</span>: <span class="hljs-string">'done'</span>})
</code></pre>
<h3 id="heading-8-profiling-and-monitoring">8. Profiling and Monitoring</h3>
<ul>
<li><p><strong>Use Profiling Tools</strong>:↳</p>
<ul>
<li>Tools like <code>django-debug-toolbar</code> for development or <code>cProfile</code> for more detailed profiling can help identify bottlenecks.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Install django-debug-toolbar</span>
    pip install django-debug-toolbar

    <span class="hljs-comment"># settings.py</span>
    INSTALLED_APPS = [
        ...
        <span class="hljs-string">'debug_toolbar'</span>,
    ]

    MIDDLEWARE = [
        ...
        <span class="hljs-string">'debug_toolbar.middleware.DebugToolbarMiddleware'</span>,
    ]

    INTERNAL_IPS = [<span class="hljs-string">'127.0.0.1'</span>]
</code></pre>
<ul>
<li><p><strong>Monitoring</strong>:</p>
<ul>
<li>Implement monitoring solutions (like New Relic, Datadog, or Sentry) to track performance and identify issues in production.</li>
</ul>
</li>
</ul>
<h3 id="heading-9-security-optimizations">9. Security Optimizations</h3>
<ul>
<li><p><strong>Secure Settings</strong>:</p>
<ul>
<li>Ensure settings like <code>SECURE_SSL_REDIRECT</code>, <code>SECURE_HSTS_SECONDS</code>, and <code>SESSION_COOKIE_SECURE</code> are enabled in production for better security which also affects performance by reducing attack vectors.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    SECURE_SSL_REDIRECT = <span class="hljs-literal">True</span>
    SECURE_HSTS_SECONDS = <span class="hljs-number">31536000</span>
    SESSION_COOKIE_SECURE = <span class="hljs-literal">True</span>
</code></pre>
<h3 id="heading-10-server-and-deployment-optimization">10. Server and Deployment Optimization</h3>
<ul>
<li><p><strong>Use Gunicorn/UWSGI</strong>:</p>
<ul>
<li>Use a robust application server like Gunicorn or uWSGI for serving your Django app in production.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    gunicorn myproject.wsgi:application --workers <span class="hljs-number">3</span>
</code></pre>
<ul>
<li><p><strong>Load Balancing</strong>:</p>
<ul>
<li>Implement load balancing to distribute traffic evenly across multiple servers or instances.</li>
</ul>
</li>
<li><p><strong>Optimize Database</strong>:</p>
<ul>
<li><p>Regularly analyze and optimize your database queries and indexes.</p>
</li>
<li><p>Use tools like <code>pg_stat_statements</code> for PostgreSQL to monitor query performance.</p>
</li>
</ul>
</li>
</ul>
<h3 id="heading-11-advanced-database-optimization">11. Advanced Database Optimization</h3>
<h4 id="heading-a-optimizing-database-schema">a. Optimizing Database Schema</h4>
<ul>
<li><p><strong>Normalization and Denormalization</strong>:</p>
<ul>
<li><p><strong>Normalization</strong> helps reduce data redundancy and improves data integrity by organizing tables and relationships.</p>
</li>
<li><p><strong>Denormalization</strong> can improve read performance by reducing the need for joins, especially for read-heavy workloads.</p>
</li>
</ul>
</li>
<li><p><strong>Partitioning</strong>:</p>
<ul>
<li>Partition large tables to improve query performance and manageability. This is useful for tables with a large number of rows.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    CREATE TABLE my_partitioned_table (
        id SERIAL PRIMARY KEY,
        data TEXT,
        created_at TIMESTAMP
    ) PARTITION BY RANGE (created_at);

    CREATE TABLE my_partitioned_table_2024_01 PARTITION OF my_partitioned_table
    FOR VALUES FROM (<span class="hljs-string">'2024-01-01'</span>) TO (<span class="hljs-string">'2024-02-01'</span>);
</code></pre>
<ul>
<li><p><strong>Indexing Strategies</strong>:</p>
<ul>
<li><p>Use <strong>multi-column indexes</strong> for queries that filter on multiple columns.</p>
</li>
<li><p>Use <strong>partial indexes</strong> for filtering rows based on specific conditions.</p>
</li>
<li><p>Consider <strong>full-text search indexes</strong> for text search fields.</p>
</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Django example of multi-column index</span>
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyModel</span>(<span class="hljs-params">models.Model</span>):</span>
        field1 = models.CharField(max_length=<span class="hljs-number">100</span>)
        field2 = models.CharField(max_length=<span class="hljs-number">100</span>)

        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
            indexes = [
                models.Index(fields=[<span class="hljs-string">'field1'</span>, <span class="hljs-string">'field2'</span>]),
            ]
</code></pre>
<h4 id="heading-b-query-optimization-techniques">b. Query Optimization Techniques</h4>
<ul>
<li><p><strong>Use Raw SQL for Complex Queries</strong>:</p>
<ul>
<li>Sometimes, Django ORM can’t express complex queries efficiently. Use raw SQL queries where necessary.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> connection

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_custom_results</span>():</span>
        <span class="hljs-keyword">with</span> connection.cursor() <span class="hljs-keyword">as</span> cursor:
            cursor.execute(<span class="hljs-string">"SELECT * FROM my_table WHERE some_complex_condition"</span>)
            rows = cursor.fetchall()
        <span class="hljs-keyword">return</span> rows
</code></pre>
<ul>
<li><p><strong>Analyze Query Plans</strong>:</p>
<ul>
<li>Use database-specific tools to analyze and optimize query execution plans (e.g., <code>EXPLAIN</code> in PostgreSQL).</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    EXPLAIN ANALYZE SELECT * FROM my_table WHERE condition = <span class="hljs-string">'value'</span>;
</code></pre>
<h3 id="heading-12-django-settings-optimization">12. Django Settings Optimization</h3>
<h4 id="heading-a-middleware-configuration">a. Middleware Configuration</h4>
<ul>
<li><p><strong>Middleware Ordering</strong>:</p>
<ul>
<li>The order of middleware affects performance. Place lighter middleware that can terminate early higher in the list.</li>
</ul>
</li>
<li><p><strong>Custom Middleware for Performance</strong>:</p>
<ul>
<li>Implement custom middleware to handle specific performance-related tasks, like logging or early termination of requests.</li>
</ul>
</li>
</ul>
<h4 id="heading-b-efficient-static-and-media-file-handling">b. Efficient Static and Media File Handling</h4>
<ul>
<li><p><strong>Use Django’s Built-in Storage Backends</strong>:</p>
<ul>
<li>Use <code>django-storages</code> to efficiently handle static and media files with cloud storage solutions like AWS S3 or Google Cloud Storage.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># settings.py</span>
    DEFAULT_FILE_STORAGE = <span class="hljs-string">'storages.backends.s3boto3.S3Boto3Storage'</span>
    STATICFILES_STORAGE = <span class="hljs-string">'storages.backends.s3boto3.S3Boto3Storage'</span>
</code></pre>
<ul>
<li><p><strong>Asset Compression and Minification</strong>:</p>
<ul>
<li>Use tools like <code>django-compressor</code> to compress and minify CSS and JavaScript files.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># settings.py</span>
    COMPRESS_ENABLED = <span class="hljs-literal">True</span>
    COMPRESS_URL = STATIC_URL
    COMPRESS_ROOT = STATIC_ROOT
</code></pre>
<h3 id="heading-13-server-and-deployment-optimization">13. Server and Deployment Optimization</h3>
<h4 id="heading-a-application-server-tuning">a. Application Server Tuning</h4>
<ul>
<li><p><strong>Gunicorn Configuration</strong>:</p>
<ul>
<li>Configure Gunicorn with appropriate worker types (sync vs. async) and numbers based on your application needs.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    gunicorn myproject.wsgi:application --workers <span class="hljs-number">3</span> --worker-<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">gevent</span> --<span class="hljs-title">timeout</span> 120</span>
</code></pre>
<ul>
<li><p><strong>uWSGI Optimization</strong>:</p>
<ul>
<li>Tune uWSGI settings for maximum performance, such as process management, caching, and threading.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    [uwsgi]
    module = myproject.wsgi:application
    master = true
    processes = <span class="hljs-number">4</span>
    threads = <span class="hljs-number">2</span>
    harakiri = <span class="hljs-number">60</span>
</code></pre>
<h4 id="heading-b-load-balancing-and-scaling">b. Load Balancing and Scaling</h4>
<ul>
<li><p><strong>Horizontal Scaling</strong>:</p>
<ul>
<li><p>Scale horizontally by deploying multiple instances of your application behind a load balancer.</p>
</li>
<li><p>Use Docker and Kubernetes for container orchestration and scaling.</p>
</li>
</ul>
</li>
<li><p><strong>Auto-Scaling</strong>:</p>
<ul>
<li>Implement auto-scaling based on metrics like CPU usage or request rate to handle varying loads dynamically.</li>
</ul>
</li>
<li><p><strong>Database Sharding</strong>:</p>
<ul>
<li>Consider database sharding for very large datasets to distribute data across multiple databases and improve performance.</li>
</ul>
</li>
</ul>
<h3 id="heading-14-security-enhancements">14. Security Enhancements</h3>
<h4 id="heading-a-secure-application-settings">a. Secure Application Settings</h4>
<ul>
<li><p><strong>Secure Password Storage</strong>:</p>
<ul>
<li>Use strong hashing algorithms for storing passwords (Django uses PBKDF2 by default, which is secure).</li>
</ul>
</li>
<li><p><strong>Use HTTPS Everywhere</strong>:</p>
<ul>
<li>Ensure that your application is served over HTTPS to encrypt data in transit.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># settings.py</span>
    SECURE_SSL_REDIRECT = <span class="hljs-literal">True</span>
    SECURE_HSTS_SECONDS = <span class="hljs-number">31536000</span>
</code></pre>
<h4 id="heading-b-preventing-common-attacks">b. Preventing Common Attacks</h4>
<ul>
<li><p><strong>SQL Injection Prevention</strong>:</p>
<ul>
<li>Always use Django ORM to interact with the database instead of raw SQL to avoid SQL injection vulnerabilities.</li>
</ul>
</li>
<li><p><strong>Cross-Site Scripting (XSS) Protection</strong>:</p>
<ul>
<li>Use Django’s built-in template system that auto-escapes data, or manually escape user-generated content.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    {{ user_input|escape }}
</code></pre>
<ul>
<li><p><strong>Cross-Site Request Forgery (CSRF) Protection</strong>:</p>
<ul>
<li>Ensure CSRF protection is enabled for all forms and API requests.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    &lt;form method=<span class="hljs-string">"post"</span>&gt;
        {% csrf_token %}
        ...
    &lt;/form&gt;
</code></pre>
<h3 id="heading-15-performance-monitoring-and-profiling">15. Performance Monitoring and Profiling</h3>
<h4 id="heading-a-application-performance-monitoring-apm">a. Application Performance Monitoring (APM)</h4>
<ul>
<li><p><strong>Implement APM Tools</strong>:</p>
<ul>
<li>Use tools like New Relic, Datadog, or AppDynamics to monitor your application’s performance in real-time.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Example: Integrating New Relic</span>
    <span class="hljs-keyword">import</span> newrelic.agent
    newrelic.agent.initialize(<span class="hljs-string">'/path/to/newrelic.ini'</span>)

    application = get_wsgi_application()
</code></pre>
<h4 id="heading-b-advanced-profiling">b. Advanced Profiling</h4>
<ul>
<li><p><strong>Use Profiling Tools</strong>:</p>
<ul>
<li>Tools like <code>cProfile</code>, <code>line_profiler</code>, or <code>django-silk</code> can help identify performance bottlenecks at a fine-grained level.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">import</span> cProfile
    cProfile.run(<span class="hljs-string">'my_function()'</span>)
</code></pre>
<ul>
<li><p><strong>Analyze Memory Usage</strong>:</p>
<ul>
<li>Use tools like <code>memory_profiler</code> to analyze and optimize memory usage.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> memory_profiler <span class="hljs-keyword">import</span> profile

<span class="hljs-meta">    @profile</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_function</span>():</span>
        ...
</code></pre>
<h3 id="heading-16-optimizing-djangos-orm-and-model-usage">16. Optimizing Django's ORM and Model Usage</h3>
<h4 id="heading-a-efficient-model-design">a. Efficient Model Design</h4>
<ul>
<li><p><strong>Use Appropriate Field Types</strong>:</p>
<ul>
<li>Choose the right field types based on data and query requirements to optimize storage and access patterns.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Product</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">255</span>)
        price = models.DecimalField(max_digits=<span class="hljs-number">10</span>, decimal_places=<span class="hljs-number">2</span>)
</code></pre>
<ul>
<li><p><strong>Optimize Model Inheritance</strong>:</p>
<ul>
<li>Use multi-table inheritance or abstract base classes wisely to balance performance and data design.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CommonInfo</span>(<span class="hljs-params">models.Model</span>):</span>
        name = models.CharField(max_length=<span class="hljs-number">100</span>)
        age = models.PositiveIntegerField()

        <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
            abstract = <span class="hljs-literal">True</span>

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Student</span>(<span class="hljs-params">CommonInfo</span>):</span>
        home_group = models.CharField(max_length=<span class="hljs-number">5</span>)
</code></pre>
<h4 id="heading-b-queryset-optimization">b. QuerySet Optimization</h4>
<ul>
<li><p><strong>Bulk Operations</strong>:</p>
<ul>
<li>Use bulk operations (<code>bulk_create</code>, <code>bulk_update</code>) for inserting or updating large datasets efficiently.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># Bulk create example</span>
    Book.objects.bulk_create([
        Book(title=<span class="hljs-string">'Book 1'</span>, author=author),
        Book(title=<span class="hljs-string">'Book 2'</span>, author=author),
    ])
</code></pre>
<ul>
<li><p><strong>Avoiding Lazy Evaluation</strong>:</p>
<ul>
<li>Be mindful of when QuerySets are evaluated to avoid unnecessary database hits. Use list() to force evaluation.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    books = list(Book.objects.filter(author=<span class="hljs-string">'Author Name'</span>))
</code></pre>
<h3 id="heading-17-utilizing-asynchronous-capabilities">17. Utilizing Asynchronous Capabilities</h3>
<h4 id="heading-a-django-channels">a. Django Channels</h4>
<ul>
<li><p><strong>WebSockets and Background Tasks</strong>:</p>
<ul>
<li>Use Django Channels to handle WebSockets, background tasks, or long-running processes asynchronously.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-comment"># consumers.py</span>
    <span class="hljs-keyword">from</span> channels.generic.websocket <span class="hljs-keyword">import</span> WebsocketConsumer

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ChatConsumer</span>(<span class="hljs-params">WebsocketConsumer</span>):</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect</span>(<span class="hljs-params">self</span>):</span>
            self.accept()

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">disconnect</span>(<span class="hljs-params">self, close_code</span>):</span>
            <span class="hljs-keyword">pass</span>

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">receive</span>(<span class="hljs-params">self, text_data</span>):</span>
            self.send(text_data=<span class="hljs-string">"Echo: "</span> + text_data)
</code></pre>
<h4 id="heading-b-async-views-and-tasks">b. Async Views and Tasks</h4>
<ul>
<li><p><strong>Async Views</strong>:</p>
<ul>
<li>Use Django’s async views for I/O-bound tasks to improve request handling.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse

    <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">async_view</span>(<span class="hljs-params">request</span>):</span>
        <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">1</span>)
        <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'status'</span>: <span class="hljs-string">'completed'</span>})
</code></pre>
<ul>
<li><p><strong>Celery for Distributed Tasks</strong>:</p>
<ul>
<li>Use Celery to handle distributed task queues, allowing you to offload processing from the main application thread.</li>
</ul>
</li>
</ul>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> shared_task

<span class="hljs-meta">    @shared_task</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">add</span>(<span class="hljs-params">x, y</span>):</span>
        <span class="hljs-keyword">return</span> x + y
</code></pre>
<h3 id="heading-18-frontend-and-api-optimization">18. Frontend and API Optimization</h3>
<h4 id="heading-a-optimizing-apis">a. Optimizing APIs</h4>
<ul>
<li><p><strong>Use DRF Efficiently</strong>:</p>
<ul>
<li>Django Rest Framework (DRF)</li>
</ul>
</li>
</ul>
<h3 id="heading-summary">Summary</h3>
<p>Optimizing a Django application requires a multi-faceted approach, addressing various layers from the database to the frontend. Here’s a summary of steps:↳</p>
<ul>
<li><p>Optimize database queries and use efficient querying techniques.</p>
</li>
<li><p>Implement caching strategies for queries, views, and templates.</p>
</li>
<li><p>Minimize middleware to only essential functions.</p>
</li>
<li><p>Efficiently handle static files and use CDNs for distribution.</p>
</li>
<li><p>Write clean, efficient, and optimized code.</p>
</li>
<li><p>Fine-tune Django settings for better performance and security.</p>
</li>
<li><p>Use asynchronous processing for long-running tasks.</p>
</li>
<li><p>Regularly profile and monitor the application to detect and resolve performance issues.</p>
</li>
<li><p>Secure your application to prevent vulnerabilities and reduce unnecessary processing overhead.</p>
</li>
<li><p>Optimize your deployment setup with appropriate application servers, load balancing, and database tuning.</p>
</li>
</ul>
<p>By systematically applying these practices, you can significantly improve the performance, scalability, and reliability of your Django application.</p>
]]></content:encoded></item><item><title><![CDATA[Setting Up Celery, Celery Beat, Redis, and Django]]></title><description><![CDATA[This guide will walk you through the detailed process of setting up and using Celery with Redis in a Django application. We'll cover task creation, enqueuing tasks, using Redis as a message broker, processing tasks with Celery workers, and scheduling...]]></description><link>https://devendraadhikari.com.np/setting-up-celery-celery-beat-redis-and-django</link><guid isPermaLink="true">https://devendraadhikari.com.np/setting-up-celery-celery-beat-redis-and-django</guid><category><![CDATA[Django]]></category><category><![CDATA[celery]]></category><category><![CDATA[Redis]]></category><category><![CDATA[Celery Beat]]></category><category><![CDATA[message queue]]></category><category><![CDATA[message broker]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sun, 02 Jun 2024 10:40:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717325201221/38eb4ee6-5db7-4ae2-a1ea-16c076a33bfc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This guide will walk you through the detailed process of setting up and using Celery with Redis in a Django application. We'll cover task creation, enqueuing tasks, using Redis as a message broker, processing tasks with Celery workers, and scheduling periodic tasks using Celery Beat.</p>
<h2 id="heading-overview">Overview</h2>
<ol>
<li><p><strong>Celery</strong>: A task queue for managing and executing asynchronous tasks.</p>
</li>
<li><p><strong>Celery Beat</strong>: A scheduler for periodic tasks.</p>
</li>
<li><p><strong>Redis</strong>: A message broker to store and manage task queues.</p>
</li>
<li><p><strong>Django</strong>: A web framework to create and manage web applications.</p>
</li>
</ol>
<h2 id="heading-step-by-step-guide">Step-by-Step Guide</h2>
<h3 id="heading-1-install-required-packages">1. Install Required Packages</h3>
<p>First, install the necessary packages using pip:</p>
<pre><code class="lang-plaintext">pip install celery redis django
</code></pre>
<h3 id="heading-2-configure-django-project">2. Configure Django Project</h3>
<p>Create a Django project and application if you haven't already:</p>
<pre><code class="lang-plaintext">django-admin startproject myproject
cd myproject
django-admin startapp myapp
</code></pre>
<h3 id="heading-3-setup-celery">3. Setup Celery</h3>
<p>Create a <a target="_blank" href="http://celery.py"><code>celery.py</code></a> file in your project directory (<code>myproject/</code><a target="_blank" href="http://celery.py"><code>celery.py</code></a>) to configure Celery:↳</p>
<pre><code class="lang-plaintext"># myproject/celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery

# Set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

app = Celery('myproject')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')
</code></pre>
<h3 id="heading-4-ensure-celery-loads-when-django-starts">4. Ensure Celery Loads When Django Starts</h3>
<p>Modify the <code>__init__.py</code> file in your project directory (<code>myproject/__init__.py</code>):</p>
<pre><code class="lang-plaintext"># myproject/__init__.py

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)
</code></pre>
<h3 id="heading-5-configure-django-settings">5. Configure Django Settings</h3>
<p>Add the Celery and Redis configurations to your Django settings (<code>myproject/</code><a target="_blank" href="http://settings.py"><code>settings.py</code></a>):</p>
<pre><code class="lang-plaintext"># settings.py

CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0'
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
</code></pre>
<h3 id="heading-6-define-tasks">6. Define Tasks</h3>
<p>Create tasks in your Django app (<code>myapp/</code><a target="_blank" href="http://tasks.py"><code>tasks.py</code></a>):</p>
<pre><code class="lang-plaintext"># myapp/tasks.py

from celery import shared_task

@shared_task
def add(x, y):
    return x + y

@shared_task
def some_periodic_task():
    # Task code here
    pass
</code></pre>
<h3 id="heading-7-enqueue-tasks">7. Enqueue Tasks</h3>
<p>Enqueue tasks from your Django views or other parts of your application (<code>myapp/</code><a target="_blank" href="http://views.py"><code>views.py</code></a>):</p>
<pre><code class="lang-plaintext"># myapp/views.py

from django.http import JsonResponse
from .tasks import add

def my_view(request):
    result = add.delay(4, 4)  # Enqueues the task to Redis
    return JsonResponse({'task_id': result.id})
</code></pre>
<h3 id="heading-8-setup-celery-beat-for-periodic-tasks">8. Setup Celery Beat for Periodic Tasks</h3>
<p>Configure periodic tasks in <a target="_blank" href="http://celery.py"><code>celery.py</code></a>:</p>
<pre><code class="lang-plaintext"># myproject/celery.py

from celery.schedules import crontab

app.conf.beat_schedule = {
    'add-every-30-seconds': {
        'task': 'myapp.tasks.add',
        'schedule': 30.0,
        'args': (16, 16)
    },
    'run-every-monday-morning': {
        'task': 'myapp.tasks.some_periodic_task',
        'schedule': crontab(hour=7, minute=30, day_of_week=1),
        'args': ()
    },
}
app.conf.timezone = 'UTC'
</code></pre>
<ul>
<li><p><code>add-every-30-seconds</code>: This task runs every 30 seconds and calls the <code>add</code> function with the arguments <code>16</code> and <code>16</code>.</p>
</li>
<li><p><code>run-every-monday-morning</code>: This task runs every Monday at 7:30 AM and calls the <code>some_periodic_task</code> function without any arguments.</p>
</li>
</ul>
<h3 id="heading-9-start-celery-worker-and-celery-beat">9. Start Celery Worker and Celery Beat</h3>
<p>Start a Celery worker to process tasks:</p>
<pre><code class="lang-plaintext">celery -A myproject worker --loglevel=info
</code></pre>
<p>Start Celery Beat to schedule periodic tasks:</p>
<pre><code class="lang-plaintext">celery -A myproject beat --loglevel=info
</code></pre>
<p>Alternatively, you can run both a worker and beat in one command:</p>
<pre><code class="lang-plaintext">celery -A myproject worker -B --loglevel=info
</code></pre>
<h3 id="heading-10-monitoring-and-management">10. Monitoring and Management</h3>
<h4 id="heading-flower">Flower</h4>
<p>Flower is a real-time web-based monitoring tool for Celery.</p>
<p>Install Flower:</p>
<pre><code class="lang-plaintext">pip install flower
</code></pre>
<p>Run Flower:</p>
<pre><code class="lang-plaintext">celery -A myproject flower
</code></pre>
<p>Access Flower in your web browser at <a target="_blank" href="http://localhost:5555.↳"><code>http://localhost:5555</code>.</a></p>
<h4 id="heading-redis-cli">Redis CLI</h4>
<p>Inspect the queues and tasks using Redis CLI.</p>
<p>Start the Redis CLI:</p>
<pre><code class="lang-plaintext">redis-cli
</code></pre>
<p>Example commands:</p>
<ul>
<li><p><code>KEYS *</code>: Lists all keys in the Redis database.</p>
</li>
<li><p><code>LLEN celery</code>: Shows the number of tasks in the <code>celery</code> queue.</p>
</li>
</ul>
<h2 id="heading-example-django-project-structure">Example Django Project Structure</h2>
<p>Here's an example directory structure for a Django project with Celery tasks:</p>
<pre><code class="lang-plaintext">myproject/
    __init__.py
    settings.py
    urls.py
    wsgi.py
    celery.py
myapp/
    __init__.py
    tasks.py
    views.py
</code></pre>
<h2 id="heading-summary">Summary</h2>
<ol>
<li><p><strong>Install Packages</strong>: Install Celery and Redis.</p>
</li>
<li><p><strong>Configure Celery</strong>: Create and configure <a target="_blank" href="http://celery.py"><code>celery.py</code></a>.</p>
</li>
<li><p><strong>Load Celery</strong>: Ensure Celery loads with Django.</p>
</li>
<li><p><strong>Configure Settings</strong>: Add Celery and Redis configurations in Django settings.</p>
</li>
<li><p><strong>Define Tasks</strong>: Create tasks in your Django app.</p>
</li>
<li><p><strong>Enqueue Tasks</strong>: Use the <code>delay</code> method to add tasks to the Redis queue.</p>
</li>
<li><p><strong>Periodic Tasks</strong>: Configure periodic tasks with Celery Beat.</p>
</li>
<li><p><strong>Start Processes</strong>: Run Celery worker and beat to process tasks and schedule periodic tasks.</p>
</li>
<li><p><strong>Monitoring</strong>: Use tools like Flower and Redis CLI to monitor and manage tasks.</p>
</li>
</ol>
<p>By following these detailed steps, you can set up a Django application to handle asynchronous tasks and periodic tasks using Celery, Celery Beat, and Redis. This setup helps in managing background jobs efficiently and ensures your application remains responsive.  </p>
<p>#######################<strong>BONUS :D #############################</strong><br /><strong>Retrieving the Result</strong>:</p>
<ul>
<li>The task ID (<a target="_blank" href="http://result.id"><code>result.id</code></a>) can be used to query the result.</li>
</ul>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> celery.result <span class="hljs-keyword">import</span> AsyncResult

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_task_result</span>(<span class="hljs-params">task_id</span>):</span>
    result = AsyncResult(task_id)
    <span class="hljs-keyword">if</span> result.ready():
        <span class="hljs-keyword">return</span> result.result  <span class="hljs-comment"># The result of the task</span>
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Task not yet completed'</span>
</code></pre>
<p>The End :D</p>
]]></content:encoded></item><item><title><![CDATA[Redis as a Cache in Django]]></title><description><![CDATA[Redis is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. It supports various data structures like strings, hashes, lists, sets, and sorted sets, making it versatile for a wide range of use cas...]]></description><link>https://devendraadhikari.com.np/redis-as-a-cache-in-django</link><guid isPermaLink="true">https://devendraadhikari.com.np/redis-as-a-cache-in-django</guid><category><![CDATA[Redis]]></category><category><![CDATA[cache]]></category><category><![CDATA[Redis Key]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sun, 02 Jun 2024 09:10:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717319385949/105fac0e-235c-4234-8d0b-0464b1bfb8d9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Redis is an open-source, in-memory data structure store that can be used as a database, cache, and message broker. It supports various data structures like strings, hashes, lists, sets, and sorted sets, making it versatile for a wide range of use cases.</p>
<h3 id="heading-key-features-of-redis">Key Features of Redis:</h3>
<ol>
<li><p><strong>In-Memory Data Storage</strong>: Redis stores data in memory, making it extremely fast for read and write operations.</p>
</li>
<li><p><strong>Persistence Options</strong>: Redis supports different persistence options like snapshotting and append-only files to ensure data durability.</p>
</li>
<li><p><strong>Data Structures</strong>: Redis provides a rich set of data structures like strings, hashes, lists, sets, and sorted sets, allowing for flexible data modeling.</p>
</li>
<li><p><strong>Atomic Operations</strong>: Redis supports atomic operations on data structures, making it suitable for building high-performance applications.</p>
</li>
<li><p><strong>Pub/Sub Messaging</strong>: Redis offers pub/sub messaging for building real-time applications and message queues.</p>
</li>
<li><p><strong>Replication and Sharding</strong>: Redis supports replication and sharding for high availability and scalability.</p>
</li>
<li><p><strong>Lua Scripting</strong>: Redis allows you to write Lua scripts for complex data manipulation and processing.</p>
</li>
</ol>
<h3 id="heading-policies-in-redis">Policies in Redis:</h3>
<ol>
<li><p><strong>Eviction Policies</strong>: Redis allows you to configure different eviction policies for handling memory constraints, such as <strong>LRU</strong> (Least Recently Used), <strong>LFU</strong> (Least Frequently Used), and Random.<br /> <strong>LRU :</strong> Suppose a cache has a memory limit of 100 keys and it currently holds 120 keys. When a new key needs to be added to the cache, Redis checks the access timestamps of all keys. It then selects the 20 keys that were accessed the longest time ago and evicts them from the cache to make space for the new key.</p>
<p> <strong>LFU:</strong> Suppose a cache has a memory limit of 100 keys and it currently holds 120 keys. When a new key needs to be added to the cache, Redis checks the access counts of all keys. It then selects the 20 keys with the lowest access counts and evicts them from the cache to make space for the new key.</p>
</li>
<li><p><strong>Expiration Policies</strong>: Redis supports setting expiration times for keys, after which they will automatically be removed from the database.</p>
</li>
</ol>
<h3 id="heading-using-redis-in-django-with-hands-on-example">Using Redis in Django with Hands-On Example:</h3>
<p>To use Redis in Django for caching, follow these steps:</p>
<ol>
<li><p><strong>Install Redis Server and Python Redis Client</strong>:</p>
<ul>
<li><p>Install Redis server on your system or use a cloud-based service like Redis Labs.</p>
</li>
<li><p>Install the Python Redis client using pip:</p>
<pre><code class="lang-plaintext">  pip install django-redis
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Configure Redis Cache Backend in Django Settings</strong>:</p>
<ul>
<li><p>Open your Django project's <a target="_blank" href="http://settings.py"><code>settings.py</code></a> file and configure Redis as the cache backend:</p>
<pre><code class="lang-plaintext">  codeCACHES = {
      'default': {
          'BACKEND': 'django_redis.cache.RedisCache',
          'LOCATION': 'redis://127.0.0.1:6379/1',  # URL of your Redis instance
          'OPTIONS': {
              'CLIENT_CLASS': 'django_redis.client.DefaultClient',
          }
      }
  }
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Use Redis Cache in Django Views</strong>:</p>
<ul>
<li><p>You can now use Django's cache framework to set and retrieve data from Redis in your views:</p>
<pre><code class="lang-plaintext">  from django.core.cache import cache

  def my_view(request):
      # Set cache
      cache.set('my_key', 'my_value', timeout=3600)  # Cache for 1 hour

      # Get cache
      value = cache.get('my_key')
</code></pre>
<p>  ```</p>
</li>
</ul>
</li>
<li><p><strong>Cache Decorators</strong>:</p>
<ul>
<li><p>Django provides cache decorators to cache the output of views for a specified amount of time:</p>
<pre><code class="lang-plaintext">  from django.views.decorators.cache import cache_page

  @cache_page(60 * 15)  # Cache for 15 minutes
  def my_cached_view(request):
      # View logic
</code></pre>
<p>  ```</p>
</li>
</ul>
</li>
<li><p><strong>Cache Middleware</strong>:</p>
<ul>
<li><p>You can also use cache middleware to cache entire pages or parts of pages in your Django application:</p>
<pre><code class="lang-plaintext">  codeMIDDLEWARE = [
      ...
      'django.middleware.cache.UpdateCacheMiddleware',
      'django.middleware.common.CommonMiddleware',
      'django.middleware.cache.FetchFromCacheMiddleware',
      ...
  ]
</code></pre>
</li>
</ul>
</li>
<li><p><strong>Redis CLI for Monitoring</strong>:</p>
<ul>
<li><p>You can use the Redis CLI to monitor cache activity and inspect cache keys:</p>
<pre><code class="lang-plaintext">  $ redis-cli
  127.0.0.1:6379&gt; KEYS *
</code></pre>
</li>
</ul>
</li>
</ol>
<p>By following these steps, you can integrate Redis caching into your Django applications to improve performance and scalability. Redis offers various features and policies that you can leverage to optimize your caching strategy based on your application's requirements.  </p>
<p>To change the default eviction policy to use LRU (Least Recently Used), you need to set the <code>maxmemory-policy</code> option in the Redis configuration to <code>volatile-lru</code>. Here's how you can modify the Django configuration to achieve this:↳</p>
<pre><code class="lang-plaintext">CACHES = {
    'default': {
        'BACKEND': 'django_redis.cache.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379/1',  # URL of your Redis instance
        'OPTIONS': {
            'CLIENT_CLASS': 'django_redis.client.DefaultClient',
            'MAXMEMORY_POLICY': 'volatile-lru',  # Set the eviction policy to LRU
        }
    }
}
</code></pre>
<p>By adding the <code>MAXMEMORY_POLICY</code> option with the value <code>volatile-lru</code> to the <code>OPTIONS</code> dictionary, you instruct Redis to use the LRU eviction policy among the keys with an expiration set (<code>volatile-lru</code>). This means that Redis will evict keys based on their last access time when memory is full, prioritizing keys with an expiration set (e.g., keys set with a TTL). You can also change the policy from redis.conf file.</p>
]]></content:encoded></item><item><title><![CDATA[Useful Docker Commands In daily use]]></title><description><![CDATA[Docker Basics

docker version

Shows the Docker version installed on your system.

  docker version




docker info

Displays system-wide information about Docker, including number of containers, images, and other details.
  docker info




docker he...]]></description><link>https://devendraadhikari.com.np/useful-docker-commands-in-daily-use</link><guid isPermaLink="true">https://devendraadhikari.com.np/useful-docker-commands-in-daily-use</guid><category><![CDATA[Docker]]></category><category><![CDATA[Commands]]></category><category><![CDATA[Docker compose]]></category><category><![CDATA[Dockerfile]]></category><category><![CDATA[docker images]]></category><category><![CDATA[docker-network]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sat, 01 Jun 2024 05:41:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717220617141/1abdbb21-7873-41bb-8216-acc8c3f55b02.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-docker-basics">Docker Basics</h3>
<ol>
<li><p><strong>docker version</strong></p>
<ul>
<li><p>Shows the Docker version installed on your system.</p>
</li>
<li><pre><code class="lang-plaintext">  docker version
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker info</strong></p>
<ul>
<li><p>Displays system-wide information about Docker, including number of containers, images, and other details.</p>
<pre><code class="lang-plaintext">  docker info
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker help</strong></p>
<ul>
<li><p>Provides help on using Docker commands.</p>
<pre><code class="lang-python">  docker help
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-working-with-images">Working with Images</h3>
<ol start="4">
<li><p><strong>docker pull</strong></p>
<ul>
<li><p>Downloads an image from a Docker registry (e.g., Docker Hub).</p>
<pre><code class="lang-python">  docker pull &lt;image_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker images</strong></p>
<ul>
<li><p>Lists all the images on your local machine.</p>
<pre><code class="lang-python">  docker images
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker rmi</strong></p>
<ul>
<li><p>Removes one or more images from your local machine.</p>
</li>
<li><pre><code class="lang-python">  docker rmi &lt;image_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker tag</strong></p>
<ul>
<li><p>Tags an image with a new name.</p>
<pre><code class="lang-python">  docker tag &lt;existing_image&gt; &lt;new_image:tag&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker build</strong></p>
<ul>
<li><p>Builds an image from a Dockerfile.</p>
<pre><code class="lang-python">  docker build -t &lt;image_name:tag&gt; &lt;path_to_dockerfile&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker push</strong></p>
<ul>
<li><p>Uploads an image to a Docker registry.</p>
<pre><code class="lang-python">  docker push &lt;image_name:tag&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-working-with-containers">Working with Containers</h3>
<ol start="10">
<li><p><strong>docker run</strong></p>
<ul>
<li><p>Runs a container from an image.</p>
<pre><code class="lang-python">  docker run -d --name &lt;container_name&gt; &lt;image_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker ps</strong></p>
<ul>
<li><p>Lists all running containers.</p>
<pre><code class="lang-python">  docker ps
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker ps -a</strong></p>
<ul>
<li><p>Lists all containers, including stopped ones.</p>
<pre><code class="lang-python">  docker ps -a
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker stop</strong></p>
<ul>
<li><p>Stops a running container.</p>
<pre><code class="lang-python">  docker stop &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker start</strong></p>
<ul>
<li><p>Starts a stopped container.</p>
<pre><code class="lang-python">  docker start &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker restart</strong></p>
<ul>
<li><p>Restarts a container.</p>
<pre><code class="lang-python">  docker restart &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker rm</strong></p>
<ul>
<li><p>Removes a container.</p>
<pre><code class="lang-python">  docker rm &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker logs</strong></p>
<ul>
<li><p>Displays the logs of a container.</p>
<pre><code class="lang-python">  docker logs &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker exec</strong></p>
<ul>
<li><p>Runs a command in a running container.</p>
<pre><code class="lang-python">  docker <span class="hljs-keyword">exec</span> -it &lt;container_id&gt; &lt;command&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker attach</strong></p>
<ul>
<li><p>Attaches your terminal to a running container.</p>
<pre><code class="lang-python">  docker attach &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-container-networking">Container Networking</h3>
<ol start="20">
<li><p><strong>docker network ls</strong></p>
<ul>
<li><p>Lists all Docker networks.</p>
<pre><code class="lang-python">  docker network ls
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker network create</strong></p>
<ul>
<li><p>Creates a new Docker network.</p>
<pre><code class="lang-python">  docker network create &lt;network_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker network inspect</strong></p>
<ul>
<li><p>Displays detailed information about a network.</p>
<pre><code class="lang-python">  docker network inspect &lt;network_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker network connect</strong></p>
<ul>
<li><p>Connects a container to a network.</p>
<pre><code class="lang-python">  docker network connect &lt;network_name&gt; &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker network disconnect</strong></p>
<ul>
<li><p>Disconnects a container from a network.</p>
<pre><code class="lang-python">  docker network disconnect &lt;network_name&gt; &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-docker-volumes">Docker Volumes</h3>
<ol start="25">
<li><p><strong>docker volume ls</strong></p>
<ul>
<li><p>Lists all Docker volumes.</p>
<pre><code class="lang-python">  docker volume ls
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker volume create</strong></p>
<ul>
<li><p>Creates a new Docker volume.</p>
<pre><code class="lang-python">  docker volume create &lt;volume_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker volume inspect</strong></p>
<ul>
<li><p>Displays detailed information about a volume.</p>
<pre><code class="lang-python">  docker volume inspect &lt;volume_name&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker volume rm</strong></p>
<ul>
<li><p>Removes a Docker volume.</p>
<pre><code class="lang-python">  docker volume rm &lt;volume_name&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-docker-compose">Docker Compose</h3>
<ol start="29">
<li><p><strong>docker-compose up</strong></p>
<ul>
<li><p>Builds, (re)creates, starts, and attaches to containers for a service defined in a <code>docker-compose.yml</code> file.</p>
<pre><code class="lang-python">  docker-compose up
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker-compose down</strong></p>
<ul>
<li><p>Stops and removes containers, networks, volumes, and images created by <code>docker-compose up</code>.</p>
<pre><code class="lang-python">  docker-compose down
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker-compose ps</strong></p>
<ul>
<li><p>Lists containers started by Docker Compose.</p>
<pre><code class="lang-python">  docker-compose ps
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker-compose logs</strong></p>
<ul>
<li><p>Displays log output from services managed by Docker Compose.</p>
<pre><code class="lang-python">  docker-compose logs
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker-compose exec</strong></p>
<ul>
<li><p>Executes a command in a running service container.</p>
<pre><code class="lang-python">  docker-compose <span class="hljs-keyword">exec</span> &lt;service_name&gt; &lt;command&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-cleanup-commands">Cleanup Commands</h3>
<ol start="34">
<li><p><strong>docker system prune</strong></p>
<ul>
<li><p>Removes all unused containers, networks, images (both dangling and unreferenced), and optionally, volumes.</p>
<pre><code class="lang-python">  docker system prune
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker container prune</strong></p>
<ul>
<li><p>Removes all stopped containers.</p>
<pre><code class="lang-python">  docker container prune
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker image prune</strong></p>
<ul>
<li><p>Removes unused images.</p>
<pre><code class="lang-python">  docker image prune
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker volume prune</strong></p>
<ul>
<li><p>Removes all unused volumes.</p>
<pre><code class="lang-python">  docker volume prune
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-inspecting-and-debugging">Inspecting and Debugging</h3>
<ol start="38">
<li><p><strong>docker inspect</strong></p>
<ul>
<li><p>Returns low-level information about Docker objects.</p>
<pre><code class="lang-python">  docker inspect &lt;container_id <span class="hljs-keyword">or</span> image_id&gt;
</code></pre>
</li>
</ul>
</li>
<li><p><strong>docker diff</strong></p>
<ul>
<li><p>Inspects changes to files or directories on a container’s filesystem.</p>
<pre><code class="lang-python">  docker diff &lt;container_id&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<h3 id="heading-security">Security</h3>
<ol start="40">
<li><p><strong>docker scan</strong></p>
<ul>
<li><p>Scans your Docker images for vulnerabilities.</p>
<pre><code class="lang-python">  docker scan &lt;image_name&gt;
</code></pre>
</li>
</ul>
</li>
</ol>
<p>By mastering these commands, you can effectively manage Docker images, containers, networks, volumes, and more, enhancing your ability to deploy and maintain containerized applications.</p>
]]></content:encoded></item><item><title><![CDATA[Reverse Proxy]]></title><description><![CDATA[A reverse proxy is a server that sits between client devices and a backend server, forwarding client requests to the appropriate backend server and returning the server's responses to the clients. Unlike a forward proxy, which acts on behalf of the c...]]></description><link>https://devendraadhikari.com.np/reverse-proxy</link><guid isPermaLink="true">https://devendraadhikari.com.np/reverse-proxy</guid><category><![CDATA[Proxy Server]]></category><category><![CDATA[Reverse Proxy]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Fri, 31 May 2024 15:05:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1717167894708/e11268d8-1616-4d29-8ff6-a73a225e087a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A reverse proxy is a <strong>server</strong> that sits between <strong>client devices</strong> and a <strong>backend server</strong>, forwarding client requests to the appropriate backend server and returning the server's responses to the clients. Unlike a forward proxy, which acts on behalf of the client to access a server, a <strong>reverse proxy</strong> <strong>acts</strong> on behalf of the <strong>server to mediate traffic between the server and clients.</strong>  </p>
<p><strong>Key Functions and Benefits of a Reverse Proxy:</strong></p>
<ol>
<li><p><strong>Load Balancing</strong>: Distributes incoming client requests across multiple backend servers to ensure no single server becomes overwhelmed. This improves overall application performance and availability.</p>
</li>
<li><p><strong>Improved Security</strong>: Hides the backend servers' details from clients, which adds a layer of security. It can also provide protection against Distributed Denial of Service (DDoS) attacks by managing traffic and identifying malicious requests.</p>
</li>
<li><p><strong>SSL Termination</strong>: Manages SSL encryption and decryption, offloading this resource-intensive process from backend servers. This can improve performance and simplify the management of SSL certificates.</p>
</li>
<li><p><strong>Caching</strong>: Stores copies of frequently requested resources, which reduces the load on backend servers and speeds up response times for clients.</p>
</li>
<li><p><strong>Compression</strong>: Compresses responses before sending them to clients, reducing bandwidth usage and improving load times.</p>
</li>
<li><p><strong>Static Content Delivery</strong>: Serves static content such as images, CSS, and JavaScript files directly to clients, reducing the load on backend servers.</p>
</li>
<li><p><strong>Application Firewall</strong>: Inspects incoming traffic for security threats, providing an additional layer of defense against attacks like SQL injection or cross-site scripting (XSS).</p>
</li>
</ol>
<h3 id="heading-common-use-cases-for-reverse-proxies">Common Use Cases for Reverse Proxies:</h3>
<ul>
<li><p><strong>Web Servers</strong>: Reverse proxies are often used in conjunction with web servers like Apache or Nginx to manage web traffic efficiently.</p>
</li>
<li><p><strong>Microservices Architecture</strong>: They can help manage communication between different services in a microservices-based application.</p>
</li>
<li><p><strong>Content Delivery Networks (CDNs)</strong>: CDNs often use reverse proxies to deliver content from edge servers located closer to users, improving performance and reducing latency.</p>
</li>
</ul>
<h3 id="heading-how-a-reverse-proxy-works">How a Reverse Proxy Works:</h3>
<ol>
<li><p><strong>Client Request</strong>: A client (e.g., a web browser) sends a request to a domain (e.g., <a target="_blank" href="http://example.com">example.com</a>).</p>
</li>
<li><p><strong>DNS Resolution</strong>: The domain name is resolved to the IP address of the reverse proxy server.</p>
</li>
<li><p><strong>Request Forwarding</strong>: The reverse proxy server receives the request and forwards it to one of the backend servers based on its routing logic (e.g., load balancing algorithm).</p>
</li>
<li><p><strong>Backend Server Response</strong>: The backend server processes the request and sends the response back to the reverse proxy server.</p>
</li>
<li><p><strong>Client Response</strong>: The reverse proxy server sends the backend server's response to the client.</p>
</li>
</ol>
<p>By managing and optimizing client requests and server responses, a reverse proxy can significantly improve the efficiency, security, and scalability of web services and applications.</p>
]]></content:encoded></item><item><title><![CDATA[OOP Python]]></title><description><![CDATA[OOP stands for Object-Oriented Programming. It's a programming paradigm that revolves around the concept of "objects," which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often...]]></description><link>https://devendraadhikari.com.np/oop-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/oop-python</guid><category><![CDATA[Python]]></category><category><![CDATA[oop]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Sat, 04 May 2024 13:02:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714925716603/05592f3d-0a3e-4a65-9f26-f5f5e1c21032.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>OOP stands for Object-Oriented Programming. It's a programming paradigm that revolves around the concept of "objects," which can contain data, in the form of fields (often known as attributes or properties), and code, in the form of procedures (often known as methods).  </p>
<p><strong>1. Classes and Objects:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, make, model</span>):</span>
        self.make = make
        self.model = model

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">drive</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Driving <span class="hljs-subst">{self.make}</span> <span class="hljs-subst">{self.model}</span>"</span>)

<span class="hljs-comment"># Create instances of the Car class</span>
car1 = Car(<span class="hljs-string">"Toyota"</span>, <span class="hljs-string">"Camry"</span>)
car2 = Car(<span class="hljs-string">"Honda"</span>, <span class="hljs-string">"Accord"</span>)

<span class="hljs-comment"># Call the drive method on the instances</span>
car1.drive()  <span class="hljs-comment"># Output: Driving Toyota Camry</span>
car2.drive()  <span class="hljs-comment"># Output: Driving Honda Accord</span>
</code></pre>
<p><strong>2. Inheritance:</strong></p>
<p>Inheritance allows a class (subclass) to inherit attributes and methods from another class (superclass). It promotes code reusability and establishes an "is-a" relationship between classes.  </p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ElectricCar</span>(<span class="hljs-params">Car</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, make, model, battery_capacity</span>):</span>
        super().__init__(make, model)
        self.battery_capacity = battery_capacity

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">charge</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">f"Charging <span class="hljs-subst">{self.make}</span> <span class="hljs-subst">{self.model}</span> with <span class="hljs-subst">{self.battery_capacity}</span> kWh"</span>)

electric_car = ElectricCar(<span class="hljs-string">"Tesla"</span>, <span class="hljs-string">"Model S"</span>, <span class="hljs-number">100</span>)
electric_car.drive()  <span class="hljs-comment"># Inherited method from Car class</span>
electric_car.charge()  <span class="hljs-comment"># New method in ElectricCar class</span>
</code></pre>
<p><strong>3. Polymorphism:</strong></p>
<p>Polymorphism allows objects of different classes to be treated as objects of a common superclass. It enables flexibility and extensibility in code by allowing methods to behave differently based on the object they are called on.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">area</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Rectangle</span>(<span class="hljs-params">Shape</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, width, height</span>):</span>
        self.width = width
        self.height = height

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">area</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> self.width * self.height

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Circle</span>(<span class="hljs-params">Shape</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, radius</span>):</span>
        self.radius = radius

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">area</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-number">3.14</span> * self.radius ** <span class="hljs-number">2</span>

<span class="hljs-comment"># Polymorphic function</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">print_area</span>(<span class="hljs-params">shape</span>):</span>
    print(<span class="hljs-string">f"Area: <span class="hljs-subst">{shape.area()}</span>"</span>)

<span class="hljs-comment"># Usage</span>
rectangle = Rectangle(<span class="hljs-number">5</span>, <span class="hljs-number">4</span>)
circle = Circle(<span class="hljs-number">3</span>)

print_area(rectangle)  <span class="hljs-comment"># Output: Area: 20</span>
print_area(circle)
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Custom Middleware In Django]]></title><description><![CDATA[In Django, middleware is a framework of hooks into Django's request/response processing. It's a way to modify the input or output of Django views and allows you to perform operations on requests and responses globally for your project. Middleware sit...]]></description><link>https://devendraadhikari.com.np/custom-middleware-in-django</link><guid isPermaLink="true">https://devendraadhikari.com.np/custom-middleware-in-django</guid><category><![CDATA[Python]]></category><category><![CDATA[Middleware]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Wed, 01 May 2024 12:52:45 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714568065606/4ef6ce11-7e32-49cf-82f7-1ed3ca0b39d5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Django, middleware is a framework of hooks into Django's request/response processing. It's a way to modify the input or output of Django views and allows you to perform operations on requests and responses globally for your project. Middleware sits between the request and the view, and between the view and the response, allowing you to modify incoming requests and outgoing responses.</p>
<p>Here's a brief overview of middleware in Django:</p>
<ol>
<li><p><strong>How Middleware Works</strong>: Middleware consists of a series of classes defined in Python that define methods for processing requests and responses. Each middleware component can perform operations before and after the view is called.</p>
</li>
<li><p><strong>Order of Middleware Execution</strong>: Middleware classes are executed in the order they are defined in the <code>MIDDLEWARE</code> setting in your Django project's settings file (<a target="_blank" href="http://settings.py"><code>settings.py</code></a>). Middleware defined earlier in the list are executed first, and middleware defined later are executed later.</p>
</li>
<li><p><strong>Common Use Cases for Middleware</strong>:</p>
<ul>
<li><p>Authentication: Checking if a user is logged in and redirecting if not.</p>
</li>
<li><p>Session Management: Handling session-related tasks.</p>
</li>
<li><p>Security: Adding security headers, XSS protection, etc.</p>
</li>
<li><p>Content-Length Header: Setting the <code>Content-Length</code> header for responses.</p>
</li>
<li><p>CORS (Cross-Origin Resource Sharing) Handling: Adding CORS headers to responses.</p>
</li>
<li><p>Request/Response Logging: Logging incoming requests and outgoing responses for debugging or analytics purposes.</p>
</li>
<li><p>Compression: Compressing responses for improved performance.</p>
</li>
</ul>
</li>
<li><p><strong>Creating Custom Middleware</strong>: You can create custom middleware by defining a class with methods such as <code>__init__</code>, <code>__call__</code>, <code>process_request</code>, <code>process_response</code>, etc. These methods are called at different stages of request/response processing.  </p>
<p> Here's a simple example of custom middleware that logs each request and its corresponding response:</p>
</li>
</ol>
<pre><code class="lang-python"><span class="hljs-comment"># custom_middleware.py</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RequestResponseLoggerMiddleware</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, get_response</span>):</span>
        self.get_response = get_response

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__call__</span>(<span class="hljs-params">self, request</span>):</span>
        <span class="hljs-comment"># Logic to execute before the view is called</span>
        response = self.get_response(request)
        <span class="hljs-comment"># Logic to execute after the view is called</span>
        <span class="hljs-keyword">return</span> response

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_request</span>(<span class="hljs-params">self, request</span>):</span>
        <span class="hljs-comment"># Logic to execute before the view is called</span>
        print(<span class="hljs-string">f"Request Path: <span class="hljs-subst">{request.path}</span>"</span>)

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_response</span>(<span class="hljs-params">self, request, response</span>):</span>
        <span class="hljs-comment"># Logic to execute after the view is called</span>
        print(<span class="hljs-string">f"Response Status Code: <span class="hljs-subst">{response.status_code}</span>"</span>)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p>To use this middleware, add its path to the MIDDLEWARE setting in your Django project's settings file:</p>
<pre><code class="lang-python"><span class="hljs-comment"># settings.py</span>

MIDDLEWARE = [
    <span class="hljs-comment"># Other middleware classes...</span>
    <span class="hljs-string">'myapp.custom_middleware.RequestResponseLoggerMiddleware'</span>,
]
</code></pre>
<p>This will log the path of each incoming request and the corresponding response status code.</p>
<p>Overall, middleware in Django provides a powerful way to globally customize the behavior of request/response processing in your Django project. It's a fundamental aspect of Django's architecture and is widely used for various purposes such as authentication, security, logging, and more.</p>
]]></content:encoded></item><item><title><![CDATA[Decorator In Python]]></title><description><![CDATA[A decorator in Python is a design pattern that allows behavior to be added to objects dynamically. It's a function that takes another function as an argument and extends its functionality without modifying it. Decorators are widely used in Python for...]]></description><link>https://devendraadhikari.com.np/decorator-in-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/decorator-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[decorators]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Wed, 01 May 2024 10:17:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1714541078452/a51fb56f-fce5-4362-b830-cab776cb233b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>A decorator in Python is a design pattern that allows behavior to be added to objects dynamically. It's a function that takes another function as an argument and extends its functionality without modifying it. Decorators are widely used in Python for various purposes such as logging, authentication, caching, and more.</p>
<p>In essence, a decorator wraps another function, allowing you to execute code before and/or after the wrapped function runs, or even completely replace the original function with a new one. This enables you to add reusable functionalities to functions or methods without modifying their core logic.  </p>
<p>Example 1:-</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_decorator</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">wrapper</span>():</span>
        print(<span class="hljs-string">"Something is happening before the function is called."</span>)
        func()  <span class="hljs-comment"># Call the original function</span>
        print(<span class="hljs-string">"Something is happening after the function is called."</span>)
    <span class="hljs-keyword">return</span> wrapper

<span class="hljs-meta">@my_decorator</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">say_hello</span>():</span>
    print(<span class="hljs-string">"Hello!"</span>)

say_hello()
</code></pre>
<p>Example 2:-  </p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">smart_divide</span>(<span class="hljs-params">func</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">inner</span>(<span class="hljs-params">a, b</span>):</span>
        print(<span class="hljs-string">"Dividing"</span>, a, <span class="hljs-string">"and"</span>, b)
        <span class="hljs-keyword">if</span> b == <span class="hljs-number">0</span>:
            print(<span class="hljs-string">"Cannot divide"</span>)
            <span class="hljs-keyword">return</span>

        <span class="hljs-keyword">return</span> func(a, b)
    <span class="hljs-keyword">return</span> inner

<span class="hljs-meta">@smart_divide</span>
<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">divide</span>(<span class="hljs-params">a, b</span>):</span>
    print(a/b)

divide(<span class="hljs-number">4</span>,<span class="hljs-number">2</span>)

divide(<span class="hljs-number">5</span>,<span class="hljs-number">0</span>)
</code></pre>
<p>In conclusion, decorators in Python provide a powerful mechanism for extending and modifying the behavior of functions or methods without altering their original code. They allow you to add reusable functionalities such as logging, authentication, caching, performance optimization, and more in a clear, concise, and modular way.</p>
<p>Key points about decorators:</p>
<ol>
<li><p><strong>Function Wrapping</strong>: Decorators wrap functions or methods with additional functionality, enabling you to execute code before and/or after the wrapped function runs, or even replace the original function with a new one.</p>
</li>
<li><p><strong>Syntax</strong>: Decorators are implemented using the <code>@decorator_name</code> syntax, which is a convenient way to apply a decorator to a function or method.</p>
</li>
<li><p><strong>Flexibility</strong>: Decorators can take arguments and be chained together to create complex behavior. They can also be applied to both standalone functions and methods within classes.</p>
</li>
<li><p><strong>Maintaining Function Metadata</strong>: The <code>functools.wraps</code> decorator helps preserve metadata such as docstrings and function names when using decorators.</p>
</li>
<li><p><strong>Common Use Cases</strong>: Decorators are widely used in various programming scenarios, including web development, asynchronous programming, testing, and performance optimization.</p>
</li>
</ol>
<p>Overall, decorators are an essential feature of Python that promotes code reusability, modularity, and readability, making it easier to develop and maintain Python applications.</p>
]]></content:encoded></item><item><title><![CDATA[Generators in Python]]></title><description><![CDATA[Python generators are functions that generate an iterable sequence of values. Unlike regular functions, generators use the "yield" keyword instead of "return" to return a value and suspend the execution of the function. This allows generators to prod...]]></description><link>https://devendraadhikari.com.np/generators-in-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/generators-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[generators]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Mon, 06 Mar 2023 16:52:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678121682621/46e0909a-5314-4a3c-b597-1e3d8158ae55.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Python generators are functions that generate an iterable sequence of values. Unlike regular functions, generators use the "yield" keyword instead of "return" to return a value and suspend the execution of the function. This allows generators to produce a sequence of values on the fly, rather than generating a complete list or tuple of values at once.</p>
<p>Here is an example of a simple generator that produces the first 5 even numbers:</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">even_numbers</span>():</span>
    n = <span class="hljs-number">0</span>
    <span class="hljs-keyword">while</span> n &lt; <span class="hljs-number">10</span>:
        <span class="hljs-keyword">yield</span> n
        n += <span class="hljs-number">2</span>

<span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> even_numbers():
    print(i)
</code></pre>
<p>In this example, the even_numbers function uses a while loop to generate even numbers starting from 0 and incrementing by 2 until the value of n is 10. Instead of returning the value of n, the yield keyword is used to return the current value of n and suspend the execution of the function until the next value is requested. The for loop then iterates over the values produced by the generator and prints them to the console.</p>
<p>Generators can be used in many different scenarios, such as generating large amounts of data that would be too memory-intensive to generate all at once, or generating data on-the-fly in response to user input.</p>
]]></content:encoded></item><item><title><![CDATA[Asynchronous Operations (Coroutine) in Python]]></title><description><![CDATA[Asynchronous operations are operations that run independently of the main program flow and don't block the execution of the program. In other words, asynchronous operations allow the program to continue executing other tasks while it waits for the op...]]></description><link>https://devendraadhikari.com.np/asynchronous-operations-coroutine-in-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/asynchronous-operations-coroutine-in-python</guid><category><![CDATA[Python]]></category><category><![CDATA[coroutines]]></category><category><![CDATA[async/await]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Thu, 02 Feb 2023 16:37:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675355624167/a7985357-fbba-417f-9996-55dd91c8706d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Asynchronous operations are operations that run independently of the main program flow and don't block the execution of the program. In other words, asynchronous operations allow the program to continue executing other tasks while it waits for the operation to complete.</p>
<p>In Python, asynchronous operations can be performed using coroutines, which are functions marked with the "async" keyword. Coroutines allow you to write asynchronous code that is more readable and maintainable than using threads or callbacks.</p>
<p>Here's an example to help illustrate how asynchronous operations work:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">fetch_data</span>():</span>
    <span class="hljs-comment"># Perform an asynchronous operation (e.g. fetch data from a network or database)</span>
    <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">2</span>)  <span class="hljs-comment"># Wait for 2 seconds</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">"Data fetched"</span>

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-comment"># Start the asynchronous operation</span>
    result = <span class="hljs-keyword">await</span> fetch_data()
    print(result)

asyncio.run(main())
</code></pre>
<h3 id="heading-what-is-coroutine">What is coroutine?</h3>
<p>A coroutine is a special type of function in Python that is used to handle asynchronous operations. Unlike normal functions, coroutines can be suspended and resumed multiple times, allowing other parts of the code to run while they are waiting for an operation to complete.</p>
<p>Coroutines are defined using the "async" keyword before the function definition. They can contain one or more "await" expressions, which pause the execution of the coroutine until the result of an asynchronous operation is returned.</p>
<p>Coroutines are similar to threads, but they are more lightweight and efficient, as they only consume resources when they are actually running. Additionally, coroutines can be used to handle large numbers of parallel operations without the overhead of creating a separate thread for each one.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> asyncio

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_coroutine</span>(<span class="hljs-params">x,whichone</span>):</span>
    print(<span class="hljs-string">"Running coroutine..."</span>,whichone)
    <span class="hljs-keyword">await</span> asyncio.sleep(x)
    print(<span class="hljs-string">"Coroutine complete."</span>,whichone)

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">main</span>():</span>
    <span class="hljs-keyword">await</span> asyncio.gather(my_coroutine(<span class="hljs-number">1</span>,<span class="hljs-number">1</span>), my_coroutine(<span class="hljs-number">2</span>,<span class="hljs-number">2</span>), my_coroutine(<span class="hljs-number">3</span>,<span class="hljs-number">3</span>))
    print(<span class="hljs-string">'all complete.'</span>)

asyncio.run(main())
</code></pre>
<p>In this example, the "my_coroutine" function is a coroutine that runs for a specified amount of time and then prints a message indicating that it is complete. The "main" function uses the "asyncio.gather" function to run multiple coroutines in parallel, and the "<a target="_blank" href="http://asyncio.run">asyncio.run</a>" function is used to run the "main" function and wait for it to complete.</p>
]]></content:encoded></item><item><title><![CDATA[Factory Pattern (Python)]]></title><description><![CDATA[What is Factory Pattern?
The factory design pattern is a creational pattern that provides a way to create objects without specifying the exact class of the object that will be created. This is useful when the process of creating an object is complex ...]]></description><link>https://devendraadhikari.com.np/factory-pattern-python</link><guid isPermaLink="true">https://devendraadhikari.com.np/factory-pattern-python</guid><category><![CDATA[Python]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Factory Design Pattern]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Wed, 01 Feb 2023 13:34:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675339051978/2b20ed47-4c87-4885-821f-7a3735a46bc2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>What is Factory Pattern?</p>
<p>The factory design pattern is a creational pattern that provides a way to create objects without specifying the exact class of the object that will be created. This is useful when the process of creating an object is complex or you want to abstract the object creation process from the rest of the application.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name</span>):</span>
        self._name = name

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">speak</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Woof!"</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, name</span>):</span>
        self._name = name

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">speak</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"Meow!"</span>

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_pet</span>(<span class="hljs-params">pet=<span class="hljs-string">"dog"</span></span>):</span>
    pets = dict(dog=Dog(<span class="hljs-string">"Hope"</span>), cat=Cat(<span class="hljs-string">"Peace"</span>))
    <span class="hljs-keyword">return</span> pets[pet]

d = get_pet(<span class="hljs-string">"dog"</span>)
print(d.speak())

c = get_pet(<span class="hljs-string">"cat"</span>)
print(c.speak())
</code></pre>
<p>In this example, we have two classes <code>Dog</code> and <code>Cat</code> each with their own <code>speak</code> method. The <code>get_pet</code> function acts as a factory that takes a string <code>pet</code> as a parameter and returns an instance of either the <code>Dog</code> or <code>Cat</code> class, depending on the value of the <code>pet</code> parameter. The factory function uses a dictionary <code>pets</code> to map the string values to the respective classes.  </p>
<p>By using the factory pattern, the rest of the application does not need to know about the specific classes that are being created, it only needs to know about the <code>get_pet</code> function and the <code>speak</code> method, which provides a clean and abstract interface for creating objects.  </p>
<p><strong>More Realistically</strong>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> abc <span class="hljs-keyword">import</span> ABC, abstractmethod

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseConnection</span>(<span class="hljs-params">ABC</span>):</span>
<span class="hljs-meta">    @abstractmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MySQLConnection</span>(<span class="hljs-params">DatabaseConnection</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"MySQL connection established."</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostgreSQLConnection</span>(<span class="hljs-params">DatabaseConnection</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">connect</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">return</span> <span class="hljs-string">"PostgreSQL connection established."</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseConnectionFactory</span>:</span>
<span class="hljs-meta">    @staticmethod</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">create_connection</span>(<span class="hljs-params">db_type: str</span>) -&gt; DatabaseConnection:</span>
        <span class="hljs-keyword">if</span> db_type == <span class="hljs-string">"mysql"</span>:
            <span class="hljs-keyword">return</span> MySQLConnection()
        <span class="hljs-keyword">elif</span> db_type == <span class="hljs-string">"postgresql"</span>:
            <span class="hljs-keyword">return</span> PostgreSQLConnection()
        <span class="hljs-keyword">else</span>:
            <span class="hljs-keyword">raise</span> ValueError(<span class="hljs-string">f"Unknown database type: <span class="hljs-subst">{db_type}</span>"</span>)

<span class="hljs-comment"># Usage</span>
factory = DatabaseConnectionFactory()
connection = factory.create_connection(<span class="hljs-string">"mysql"</span>)
print(connection.connect())  <span class="hljs-comment"># Output: MySQL connection established.</span>
</code></pre>
<p>In short, using the Factory Pattern in the example provides the following key benefits:</p>
<ol>
<li><p><strong>Encapsulation</strong>: Centralizes and simplifies object creation logic, making it easier to manage and change without affecting client code.</p>
</li>
<li><p><strong>Loose Coupling</strong>: Decouples client code from specific classes, allowing it to work with abstract interfaces and promoting flexibility.</p>
</li>
<li><p><strong>Single Responsibility</strong>: Keeps object creation responsibility within the factory, while connection classes focus solely on their behavior.</p>
</li>
<li><p><strong>Extensibility</strong>: Easily add new types of database connections without modifying existing client code.</p>
</li>
<li><p><strong>Runtime Flexibility</strong>: Allows dynamic selection of connection types at runtime based on input or configuration.</p>
</li>
<li><p><strong>Improved Maintenance</strong>: Standardizes object creation, making the codebase more readable and easier to maintain.</p>
</li>
<li><p><strong>Testing Ease</strong>: Facilitates testing by allowing controlled creation of objects, aiding in mocking and stubbing.  </p>
<p> DONE :D</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Design Pattern Python: Creational (Singelton) Pattern]]></title><description><![CDATA[What is Creational Design Pattern?
It is a unique way of object creation, making it easier for developers to create objects in a flexible and maintainable way, without tightly coupling their code to the object creation logic.
Singelton Design Pattern...]]></description><link>https://devendraadhikari.com.np/design-pattern-python-creational-singelton-pattern</link><guid isPermaLink="true">https://devendraadhikari.com.np/design-pattern-python-creational-singelton-pattern</guid><category><![CDATA[Python]]></category><category><![CDATA[design patterns]]></category><category><![CDATA[Singleton Design Pattern]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Wed, 01 Feb 2023 06:01:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1675231078818/b20fd89d-b4f7-409a-bfa3-256848ec6873.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><strong>What is Creational Design Pattern?</strong></p>
<p>It is a unique way of object creation, making it easier for developers to create objects in a flexible and maintainable way, without tightly coupling their code to the object creation logic.</p>
<p><strong>Singelton Design Pattern</strong></p>
<p>Singleton is a creational design pattern that lets you ensure that a class has only one instance while providing a global access point to this instance. This pattern is used to provide a single point of control or to ensure that a class only has one instance throughout the lifetime of a program.</p>
<p><strong><em>A singleton class has the following properties:</em></strong></p>
<ul>
<li><p>It has a private constructor, which prevents other classes from creating instances of the singleton class.</p>
</li>
<li><p>It has a private static instance variable, which stores the single instance of the class.</p>
</li>
<li><p>It has a public static method (often called "getInstance()") that returns the single instance of the class, creating it if necessary.</p>
</li>
</ul>
<p><strong>Example</strong></p>
<pre><code class="lang-python">            <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Singleton</span>:</span>
                __instance = <span class="hljs-literal">None</span>

<span class="hljs-meta">                @staticmethod</span>
                <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">getInstance</span>():</span>
                    <span class="hljs-keyword">if</span> Singleton.__instance <span class="hljs-keyword">is</span> <span class="hljs-literal">None</span>:
                        Singleton()
                    <span class="hljs-keyword">return</span> Singleton.__instance

                <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self</span>):</span>
                    <span class="hljs-keyword">if</span> Singleton.__instance <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span>:
                        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"You cannot create multiple instances of a singleton class."</span>)
                    <span class="hljs-keyword">else</span>:
                        Singleton.__instance = self
</code></pre>
<p>To use the singleton class, clients simply call the getInstance() method, which returns the single instance of the class. The first time the method is called, the instance of the class is created. Subsequent calls to the method return the same instance. This ensures that there is only one instance of the singleton class throughout the lifetime of the program.</p>
]]></content:encoded></item><item><title><![CDATA[Amplify commands at one place]]></title><description><![CDATA[Configuration

When you have to configure amplify project first time
*amplify configure*

Initialize existing project
 *amplify init*

Amplify CLI commands




Pull latest backend backend environment to local
 *amplify pull*

Push local update to clo...]]></description><link>https://devendraadhikari.com.np/amplify-commands-at-one-place</link><guid isPermaLink="true">https://devendraadhikari.com.np/amplify-commands-at-one-place</guid><category><![CDATA[cli commands]]></category><category><![CDATA[AWS Amplify]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Deven ]]></dc:creator><pubDate>Thu, 10 Nov 2022 09:54:17 GMT</pubDate><content:encoded><![CDATA[<p>Configuration</p>
<ol>
<li><p>When you have to configure amplify project first time</p>
<pre><code>*amplify configure*
</code></pre></li>
<li><p>Initialize existing project</p>
<pre><code> *amplify init*
</code></pre></li>
<li><p>Amplify CLI commands</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668073447472/IzAOQ0O87.png" alt="Screenshot from 2022-11-10 15-28-32.png" /></p>
<ol>
<li><p>Pull latest backend backend environment to local</p>
<pre><code> *amplify pull*
</code></pre></li>
<li><p>Push local update to cloud server</p>
<pre><code> *amplify push*
</code></pre></li>
<li><p>See local changes</p>
<pre><code> *amplify status*
</code></pre></li>
</ol>
<p>These are the basic command commonly user in amplify project. Since, this is my first blog post, I keep this much. I will start contributing more from now.</p>
]]></content:encoded></item></channel></rss>