<?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[Python is Love ❤️]]></title><description><![CDATA[Your hub for Python and Django insights! Connect, learn, and share on our user-friendly blogging platform. Dive into the world of coding now!]]></description><link>https://arjun.name.np</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1746887186188/f9e22393-4764-4f66-8c5f-3b447a7ef055.png</url><title>Python is Love ❤️</title><link>https://arjun.name.np</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 11 Apr 2026 04:19:55 GMT</lastBuildDate><atom:link href="https://arjun.name.np/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Supercharge Your Python Apps with Rust]]></title><description><![CDATA[Welcome to our latest exploration, where we dive into the thrilling world of combining the raw power of Rust with the versatility of Python to elevate your programming projects to unprecedented levels of efficiency and performance. In "Supercharge Yo...]]></description><link>https://arjun.name.np/supercharge-your-python-apps-with-rust</link><guid isPermaLink="true">https://arjun.name.np/supercharge-your-python-apps-with-rust</guid><category><![CDATA[Python]]></category><category><![CDATA[Rust]]></category><category><![CDATA[FFI]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Tue, 06 Feb 2024 16:04:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1707235430532/0b1f4008-ee70-4138-a27b-d115f7ea4ced.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to our latest exploration, where we dive into the thrilling world of combining the raw power of Rust with the versatility of Python to elevate your programming projects to unprecedented levels of efficiency and performance. In "Supercharge Your Python Apps with Rust," we embark on a journey designed to transform beginners into adept users of these two formidable languages.</p>
<p>Whether you're looking to boost your Python application's speed, ensure memory safety, or simply be curious about integrating Rust into your workflow, this blog is your first step towards mastering the art of leveraging Rust's capabilities within your Python projects. Dive in now to discover a step-by-step guide that demystifies the process, making it accessible and straightforward for developers of all skill levels. Don't miss out on unlocking the full potential of your applications; join us in this exciting adventure!</p>
<p>Creating a dynamic library in Rust and calling it from Python using Foreign Function Interface (FFI) is an exciting way to leverage Rust's performance and safety in Python applications. This tutorial will guide you through the process step-by-step, with clear examples and explanations tailored for developers.</p>
<h3 id="heading-creating-a-rust-dynamic-library"><strong>Creating a Rust Dynamic Library</strong></h3>
<h4 id="heading-step-1-setting-up-your-rust-project"><strong>Step 1: Setting Up Your Rust Project</strong></h4>
<p>First, you'll need to create a new Rust library project. Open a terminal and run the following command:</p>
<pre><code class="lang-sh">cargo new --lib rust_library
<span class="hljs-built_in">cd</span> rust_library
</code></pre>
<p>This command creates a new Rust library project called <code>rust_library</code> and moves it into the project directory.</p>
<h4 id="heading-step-2-writing-your-rust-function"><strong>Step 2: Writing Your Rust Function</strong></h4>
<p>Open the <code>src/</code><a target="_blank" href="http://lib.rs"><code>lib.rs</code></a> file and replace its contents with the following code, which defines a simple function to add two numbers:</p>
<pre><code class="lang-rust"><span class="hljs-meta">#[no_mangle]</span>
<span class="hljs-keyword">pub</span> <span class="hljs-keyword">extern</span> <span class="hljs-string">"C"</span> <span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">add_numbers</span></span>(a: <span class="hljs-built_in">i32</span>, b: <span class="hljs-built_in">i32</span>) -&gt; <span class="hljs-built_in">i32</span> {
    a + b
}
</code></pre>
<ul>
<li><p><code>#[no_mangle]</code> prevents Rust from changing the name of the function during compilation, making it easier to link from Python.</p>
</li>
<li><p><code>pub extern "C"</code> makes this function adhere to the C calling convention, a requirement for FFI.</p>
</li>
</ul>
<h4 id="heading-step-3-configuring-cargotoml"><strong>Step 3: Configuring Cargo.toml</strong></h4>
<p>Open the <code>Cargo.toml</code> file and add the following lines to create a dynamic library:</p>
<pre><code class="lang-toml"><span class="hljs-section">[lib]</span>
<span class="hljs-attr">crate-type</span> = [<span class="hljs-string">"cdylib"</span>]
</code></pre>
<p>This configuration tells Rust to compile the library as a C-compatible dynamic library (<code>cdylib</code>).</p>
<h4 id="heading-step-4-building-the-dynamic-library"><strong>Step 4: Building the Dynamic Library</strong></h4>
<p>Run the following command in your terminal:</p>
<pre><code class="lang-sh">cargo build --release
</code></pre>
<p>After the build completes, you'll find the dynamic library in <code>target/release</code> (e.g., <code>librust_</code><a target="_blank" href="http://library.so"><code>library.so</code></a> on Linux, <code>rust_library.dll</code> on Windows, or <code>librust_library.dylib</code> on macOS).</p>
<h3 id="heading-calling-rust-from-python"><strong>Calling Rust from Python</strong></h3>
<h4 id="heading-step-1-installing-ctypes-in-python"><strong>Step 1: Installing ctypes in Python</strong></h4>
<p>Ensure you have <code>ctypes</code> available in your Python environment. It's included in the standard library, so you should be all set.</p>
<h4 id="heading-step-2-writing-python-code-to-call-rust-function"><strong>Step 2: Writing Python Code to Call Rust Function</strong></h4>
<p>Create a new Python file (e.g., <code>call_</code><a target="_blank" href="http://rust.py"><code>rust.py</code></a>) and write the following code:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> ctypes <span class="hljs-keyword">import</span> cdll, c_int

<span class="hljs-comment"># Load the shared library. Adjust the path as necessary.</span>
lib = cdll.LoadLibrary(<span class="hljs-string">"target/release/librust_library.so"</span>)

<span class="hljs-comment"># Set the argument and return types</span>
lib.add_numbers.argtypes = (c_int, c_int)
lib.add_numbers.restype = c_int

<span class="hljs-comment"># Call the Rust function</span>
result = lib.add_numbers(<span class="hljs-number">5</span>, <span class="hljs-number">7</span>)
print(<span class="hljs-string">f"The result is: <span class="hljs-subst">{result}</span>"</span>)
</code></pre>
<ul>
<li><p>Adjust the path to <code>LoadLibrary</code> based on your dynamic library's location and name.</p>
</li>
<li><p><code>argtypes</code> and <code>restype</code> ensure Python correctly converts types between Python and Rust.</p>
</li>
</ul>
<h4 id="heading-step-3-running-your-python-code"><strong>Step 3: Running Your Python Code</strong></h4>
<p>Run your Python script:</p>
<pre><code class="lang-sh">python call_rust.py
</code></pre>
<p>You should see the output:</p>
<pre><code class="lang-xml">The result is: 12
</code></pre>
<h3 id="heading-conclusion"><strong>Conclusion</strong></h3>
<p>You've now successfully created a Rust dynamic library and called it from Python using FFI! This approach enables you to combine Rust's performance and reliability with Python's ease of use, creating powerful and efficient applications.</p>
<p>This tutorial serves as a basic introduction to FFI and inter-language communication. As you dive deeper, you'll encounter more complex scenarios, such as passing strings or complex data structures between Rust and Python. Each step has been designed to be as developer-friendly as possible, providing you with a solid foundation for integrating Rust and Python in your projects.</p>
<hr />
<p>The examples for the above tutorial is referenced from : <a target="_blank" href="https://github.com/theArjun/learning-rust/tree/main/rust_adder">https://github.com/theArjun/learning-rust/tree/main/rust_adder</a></p>
]]></content:encoded></item><item><title><![CDATA[Comparative Analysis of Dataclasses, attrs, and Pydantic]]></title><description><![CDATA[In the Python programming language, several libraries provide convenient ways to define and work with data structures. Three popular choices for creating classes that primarily store data are dataclasses, attrs, and pydantic. This report aims to comp...]]></description><link>https://arjun.name.np/comparative-analysis-of-dataclasses-attrs-and-pydantic</link><guid isPermaLink="true">https://arjun.name.np/comparative-analysis-of-dataclasses-attrs-and-pydantic</guid><category><![CDATA[Python]]></category><category><![CDATA[json]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Mon, 22 Jan 2024 11:49:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705924096815/3c844d5c-e43f-4c53-8671-d5cc98d14c8f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the Python programming language, several libraries provide convenient ways to define and work with data structures. Three popular choices for creating classes that primarily store data are <code>dataclasses</code>, <code>attrs</code>, and <code>pydantic</code>. This report aims to compare these libraries based on various aspects such as syntax, features, performance, and use cases.</p>
<h3 id="heading-1-dataclasses">1. Dataclasses</h3>
<h4 id="heading-syntax">Syntax:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass

<span class="hljs-meta">@dataclass</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    x: float
    y: float
    z: float = <span class="hljs-number">0.0</span>
</code></pre>
<h4 id="heading-key-features">Key Features:</h4>
<ul>
<li><p>Concise syntax with the <code>@dataclass</code> decorator.</p>
</li>
<li><p>Automatically generates special methods (e.g., <code>__init__</code>, <code>__repr__</code>) based on class attributes.</p>
</li>
<li><p>Default values for attributes can be specified.</p>
</li>
</ul>
<h4 id="heading-use-cases">Use Cases:</h4>
<ul>
<li>Simple data structures where automatic methods generation is sufficient.</li>
</ul>
<h3 id="heading-2-attrs">2. attrs</h3>
<h4 id="heading-syntax-1">Syntax:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> attr

<span class="hljs-meta">@attr.s</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>:</span>
    x = attr.ib()
    y = attr.ib()
    z = attr.ib(default=<span class="hljs-number">0.0</span>)
</code></pre>
<h4 id="heading-key-features-1">Key Features:</h4>
<ul>
<li><p>Decorator <code>@attr.s</code> is used to define a class with attributes.</p>
</li>
<li><p>Explicit attribute definition using <code>attr.ib()</code> with optional default values.</p>
</li>
<li><p>Powerful features like validation, converters, and metadata.</p>
</li>
</ul>
<h4 id="heading-use-cases-1">Use Cases:</h4>
<ul>
<li><p>Fine-grained control over attribute behavior.</p>
</li>
<li><p>Rich attribute features like validation and metadata.</p>
</li>
</ul>
<h3 id="heading-3-pydantic">3. Pydantic</h3>
<h4 id="heading-syntax-2">Syntax:</h4>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> pydantic <span class="hljs-keyword">import</span> BaseModel

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span>(<span class="hljs-params">BaseModel</span>):</span>
    x: float
    y: float
    z: float = <span class="hljs-number">0.0</span>
</code></pre>
<h4 id="heading-key-features-2">Key Features:</h4>
<ul>
<li><p>Inherited from <code>BaseModel</code>.</p>
</li>
<li><p>Automatic validation based on type annotations.</p>
</li>
<li><p>Supports parsing and serialization of data from/to various formats (e.g., JSON).</p>
</li>
</ul>
<h4 id="heading-use-cases-2">Use Cases:</h4>
<ul>
<li><p>Data validation and parsing in applications involving input from external sources.</p>
</li>
<li><p>API request/response handling where automatic parsing and validation are essential.</p>
</li>
</ul>
<h2 id="heading-comparison">Comparison</h2>
<h3 id="heading-1-syntax-and-ease-of-use">1. Syntax and Ease of Use</h3>
<ul>
<li><p><strong>Dataclasses:</strong> Simple and concise syntax with the <code>@dataclass</code> decorator.</p>
</li>
<li><p><strong>attrs:</strong> Explicit attribute definition using <code>attr.ib()</code>, providing fine-grained control.</p>
</li>
<li><p><strong>Pydantic:</strong> Concise syntax with automatic validation based on type annotations.</p>
</li>
</ul>
<h3 id="heading-2-features">2. Features</h3>
<ul>
<li><p><strong>Dataclasses:</strong> Automatic generation of special methods; default values can be specified.</p>
</li>
<li><p><strong>attrs:</strong> Rich set of features, including validation, converters, and metadata.</p>
</li>
<li><p><strong>Pydantic:</strong> Automatic validation, parsing, and serialization; supports JSON schema generation.</p>
</li>
</ul>
<h3 id="heading-3-performance">3. Performance</h3>
<ul>
<li><p><strong>Dataclasses:</strong> Generally lightweight and performs well.</p>
</li>
<li><p><strong>attrs:</strong> Slightly heavier due to additional features, but still performs well.</p>
</li>
<li><p><strong>Pydantic:</strong> May have higher overhead due to additional functionality; suitable for scenarios where validation and parsing are crucial.</p>
</li>
</ul>
<h3 id="heading-4-use-cases">4. Use Cases</h3>
<ul>
<li><p><strong>Dataclasses:</strong> Simple data structures where automatic methods generation suffices.</p>
</li>
<li><p><strong>attrs:</strong> Situations requiring fine-grained control over attribute behavior and additional features.</p>
</li>
<li><p><strong>Pydantic:</strong> Data validation, parsing, and serialization in scenarios involving external data sources, APIs, or configuration files.</p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Choosing between <code>dataclasses</code>, <code>attrs</code>, and <code>pydantic</code> depends on the specific needs of the project. For basic data structures, <code>dataclasses</code> provide a lightweight and easy-to-use solution. <code>attrs</code> is a good choice when fine-grained control over attributes and additional features are required. On the other hand, <code>pydantic</code> is well-suited for scenarios involving data validation, parsing, and serialization, especially in applications dealing with external data sources or APIs. Ultimately, the choice depends on the trade-offs between simplicity, features, and performance based on the project requirements.</p>
]]></content:encoded></item><item><title><![CDATA[Real-Time Apache Log Streaming with FastAPI]]></title><description><![CDATA[Here, we're going to stream Apache logs by leveraging FastAPI, a high-performance Python framework. FastAPI is known for its speed and ease of use, making it a great choice for building APIs and handling real-time data streams. Let's get started on h...]]></description><link>https://arjun.name.np/real-time-apache-log-streaming-with-fastapi</link><guid isPermaLink="true">https://arjun.name.np/real-time-apache-log-streaming-with-fastapi</guid><category><![CDATA[FastAPI]]></category><category><![CDATA[Python]]></category><category><![CDATA[apache]]></category><category><![CDATA[streaming]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Sat, 20 Jan 2024 17:25:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705771507790/47a80390-8f8f-4893-9de1-df22c17697ed.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here, we're going to stream Apache logs by leveraging FastAPI, a high-performance Python framework. FastAPI is known for its speed and ease of use, making it a great choice for building APIs and handling real-time data streams. Let's get started on how to set this up!</p>
<h3 id="heading-setting-up-your-environment">Setting Up Your Environment</h3>
<p>Before we begin, ensure you have Python installed. FastAPI runs on Python 3.6+.</p>
<ol>
<li><p><strong>Create a Virtual Environment (Optional but Recommended):</strong> This keeps your project dependencies separate from your global Python installation.</p>
<pre><code class="lang-bash"> python -m venv venv
 <span class="hljs-built_in">source</span> venv/bin/activate  <span class="hljs-comment"># On Windows use `venv\Scripts\activate`</span>
</code></pre>
</li>
<li><p><strong>Install FastAPI and Uvicorn:</strong> Uvicorn is an ASGI server that will run our FastAPI application.</p>
<pre><code class="lang-bash"> pip install fastapi uvicorn
</code></pre>
</li>
<li><p><strong>Install Additional Dependencies:</strong> We'll use <code>aiofiles</code> for asynchronous file handling.</p>
<pre><code class="lang-bash"> pip install aiofiles
</code></pre>
</li>
</ol>
<h3 id="heading-building-the-fastapi-backend">Building the FastAPI Backend</h3>
<h4 id="heading-the-fastapi-app">The FastAPI App</h4>
<p>We will create a file named<a target="_blank" href="http://main.py"><code>main.py</code></a> and write the FastAPI application code such that it sends new content from the Apache logs when it's added. We also need to implement a way to watch the file for changes and send those changes over the WebSocket. This can be achieved using file polling or more sophisticated file monitoring techniques. However, keep in mind that Python doesn't have built-in, cross-platform support for real-time file monitoring, so we'll use a simple polling approach for this example.</p>
<h3 id="heading-fastapi-backend-with-file-polling">FastAPI Backend with File Polling</h3>
<p>Here's how you can adjust the <a target="_blank" href="http://main.py"><code>main.py</code></a> to include file polling:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> fastapi <span class="hljs-keyword">import</span> FastAPI, WebSocket
<span class="hljs-keyword">from</span> fastapi.responses <span class="hljs-keyword">import</span> HTMLResponse
<span class="hljs-keyword">import</span> aiofiles
<span class="hljs-keyword">import</span> asyncio
<span class="hljs-keyword">import</span> os

app = FastAPI()

html = <span class="hljs-string">"""
&lt;!DOCTYPE html&gt;
&lt;html&gt;
    &lt;head&gt;
        &lt;title&gt;Apache Logs Stream&lt;/title&gt;
    &lt;/head&gt;
    &lt;body&gt;
        &lt;h1&gt;Apache Access Log&lt;/h1&gt;
        &lt;pre id="accessLog"&gt;&lt;/pre&gt;
        &lt;script src="/static/app.js"&gt;&lt;/script&gt;
    &lt;/body&gt;
&lt;/html&gt;
"""</span>

<span class="hljs-meta">@app.get("/")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get</span>():</span>
    <span class="hljs-keyword">return</span> HTMLResponse(html)

<span class="hljs-meta">@app.websocket("/ws")</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">websocket_endpoint</span>(<span class="hljs-params">websocket: WebSocket</span>):</span>
    <span class="hljs-keyword">await</span> websocket.accept()
    file_path = <span class="hljs-string">'/path/to/apache.access.log'</span>
    last_size = <span class="hljs-number">0</span>

    <span class="hljs-keyword">while</span> <span class="hljs-literal">True</span>:
        <span class="hljs-keyword">await</span> asyncio.sleep(<span class="hljs-number">1</span>)  <span class="hljs-comment"># Poll every second</span>
        current_size = os.path.getsize(file_path)
        <span class="hljs-keyword">if</span> current_size &gt; last_size:
            <span class="hljs-keyword">async</span> <span class="hljs-keyword">with</span> aiofiles.open(file_path, mode=<span class="hljs-string">'r'</span>) <span class="hljs-keyword">as</span> f:
                <span class="hljs-keyword">await</span> f.seek(last_size)
                <span class="hljs-keyword">while</span> new_line := <span class="hljs-keyword">await</span> f.readline():
                    <span class="hljs-comment"># If new line is just a blank line, new line char or empty string, skip it</span>
                    <span class="hljs-keyword">if</span> new_line <span class="hljs-keyword">in</span> [<span class="hljs-string">"\n"</span>, <span class="hljs-string">"\r\n"</span>, <span class="hljs-string">""</span>]:
                        <span class="hljs-keyword">continue</span>
                    <span class="hljs-keyword">await</span> websocket.send_text(new_line)
            last_size = current_size
</code></pre>
<p>In this code:</p>
<ol>
<li><p>The WebSocket connection is established.</p>
</li>
<li><p>It enters an infinite loop where it checks the file size every second.</p>
</li>
<li><p>If the file size has increased (indicating new content), it reads the new lines and sends them over the WebSocket.</p>
</li>
</ol>
<p>Remember to replace <code>/path/to/apache.access.log</code> with the actual path to your Apache access log file.</p>
<h3 id="heading-running-the-application">Running the Application</h3>
<p>Run your FastAPI server as before:</p>
<pre><code class="lang-bash">uvicorn main:app --reload
</code></pre>
<p>Now, when you add new lines to your Apache log file, those lines will be sent to the connected web client in real-time.</p>
<h3 id="heading-important-considerations">Important Considerations</h3>
<ul>
<li><p><strong>Polling vs. Event-Driven Monitoring:</strong> This example uses polling, which is less efficient than event-driven monitoring. For a production environment, you might want to explore libraries like <code>watchdog</code> for Python, which can provide more efficient file monitoring.</p>
</li>
<li><p><strong>Error Handling:</strong> In a production environment, add error handling to deal with issues like lost WebSocket connections or file read errors.</p>
</li>
<li><p><strong>Security and Performance:</strong> Be cautious about security implications and the performance impact of constantly reading large log files, especially in a busy production environment.Replace <code>/path/to/apache.access.log</code> with the path to your Apache log file.</p>
</li>
</ul>
<h4 id="heading-the-frontend-javascript">The Frontend JavaScript</h4>
<p>In a folder named <code>static</code>, create <code>app.js</code> with the following content:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> ws = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">'ws://localhost:8000/ws'</span>);
ws.onmessage = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'accessLog'</span>).textContent += event.data + <span class="hljs-string">'\n'</span>;
};
</code></pre>
<h3 id="heading-key-takeaways">Key Takeaways</h3>
<ul>
<li><p><strong>Asynchronous Streaming:</strong> FastAPI and aiofiles make it easy to handle real-time data streaming asynchronously.</p>
</li>
<li><p><strong>Security:</strong> Remember to implement authentication and secure your WebSocket connections, especially in a production environment.</p>
</li>
<li><p><strong>Performance:</strong> FastAPI is known for its high performance, making it an excellent choice for real-time data streaming applications.</p>
</li>
</ul>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Using FastAPI for streaming Apache logs to a web interface is a powerful approach. It's not only efficient but also provides a modern Pythonic way of handling real-time data. This setup can be customized to fit a variety of monitoring and streaming needs.</p>
<p>Happy coding and real-time monitoring with FastAPI! 🐍💨</p>
]]></content:encoded></item><item><title><![CDATA[Testing Date Functions in Python: A Tale of Mocks and Realities]]></title><description><![CDATA[Greetings, Python enthusiasts and curious coders! Today, I'm excited to share with you a tale from my coding adventures – specifically, the intriguing challenge of testing a function that returns today's date in Python. It's a journey filled with pra...]]></description><link>https://arjun.name.np/testing-date-functions-in-python-a-tale-of-mocks-and-realities</link><guid isPermaLink="true">https://arjun.name.np/testing-date-functions-in-python-a-tale-of-mocks-and-realities</guid><category><![CDATA[Python]]></category><category><![CDATA[Testing]]></category><category><![CDATA[date]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Sat, 20 Jan 2024 16:07:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705766801525/08701e6c-a4e9-4c31-85ea-0585fbc2b97b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Greetings, Python enthusiasts and curious coders! Today, I'm excited to share with you a tale from my coding adventures – specifically, the intriguing challenge of testing a function that returns today's date in Python. It's a journey filled with practical solutions, a touch of magic (mocking magic, to be precise), and some important lessons. So, grab a cup of your favorite beverage, and let's dive in!</p>
<h2 id="heading-the-quest-begins-the-simple-yet-tricky-date-function">The Quest Begins: The Simple Yet Tricky Date Function</h2>
<p>Let's set the stage with our star player, a simple function named <code>get_today_date</code>. Its mission is straightforward – to fetch and return the current date. Here's how it looks in Python:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_today_date</span>():</span>
    <span class="hljs-keyword">return</span> datetime.now().date()
</code></pre>
<p>It's a simple piece of code, but as we'll see, even the simplest code can lead to complex testing scenarios.</p>
<h2 id="heading-the-twist-testing-a-moving-target">The Twist: Testing a Moving Target</h2>
<p>Testing static functions is a breeze, but testing a function that returns a dynamic value like the current date? That's where the real challenge lies. We need our tests to be consistent, regardless of the actual date. This is where I introduce a clever trick up my Python sleeve – <code>unittest.mock</code>.</p>
<h2 id="heading-the-magic-trick-mocking-the-date">The Magic Trick: Mocking the Date</h2>
<p>Using the <code>unittest</code> framework, along with <code>unittest.mock</code>, I conjure a controlled environment where <a target="_blank" href="http://datetime.now"><code>datetime.now</code></a><code>()</code> is under our spell, always returning a fixed, predictable date.</p>
<p>Here's a test case for our <code>get_today_date</code> function:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> unittest
<span class="hljs-keyword">from</span> unittest.mock <span class="hljs-keyword">import</span> patch
<span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> datetime
<span class="hljs-keyword">from</span> my_module <span class="hljs-keyword">import</span> get_today_date  <span class="hljs-comment"># Replace 'my_module' with your actual module name</span>

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TestGetTodayDate</span>(<span class="hljs-params">unittest.TestCase</span>):</span>
<span class="hljs-meta">    @patch('my_module.datetime')  # Again, replace 'my_module' with your actual module name</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_get_today_date</span>(<span class="hljs-params">self, mock_datetime</span>):</span>
        mock_date = datetime(<span class="hljs-number">2024</span>, <span class="hljs-number">1</span>, <span class="hljs-number">19</span>)
        mock_datetime.now.return_value = mock_date

        result = get_today_date()

        self.assertEqual(result, mock_date.date())

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    unittest.main()
</code></pre>
<p>This test ensures our function is behaving as expected, but as with any magic, there are caveats.</p>
<h2 id="heading-the-caveats-unveiling-the-shortcomings">The Caveats: Unveiling the Shortcomings</h2>
<h3 id="heading-1-over-reliance-on-mocking">1. <strong>Over-Reliance on Mocking</strong></h3>
<p>By using <code>unittest.mock</code>, we're testing in an artificial bubble. It's perfect for consistency but can potentially hide issues in handling real-world date scenarios.</p>
<h3 id="heading-2-ignoring-real-world-scenarios">2. <strong>Ignoring Real-World Scenarios</strong></h3>
<p>The test blissfully skips over the ever-changing nature of real dates. It doesn't account for complexities like time zones or daylight saving time.</p>
<h3 id="heading-3-maintenance-overhead">3. <strong>Maintenance Overhead</strong></h3>
<p>Setting up these mocks across multiple tests can be cumbersome, adding extra maintenance and complexity.</p>
<h3 id="heading-4-risk-of-false-positives">4. <strong>Risk of False Positives</strong></h3>
<p>Just because the test passes with the mocked date doesn't guarantee the absence of bugs in date handling.</p>
<h3 id="heading-5-framework-limitations">5. <strong>Framework Limitations</strong></h3>
<p>This approach is tailored for <code>unittest</code>. Switching frameworks could mean a significant overhaul of our testing strategy.</p>
<h2 id="heading-the-conclusion-a-mixed-bag-of-tricks">The Conclusion: A Mixed Bag of Tricks</h2>
<p>Despite these challenges, the mocking strategy is a valuable tool in our Python testing arsenal, especially for functions dealing with dates. However, it's crucial to complement this approach with additional testing strategies to ensure robustness and real-world applicability.</p>
<p>So there you have it – a glimpse into the intricate dance of testing date functions in Python. It's a blend of precision, foresight, and a bit of magic, all wrapped up in the pursuit of reliable, bug-resistant code. Keep experimenting, keep learning, and most importantly, keep enjoying the journey of coding! 🎩✨🐍💻📅</p>
]]></content:encoded></item><item><title><![CDATA[Maintenance mode in Django]]></title><description><![CDATA[To force a maintenance mode in Django, we need to redirect all traffic to a maintenance page, except for requests from specific IPs (like our own for management purposes). This can be achieved using middleware. Here's a basic approach:

Create a main...]]></description><link>https://arjun.name.np/maintenance-mode-in-django</link><guid isPermaLink="true">https://arjun.name.np/maintenance-mode-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[maintain]]></category><category><![CDATA[maintainability]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Mon, 15 Jan 2024 13:50:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705326715681/2f486325-9659-4651-a6f9-d925ebf8ac7f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>To force a maintenance mode in Django, we need to redirect all traffic to a maintenance page, except for requests from specific IPs (like our own for management purposes). This can be achieved using middleware. Here's a basic approach:</p>
<ol>
<li><p><strong>Create a maintenance middleware:</strong></p>
<ul>
<li>This middleware will intercept requests and redirect them to a maintenance page if a maintenance mode is active.</li>
</ul>
</li>
<li><p><strong>Add a Maintenance View and Template:</strong></p>
<ul>
<li>Create a simple view and template for the maintenance page that users will see.</li>
</ul>
</li>
<li><p><strong>Configure the middleware:</strong></p>
<ul>
<li>Add the middleware to your Django project settings.</li>
</ul>
</li>
<li><p><strong>Activate/Deactivate Maintenance Mode:</strong></p>
<ul>
<li>We can activate maintenance mode by changing a variable, a file existence, or a database flag.</li>
</ul>
</li>
</ol>
<p>Here's a simple example to illustrate these steps:</p>
<h3 id="heading-step-1-create-a-maintenance-middleware">Step 1: Create a Maintenance Middleware</h3>
<p>We will create a file named<code>maintainence_middleware.py</code> in one of your apps:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse
<span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> redirect

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MaintenanceMiddleware</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"># Check if maintenance mode is active</span>
        <span class="hljs-comment"># This can be a setting in settings.py, a database flag, or checking for a file</span>
        <span class="hljs-keyword">if</span> hasattr(settings, <span class="hljs-string">'MAINTENANCE_MODE'</span>) <span class="hljs-keyword">and</span> settings.MAINTENANCE_MODE:
            <span class="hljs-comment"># Allow access to certain IPs</span>
            allowed_ips = [<span class="hljs-string">'123.456.78.90'</span>,]  <span class="hljs-comment"># Your IP here</span>
            <span class="hljs-keyword">if</span> request.META.get(<span class="hljs-string">'REMOTE_ADDR'</span>) <span class="hljs-keyword">in</span> allowed_ips:
                <span class="hljs-keyword">return</span> self.get_response(request)
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> redirect(<span class="hljs-string">'maintenance_page'</span>)
        <span class="hljs-keyword">return</span> self.get_response(request)
</code></pre>
<h3 id="heading-step-2-add-a-maintenance-view-and-template">Step 2: Add a Maintenance View and Template</h3>
<p>In our <a target="_blank" href="http://views.py"><code>views.py</code></a>:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">maintenance_page</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'maintenance.html'</span>)
</code></pre>
<p>Create a <code>maintenance.html</code> template in your templates directory with the appropriate HTML content.</p>
<h3 id="heading-step-3-configure-the-middleware">Step 3: Configure the Middleware</h3>
<p>In your <a target="_blank" href="http://settings.py"><code>settings.py</code></a>, add the middleware to <code>MIDDLEWARE</code>:</p>
<pre><code class="lang-python">MIDDLEWARE = [
    <span class="hljs-comment"># ...</span>
    <span class="hljs-string">'yourapp.maintenance_middleware.MaintenanceMiddleware'</span>,
    <span class="hljs-comment"># ...</span>
]
</code></pre>
<h3 id="heading-step-4-activatedeactivate-maintenance-mode">Step 4: Activate/Deactivate Maintenance Mode</h3>
<p>In your <a target="_blank" href="http://settings.py"><code>settings.py</code></a>:</p>
<pre><code class="lang-python"><span class="hljs-comment"># Set this to True to activate maintenance mode</span>
MAINTENANCE_MODE = <span class="hljs-literal">False</span>
</code></pre>
<h3 id="heading-step-5-you-might-want-to">Step 5: You might want to:</h3>
<ul>
<li><p><strong>Custom Maintenance Page</strong>: Customize the <code>maintenance.html</code> to inform our users about the maintenance and possibly provide an estimated time for when the service will be back.</p>
</li>
<li><p><strong>Dynamic Activation</strong>: Instead of manually changing the <a target="_blank" href="http://settings.py"><code>settings.py</code></a>, we could use an environment variable or a database setting that we can modify without deploying new code.</p>
</li>
<li><p><strong>Logging Access Attempts</strong>: We might want to log attempts to access the site during maintenance for security and analysis.</p>
</li>
<li><p><strong>Testing</strong>: Ensure we test this thoroughly in a staging environment before deploying it to production, especially the IP whitelisting part.</p>
</li>
<li><p><strong>Notify Users in Advance</strong>: If possible, notify our users in advance about the planned maintenance.</p>
</li>
</ul>
<p>By following these steps, you can implement a maintenance mode in your Django application that can be easily activated or deactivated as needed.</p>
<h2 id="heading-step-6-testing-maintainence-middleware">Step 6: Testing Maintainence Middleware</h2>
<ol>
<li><p><strong>Set up the test environment:</strong> This involves creating a test class that inherits from <code>TestCase</code> and setting up any necessary configurations.</p>
</li>
<li><p><strong>Test the middleware's behavior:</strong> You should test for both when maintenance mode is active and when it is not. Additionally, testing for access from allowed IPs and disallowed IPs is important.</p>
</li>
</ol>
<p>Here's an example of how you might write these test cases:</p>
<h3 id="heading-1-set-up-the-test-environment">1. Set Up the Test Environment</h3>
<p>First, create a test file in your Django app's <code>tests</code> directory, e.g., <code>test_</code><a target="_blank" href="http://middleware.py"><code>middleware.py</code></a>.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.test <span class="hljs-keyword">import</span> TestCase, RequestFactory
<span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> yourapp.views <span class="hljs-keyword">import</span> maintenance_page
<span class="hljs-keyword">from</span> yourapp.maintenance_middleware <span class="hljs-keyword">import</span> MaintenanceMiddleware

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MaintenanceMiddlewareTest</span>(<span class="hljs-params">TestCase</span>):</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setUp</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># The RequestFactory instance is a way to create request instances for use in testing.</span>
        self.factory = RequestFactory()
        self.middleware = MaintenanceMiddleware(<span class="hljs-keyword">lambda</span> x: x)
</code></pre>
<h3 id="heading-2-test-the-middlewares-behavior">2. Test the Middleware's Behavior</h3>
<h4 id="heading-test-when-maintenance-mode-is-active">Test When Maintenance Mode is Active</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_maintenance_mode_active</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-comment"># Set maintenance mode to active</span>
    settings.MAINTENANCE_MODE = <span class="hljs-literal">True</span>

    <span class="hljs-comment"># Create a request instance</span>
    request = self.factory.get(<span class="hljs-string">'/any-page'</span>)
    request.META[<span class="hljs-string">'REMOTE_ADDR'</span>] = <span class="hljs-string">'111.222.33.44'</span>  <span class="hljs-comment"># Non-allowed IP</span>

    <span class="hljs-comment"># Process the request through the middleware</span>
    response = self.middleware(request)

    <span class="hljs-comment"># Check that the response is a redirect to the maintenance page</span>
    self.assertEqual(response.status_code, <span class="hljs-number">302</span>)
    self.assertEqual(response.url, <span class="hljs-string">'/maintenance-page'</span>)  <span class="hljs-comment"># URL of your maintenance page</span>
</code></pre>
<h4 id="heading-test-when-maintenance-mode-is-inactive">Test When Maintenance Mode is Inactive</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_maintenance_mode_inactive</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-comment"># Set maintenance mode to inactive</span>
    settings.MAINTENANCE_MODE = <span class="hljs-literal">False</span>

    <span class="hljs-comment"># Create a request instance</span>
    request = self.factory.get(<span class="hljs-string">'/any-page'</span>)

    <span class="hljs-comment"># Process the request through the middleware</span>
    response = self.middleware(request)

    <span class="hljs-comment"># Check that the request passes through the middleware unaffected</span>
    self.assertEqual(response.status_code, <span class="hljs-number">200</span>)
</code></pre>
<h4 id="heading-test-access-from-allowed-ips">Test Access from Allowed IPs</h4>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_access_from_allowed_ip</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-comment"># Set maintenance mode to active</span>
    settings.MAINTENANCE_MODE = <span class="hljs-literal">True</span>

    <span class="hljs-comment"># Create a request instance with an allowed IP</span>
    request = self.factory.get(<span class="hljs-string">'/any-page'</span>)
    request.META[<span class="hljs-string">'REMOTE_ADDR'</span>] = <span class="hljs-string">'123.456.78.90'</span>  <span class="hljs-comment"># Allowed IP</span>

    <span class="hljs-comment"># Process the request through the middleware</span>
    response = self.middleware(request)

    <span class="hljs-comment"># Check that the request passes through the middleware unaffected</span>
    self.assertEqual(response.status_code, <span class="hljs-number">200</span>)
</code></pre>
<h3 id="heading-additional-notes">Additional Notes:</h3>
<ul>
<li><p>Make sure to replace <code>'yourapp'</code> with the actual name of your Django app.</p>
</li>
<li><p>Modify the <code>'/maintenance-page'</code> with the actual URL of your maintenance page.</p>
</li>
<li><p>These tests assume that the normal response (when not in maintenance mode) has a status code of 200. Adjust according to your actual app's behavior.</p>
</li>
<li><p>Remember to reset any settings (like <code>MAINTENANCE_MODE</code>) after the test to avoid side effects on other tests.</p>
</li>
</ul>
<p>By covering these scenarios, your test case will effectively validate the behavior of your maintenance middleware under different conditions.</p>
]]></content:encoded></item><item><title><![CDATA[Middlewares in Django]]></title><description><![CDATA[Middleware in Django refers to a framework of hooks into Django’s request/response processing. It's a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for performing some specif...]]></description><link>https://arjun.name.np/middlewares-in-django</link><guid isPermaLink="true">https://arjun.name.np/middlewares-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[Middleware]]></category><category><![CDATA[logging]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Sun, 14 Jan 2024 09:15:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705224241161/ac8985e6-8dc2-4198-9d51-5c0a3019111a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Middleware in Django refers to a framework of hooks into Django’s request/response processing. It's a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for performing some specific function. For example, Django includes middleware to manage sessions, handle authentication, manage cross-site request forgery protection, and much more.</p>
<h3 id="heading-how-middleware-works">How Middleware Works:</h3>
<ol>
<li><p><strong>Layered Structure</strong>: Middleware in Django is like a series of layers or wrappers around the view. When a request comes in, it goes through each middleware in order before finally reaching the view. After the view has processed the request, the response travels back through the middleware stack to the user.</p>
</li>
<li><p><strong>Request and Response Processing</strong>: Middleware can be used for preprocessing requests before they reach the view and for post-processing responses before they are returned to the client.</p>
</li>
<li><p><strong>Global Effect</strong>: Unlike decorators, which are applied to individual views, middleware applies to all requests and responses, making them useful for tasks that need to be handled globally.</p>
</li>
</ol>
<h3 id="heading-common-uses-of-middleware">Common Uses of Middleware:</h3>
<ul>
<li><p><strong>Session Management</strong>: Handles the sending and receiving of cookies, which are used to manage sessions.</p>
</li>
<li><p><strong>Authentication</strong>: Associates users with requests using sessions.</p>
</li>
<li><p><strong>Cross-Site Request Forgery Protection</strong>: Provides a security mechanism to ensure that forms are submitted from authenticated users and from the website itself.</p>
</li>
<li><p><strong>Caching</strong>: Manages caching, which can store views or parts of views to improve performance.</p>
</li>
<li><p><strong>Localization</strong>: Detects user’s language and timezone preferences and adjusts content accordingly.</p>
</li>
</ul>
<h3 id="heading-writing-custom-middleware">Writing Custom Middleware:</h3>
<p>Creating custom middleware in Django involves defining a class with specific methods that Django recognizes:</p>
<ul>
<li><p><code>__init__(self, get_response)</code>: Constructor method called once when the web server starts.</p>
</li>
<li><p><code>__call__(self, request)</code>: Called on each request, before Django calls any view.</p>
</li>
<li><p><code>process_view(self, request, view_func, view_args, view_kwargs)</code>: Called just before Django calls the view.</p>
</li>
<li><p><code>process_exception(self, request, exception)</code>: Called if an exception is raised by</p>
</li>
</ul>
<p>the view.</p>
<ul>
<li><code>process_template_response(self, request, response)</code>: Called if the response instance has a <code>render()</code> method, indicating it's a <code>TemplateResponse</code> or equivalent.</li>
</ul>
<p><strong>Example of a simple custom middleware:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyCustomMiddleware</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"># Code executed on each request before the view is called</span>
        response = self.get_response(request)
        <span class="hljs-comment"># Code executed on each request after the view is called</span>
        <span class="hljs-keyword">return</span> response
</code></pre>
<p>To use this middleware, you would add it to the <code>MIDDLEWARE</code> setting in your Django settings file.</p>
<h3 id="heading-middleware-and-djangos-design-philosophy">Middleware and Django’s Design Philosophy:</h3>
<p>Middleware in Django aligns with its design philosophy of being explicit, reusable, and pluggable. It allows developers to cleanly and efficiently modify the input or output of an application without cluttering the business logic in views or models. This makes the application easier to maintain and extend.</p>
<h3 id="heading-creating-custom-middlewares">Creating Custom Middlewares</h3>
<p>Creating detailed code for each custom middleware, along with its pros and cons and particular use cases, would be quite extensive. However, I can provide a high-level overview of a few examples, covering the basic implementation, pros and cons, and use cases for each.</p>
<h3 id="heading-1-request-and-response-logging-middleware">1. Request and Response Logging Middleware</h3>
<p>Create a middleware that logs the details of each request and response. This can include the request path, method, duration of the request, status code of the response, and IP address of the client. This is useful for debugging and monitoring the health of your application.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> time
<span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LoggingMiddleware</span>(<span class="hljs-params">MiddlewareMixin</span>):</span>
    <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>
        request.start_time = time.time()

    <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>
        duration = time.time() - request.start_time
        print(<span class="hljs-string">f'Request to <span class="hljs-subst">{request.path}</span> took <span class="hljs-subst">{duration}</span> seconds'</span>)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Easy to implement and integrate.</p>
</li>
<li><p>It helps in monitoring and debugging.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Increases log size.</p>
</li>
<li><p>It might slow down request handling if logging is extensive.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Debugging performance issues.</p>
</li>
<li><p>Monitoring API usage and response times.</p>
</li>
</ul>
<h3 id="heading-2-api-throttlinglimiting-middleware">2. API Throttling/Limiting Middleware</h3>
<p>Implement rate limiting to restrict the number of requests a user can make to your API within a given timeframe. This helps to prevent abuse and ensures that your API remains responsive under high load.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse
<span class="hljs-keyword">from</span> django.core.cache <span class="hljs-keyword">import</span> cache

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">RateLimitMiddleware</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>
        ip = request.META.get(<span class="hljs-string">'REMOTE_ADDR'</span>)
        <span class="hljs-keyword">if</span> cache.get(ip):
            <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'error'</span>: <span class="hljs-string">'rate limit exceeded'</span>}, status=<span class="hljs-number">429</span>)
        <span class="hljs-keyword">else</span>:
            cache.set(ip, <span class="hljs-string">'exists'</span>, timeout=<span class="hljs-number">60</span>)  <span class="hljs-comment"># 1 request per minute</span>
            response = self.get_response(request)
            <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Prevents abuse of the API.</p>
</li>
<li><p>Helps in managing server load.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Might block legitimate users if not configured properly.</p>
</li>
<li><p>Additional overhead for maintaining the rate-limiting logic.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Public APIs where rate limiting is essential.</p>
</li>
<li><p>Preventing DoS attacks.</p>
</li>
</ul>
<h3 id="heading-3-maintenance-mode-middleware">3. Maintenance Mode Middleware</h3>
<p>Develop middleware that enables a “maintenance mode” for your website. When this mode is active, the middleware can return a predefined maintenance response for all HTTP requests, except those from authenticated admins or from certain IP addresses.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponse
<span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MaintenanceModeMiddleware</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-keyword">if</span> settings.MAINTENANCE_MODE:
            <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"Site under maintenance"</span>, status=<span class="hljs-number">503</span>)
        response = self.get_response(request)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>It is easy to switch the entire site to maintenance mode.</p>
</li>
<li><p>A customizable response for maintenance.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Might accidentally block access to the site if not managed correctly.</p>
</li>
<li><p>Requires additional settings and configurations.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Scheduled downtime for updates or maintenance.</p>
</li>
<li><p>Emergency response to critical issues.</p>
</li>
</ul>
<h3 id="heading-4-ssltls-redirection-middleware">4. SSL/TLS Redirection Middleware</h3>
<p>Ensure security by automatically redirecting HTTP requests to HTTPS, helping to keep user data secure during transit.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponsePermanentRedirect

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SSLRedirectMiddleware</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-keyword">if</span> <span class="hljs-keyword">not</span> request.is_secure():
            <span class="hljs-keyword">return</span> HttpResponsePermanentRedirect(<span class="hljs-string">f'https://<span class="hljs-subst">{request.get_host()}</span><span class="hljs-subst">{request.get_full_path()}</span>'</span>)
        response = self.get_response(request)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Ensures secure data transmission.</p>
</li>
<li><p>It is easy to enforce HTTPS across the site.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Can lead to redirect loops if not configured correctly.</p>
</li>
<li><p>Requires SSL/TLS certificate installation.</p>
</li>
</ul>
<p><strong>Use Cases</strong>:</p>
<ul>
<li><p>Websites that handle sensitive data (e-commerce, online banking).</p>
</li>
<li><p>General enhancement of website security.</p>
</li>
</ul>
<h3 id="heading-5-cors-middleware-for-specific-routes">5. CORS Middleware for Specific Routes</h3>
<p>While Django provides built-in support for managing Cross-Origin Resource Sharing (CORS), you might want a middleware that applies custom CORS policies to certain routes or APIs in your application.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CORSMiddleware</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)
        <span class="hljs-keyword">if</span> request.path.startswith(<span class="hljs-string">'/api/'</span>):  <span class="hljs-comment"># Apply CORS only to API routes</span>
            response[<span class="hljs-string">"Access-Control-Allow-Origin"</span>] = <span class="hljs-string">"*"</span>
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Allows control over cross-origin requests for specific routes.</p>
</li>
<li><p>Enhances security by limiting CORS only where necessary.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Potential security risk if misconfigured.</p>
</li>
<li><p>You might need to handle preflight requests separately.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Public APIs are meant to be accessed from different domains.</p>
</li>
<li><p>Single-page applications (SPAs) that need to interact with APIs hosted on different domains.</p>
</li>
</ul>
<h3 id="heading-6-profile-middleware-for-performance-monitoring">6. Profile Middleware for Performance Monitoring</h3>
<p>A middleware that measures the execution time of views and other parts of your request/response cycle. This can be invaluable for identifying performance bottlenecks.</p>
<p><strong>Code Overview:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> time

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ProfileMiddleware</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>
        start_time = time.time()
        response = self.get_response(request)
        end_time = time.time()
        print(<span class="hljs-string">f"Request to <span class="hljs-subst">{request.path}</span> took <span class="hljs-subst">{end_time - start_time}</span> seconds"</span>)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Helps in identifying slow parts of the application.</p>
</li>
<li><p>Easy to integrate and remove as needed.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Adds extra processing time to each request.</p>
</li>
<li><p>Not a detailed profiling tool; more suitable for high-level monitoring.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Identifying performance bottlenecks.</p>
</li>
<li><p>Monitoring response times during load testing.</p>
</li>
</ul>
<h3 id="heading-7-user-agent-restriction-middleware">7. User-Agent Restriction Middleware</h3>
<p>Create middleware that blocks or allows requests based on the user-agent string. This can be used to prevent certain web crawlers from accessing your site or to provide different responses for mobile and desktop users.</p>
<p><strong>Detailed Code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> HttpResponseForbidden

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UserAgentRestrictionMiddleware</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>
        user_agent = request.META.get(<span class="hljs-string">'HTTP_USER_AGENT'</span>, <span class="hljs-string">''</span>)
        <span class="hljs-keyword">if</span> <span class="hljs-string">'DisallowedUserAgent'</span> <span class="hljs-keyword">in</span> user_agent:
            <span class="hljs-keyword">return</span> HttpResponseForbidden(<span class="hljs-string">"Access Denied"</span>)
        response = self.get_response(request)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Control access based on user-agent.</p>
</li>
<li><p>Block unwanted crawlers or bots.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>User agents can be spoofed.</p>
</li>
<li><p>Might accidentally block legitimate users.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Blocking scraping bots.</p>
</li>
<li><p>Providing different content for mobile and desktop users.</p>
</li>
</ul>
<h3 id="heading-8-localization-and-timezone-middleware">8. Localization and Timezone Middleware</h3>
<p>Enhance the user experience by automatically determining the user’s preferred language and timezone based on their browser settings or location. Use this information to localize content and display times in the user’s local time zone.</p>
<p><strong>Detailed Code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.utils <span class="hljs-keyword">import</span> timezone
<span class="hljs-keyword">from</span> django.utils.translation <span class="hljs-keyword">import</span> activate

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LocalizationMiddleware</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"># Set language</span>
        user_language = request.META.get(<span class="hljs-string">'HTTP_ACCEPT_LANGUAGE'</span>)
        activate(user_language)

        <span class="hljs-comment"># Set timezone</span>
        user_timezone = request.COOKIES.get(<span class="hljs-string">'timezone'</span>)
        <span class="hljs-keyword">if</span> user_timezone:
            timezone.activate(user_timezone)
        <span class="hljs-keyword">else</span>:
            timezone.deactivate()

        response = self.get_response(request)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Enhances the user experience with language and timezone personalization.</p>
</li>
<li><p>Improves the usability of global applications.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Requires additional logic for timezone detection.</p>
</li>
<li><p>Potential overhead in detecting and setting preferences.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Multi-language websites.</p>
</li>
<li><p>Applications requiring content based on the user's locale.</p>
</li>
</ul>
<h3 id="heading-9-content-compression-middleware">9. Content Compression Middleware</h3>
<p>Implement middleware to compress the response data before sending it to the client. This can help reduce bandwidth usage and improve load times, especially for users with slower internet connections.</p>
<p><strong>Detailed Code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> gzip
<span class="hljs-keyword">from</span> io <span class="hljs-keyword">import</span> BytesIO

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">GZipMiddleware</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)

        <span class="hljs-keyword">if</span> <span class="hljs-string">'gzip'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> request.META.get(<span class="hljs-string">'HTTP_ACCEPT_ENCODING'</span>, <span class="hljs-string">''</span>):
            <span class="hljs-keyword">return</span> response

        <span class="hljs-keyword">if</span> response.status_code != <span class="hljs-number">200</span> <span class="hljs-keyword">or</span> len(response.content) &lt; <span class="hljs-number">200</span>:
            <span class="hljs-keyword">return</span> response

        buffer = BytesIO()
        gzip_file = gzip.GzipFile(mode=<span class="hljs-string">'wb'</span>, fileobj=buffer)
        gzip_file.write(response.content)
        gzip_file.close()

        response.content = buffer.getvalue()
        response[<span class="hljs-string">'Content-Encoding'</span>] = <span class="hljs-string">'gzip'</span>
        response[<span class="hljs-string">'Content-Length'</span>] = str(len(response.content))

        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Reduces the size of the response, saving bandwidth.</p>
</li>
<li><p>Improves loading times for clients with slow connections.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Adds processing overhead on the server.</p>
</li>
<li><p>Not all clients may support gzip encoding.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Websites with high traffic and large response sizes.</p>
</li>
<li><p>Improving performance for users with slower internet connections.</p>
</li>
</ul>
<h3 id="heading-10-ab-testing-middleware">10. A/B Testing Middleware</h3>
<p>Develop middleware for conducting A/B tests. You can use this to present different versions of your site to different users and gather data on how each version performs.</p>
<p><strong>Detailed Code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> random
<span class="hljs-keyword">from</span> django.utils.deprecation <span class="hljs-keyword">import</span> MiddlewareMixin

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ABTestingMiddleware</span>(<span class="hljs-params">MiddlewareMixin</span>):</span>
    <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"># Assign a random version for A/B testing</span>
        <span class="hljs-keyword">if</span> <span class="hljs-string">'ABTestVersion'</span> <span class="hljs-keyword">not</span> <span class="hljs-keyword">in</span> request.session:
            request.session[<span class="hljs-string">'ABTestVersion'</span>] = random.choice([<span class="hljs-string">'A'</span>, <span class="hljs-string">'B'</span>])

        request.ab_test_version = request.session[<span class="hljs-string">'ABTestVersion'</span>]

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">process_template_response</span>(<span class="hljs-params">self, request, response</span>):</span>
        <span class="hljs-keyword">if</span> hasattr(request, <span class="hljs-string">'ab_test_version'</span>):
            response.context_data[<span class="hljs-string">'ABTestVersion'</span>] = request.ab_test_version
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Simple implementation of A/B testing.</p>
</li>
<li><p>Ability to test different versions of your site simultaneously.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>May require additional logic for complex testing scenarios.</p>
</li>
<li><p>Tracking and analysis of results need to be handled separately.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Testing new features or design changes.</p>
</li>
<li><p>Optimizing the user experience and conversion rates.</p>
</li>
</ul>
<h3 id="heading-11-authentication-and-authorization-middleware">11. Authentication and Authorization Middleware</h3>
<p>Create middleware to handle custom authentication and authorization beyond Django's built-in systems. For example, implementing token-based authentication or integrating with OAuth providers.</p>
<p><strong>Detailed Code:</strong></p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> django.http <span class="hljs-keyword">import</span> JsonResponse
<span class="hljs-keyword">from</span> django.contrib.auth <span class="hljs-keyword">import</span> authenticate

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TokenAuthMiddleware</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>
        token = request.META.get(<span class="hljs-string">'HTTP_AUTHORIZATION'</span>)
        <span class="hljs-keyword">if</span> token:
            user = authenticate(request, token=token)
            <span class="hljs-keyword">if</span> user:
                request.user = user
            <span class="hljs-keyword">else</span>:
                <span class="hljs-keyword">return</span> JsonResponse({<span class="hljs-string">'error'</span>: <span class="hljs-string">'Invalid token'</span>}, status=<span class="hljs-number">401</span>)
        response = self.get_response(request)
        <span class="hljs-keyword">return</span> response
</code></pre>
<p><strong>Pros:</strong></p>
<ul>
<li><p>Customizable authentication process.</p>
</li>
<li><p>Flexibility to integrate with different token systems.</p>
</li>
</ul>
<p><strong>Cons:</strong></p>
<ul>
<li><p>Increased complexity in managing authentication.</p>
</li>
<li><p>Responsibility to ensure the security of the custom implementation.</p>
</li>
</ul>
<p><strong>Use Cases:</strong></p>
<ul>
<li><p>Integrating third-party authentication systems.</p>
</li>
<li><p>Implementing token-based authentication for APIs.</p>
</li>
</ul>
<p>Each middleware serves a distinct purpose and can significantly enhance the functionality of a Django application. The choice of middleware should be based on the specific requirements of the project and balanced against potential drawbacks, such as performance overhead or complexity.</p>
]]></content:encoded></item><item><title><![CDATA[Profiling and Optimizing Django Applications]]></title><description><![CDATA[In the world of web development, performance is key. A lagging or slow website can significantly impact user experience, leading to dissatisfaction and loss of traffic. In Django applications, performance issues often arise from inefficient code or u...]]></description><link>https://arjun.name.np/profiling-and-optimizing-django-applications</link><guid isPermaLink="true">https://arjun.name.np/profiling-and-optimizing-django-applications</guid><category><![CDATA[Django]]></category><category><![CDATA[optimization]]></category><category><![CDATA[profiling]]></category><category><![CDATA[celery]]></category><category><![CDATA[cache]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Sun, 14 Jan 2024 08:48:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705222069681/4c260e7d-9741-486b-928f-83d0228c1964.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the world of web development, performance is key. A lagging or slow website can significantly impact user experience, leading to dissatisfaction and loss of traffic. In Django applications, performance issues often arise from inefficient code or unoptimized queries. However, with the right tools and techniques, these problems can be identified and rectified. This blog post will guide you through profiling and detecting lagging code in Django and introduce the concept of asynchronous task queues to boost your application’s performance.</p>
<h2 id="heading-understanding-profiling-in-django">Understanding Profiling in Django</h2>
<p>Profiling is the process of measuring the various aspects of program performance, such as memory usage and execution time, to identify bottlenecks. In Django, several tools can be used for profiling.</p>
<h3 id="heading-tools-for-profiling">Tools for Profiling:</h3>
<ul>
<li><p><strong>Django Debug Toolbar</strong>: This is a configurable set of panels that display various debug information about the current request/response.</p>
<pre><code class="lang-python">  <span class="hljs-comment"># Installation</span>
  pip install django-debug-toolbar

  <span class="hljs-comment"># settings.py</span>
  INSTALLED_APPS = [
      <span class="hljs-comment"># ...</span>
      <span class="hljs-string">'debug_toolbar'</span>,
  ]
  MIDDLEWARE = [
      <span class="hljs-comment"># ...</span>
      <span class="hljs-string">'debug_toolbar.middleware.DebugToolbarMiddleware'</span>,
  ]
</code></pre>
</li>
<li><p><strong>cProfile Module</strong>: A built-in Python module that can profile any Python program.</p>
<pre><code class="lang-python">  <span class="hljs-keyword">import</span> cProfile
  cProfile.run(<span class="hljs-string">'your_function()'</span>)
</code></pre>
</li>
</ul>
<h3 id="heading-steps-for-profiling">Steps for Profiling:</h3>
<ol>
<li><p><strong>Identify Slow Areas</strong>: Use Django Debug Toolbar to get an overview of request times, SQL queries, and more.</p>
</li>
<li><p><strong>Detailed Profiling</strong>: For a detailed analysis, use cProfile to profile specific functions or code blocks.</p>
</li>
<li><p><strong>Analyze the Output</strong>: Look for functions or queries that take the most time or are called excessively.</p>
</li>
</ol>
<h2 id="heading-detecting-and-optimizing-lagging-code">Detecting and Optimizing Lagging Code</h2>
<p>Once you've profiled your application, the next step is to optimize the lagging parts.</p>
<h3 id="heading-common-issues-and-solutions">Common Issues and Solutions:</h3>
<ul>
<li><p><strong>Inefficient Database Queries</strong>: Use Django’s <code>select_related</code> and <code>prefetch_related</code> to optimize SQL queries.</p>
<pre><code class="lang-python">  <span class="hljs-comment"># Optimizing ForeignKey relationships</span>
  queryset = MyModel.objects.select_related(<span class="hljs-string">'foreign_key_field'</span>)
  <span class="hljs-comment"># Optimizing ManyToMany fields</span>
  queryset = MyModel.objects.prefetch_related(<span class="hljs-string">'many_to_many_field'</span>)
</code></pre>
</li>
<li><p><strong>Reducing Query Counts</strong>: Aim to reduce the number of queries per request. Cache frequently used data.</p>
<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">my_view</span>(<span class="hljs-params">request</span>):</span>
      data = cache.get(<span class="hljs-string">'my_data'</span>)
      <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> data:
          data = MyModel.objects.get_expensive_query()
          cache.set(<span class="hljs-string">'my_data'</span>, data, timeout=<span class="hljs-number">300</span>)  <span class="hljs-comment"># Cache for 5 minutes</span>
      <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'my_template.html'</span>, {<span class="hljs-string">'data'</span>: data})
</code></pre>
</li>
<li><p><strong>Optimizing Templates</strong>: Reduce template complexity, use template fragment caching.</p>
<pre><code class="lang-xml">  {% load cache %}
  {% cache 500 cache_fragment_name %}
   ... expensive calculations ... 
  {% endcache %}
</code></pre>
</li>
</ul>
<h3 id="heading-profiling-python-code">Profiling Python Code</h3>
<p>Using the cProfile module, you can get a detailed report of function calls and execution times. This helps in identifying bottlenecks in your Python code.</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> cProfile
<span class="hljs-keyword">import</span> io
<span class="hljs-keyword">import</span> pstats

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">profile_your_function</span>():</span>
  <span class="hljs-comment"># Your function code here</span>

<span class="hljs-comment"># Create a Profile object and run your function</span>
profiler = cProfile.Profile()
profiler.enable()
profile_your_function()
profiler.disable()

<span class="hljs-comment"># Generate profiling report</span>
s = io.StringIO()
ps = pstats.Stats(profiler, stream=s).sort_stats(<span class="hljs-string">'cumulative'</span>)
ps.print_stats()
print(s.getvalue())
</code></pre>
<h2 id="heading-introducing-asynchronous-task-queues">Introducing Asynchronous Task Queues</h2>
<p>For tasks that are time-consuming or can be processed in the background, asynchronous task queues are a lifesaver. They help in offloading such tasks from the main thread, improving the responsiveness of your application.</p>
<h3 id="heading-celery-a-robust-task-queue">Celery: A Robust Task Queue</h3>
<p>Celery is a powerful, production-ready asynchronous job queue, which allows you to run time-consuming Python functions in the background.</p>
<h4 id="heading-setting-up-celery-with-django">Setting Up Celery with Django:</h4>
<ol>
<li><p><strong>Install Celery</strong>:</p>
<pre><code class="lang-bash"> pip install celery
</code></pre>
</li>
<li><p><strong>Configure Celery in your Django project</strong>:</p>
<p> Create a new file <a target="_blank" href="http://celery.py"><code>celery.py</code></a> in your Django project’s main directory.</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> __future__ <span class="hljs-keyword">import</span> absolute_import, unicode_literals
 <span class="hljs-keyword">import</span> os
 <span class="hljs-keyword">from</span> celery <span class="hljs-keyword">import</span> Celery

 <span class="hljs-comment"># Set the default Django settings module for the 'celery' program.</span>
 os.environ.setdefault(<span class="hljs-string">'DJANGO_SETTINGS_MODULE'</span>, <span class="hljs-string">'your_project.settings'</span>)

 app = Celery(<span class="hljs-string">'your_project'</span>)

 <span class="hljs-comment"># Using a string here means the worker doesn't have to serialize</span>
 <span class="hljs-comment"># the configuration object to child processes.</span>
 app.config_from_object(<span class="hljs-string">'django.conf:settings'</span>, namespace=<span class="hljs-string">'CELERY'</span>)

 <span class="hljs-comment"># Load task modules from all registered Django app configs.</span>
 app.autodiscover_tasks()

<span class="hljs-meta"> @app.task(bind=True)</span>
 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">debug_task</span>(<span class="hljs-params">self</span>):</span>
     print(<span class="hljs-string">f'Request: <span class="hljs-subst">{self.request!r}</span>'</span>)
</code></pre>
</li>
<li><p><strong>Create a Task</strong>:</p>
<p> In your Django app, create a <a target="_blank" href="http://tasks.py"><code>tasks.py</code></a> file and define your asynchronous tasks.</p>
<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>
</li>
<li><p><strong>Run Celery Worker</strong>:</p>
<p> Run the Celery worker process to listen for incoming task requests.</p>
<pre><code class="lang-bash"> celery -A your_project worker --loglevel=info
</code></pre>
</li>
</ol>
<h3 id="heading-using-celery-in-views">Using Celery in Views:</h3>
<p>Call your asynchronous task from Django views or models. The task will be executed in the background by Celery workers.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> .tasks <span class="hljs-keyword">import</span> add

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">some_view</span>(<span class="hljs-params">request</span>):</span>
    <span class="hljs-comment"># Call an asynchronous task</span>
    add.delay(<span class="hljs-number">4</span>, <span class="hljs-number">4</span>)
    <span class="hljs-keyword">return</span> HttpResponse(<span class="hljs-string">"Task is running in the background"</span>)
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Performance optimization in Django is a continuous process. By profiling your application regularly, optimizing the lagging parts, and using asynchronous task queues like Celery, you can significantly improve your Django application's performance. Remember, a fast and efficient application not only provides a better user experience but also contributes to higher scalability and maintainability.</p>
]]></content:encoded></item><item><title><![CDATA[Django ORM - Optimization Techniques]]></title><description><![CDATA[Optimizing Django's ORM (Object-Relational Mapping) is essential for building efficient, scalable web applications. The ORM is a powerful tool for abstracting database operations, but it can lead to performance issues if not used carefully. In this c...]]></description><link>https://arjun.name.np/django-orm-optimization-techniques</link><guid isPermaLink="true">https://arjun.name.np/django-orm-optimization-techniques</guid><category><![CDATA[Django]]></category><category><![CDATA[orm]]></category><category><![CDATA[optimization]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Sun, 14 Jan 2024 08:10:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705219740075/d168343b-98c7-4ba6-8895-139e06b3b7d5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Optimizing Django's ORM (Object-Relational Mapping) is essential for building efficient, scalable web applications. The ORM is a powerful tool for abstracting database operations, but it can lead to performance issues if not used carefully. In this comprehensive guide, we'll explore strategies to optimize Django's ORM, focusing on query efficiency, data retrieval, and best practices in model design.</p>
<h3 id="heading-understanding-django-orm">Understanding Django ORM</h3>
<p>Django's ORM allows developers to interact with the database using Python objects, abstracting the underlying SQL. However, this abstraction can lead to inefficient queries if not managed properly.</p>
<h4 id="heading-1-query-efficiency">1. <strong>Query Efficiency</strong></h4>
<ul>
<li><p><strong>Select Related and Prefetch Related</strong>: One common issue in Django ORM is the "N+1" query problem, which occurs when a loop executes a new query for each iteration. To mitigate this, use <code>select_related</code> for foreign key and one-to-one relationships, and <code>prefetch_related</code> for many-to-many and reverse foreign key relationships.</p>
</li>
<li><p><strong>Only and Defer</strong>: If you only need a subset of fields from the database, <code>only()</code> can be used to load specific fields, reducing the amount of data transferred. Conversely, <code>defer()</code> delays loading of specific fields until they are accessed.</p>
</li>
<li><p><strong>Aggregates and Annotations</strong>: Aggregation functions like <code>Sum</code>, <code>Count</code>, etc., can be used to perform calculations at the database level. Annotations allow for complex queries, like conditional aggregates, without pulling excessive data into Python.</p>
</li>
<li><p><strong>F() Expressions</strong>: Use F() expressions to perform database-side operations, reducing Python's processing load.</p>
</li>
</ul>
<h4 id="heading-2-indexing-and-database-design">2. <strong>Indexing and Database Design</strong></h4>
<ul>
<li><p><strong>Appropriate Indexing</strong>: Indexes are crucial for query optimization. Identify frequently queried fields, especially in <code>WHERE</code>, <code>ORDER BY</code>, and <code>JOIN</code> clauses, and index them accordingly.</p>
</li>
<li><p><strong>Database Normalization</strong>: While normalization reduces data redundancy, over-normalization can lead to excessive joins. Conversely, denormalization can improve read performance at the cost of write performance and data integrity. Strike a balance based on your application's read-write patterns.</p>
</li>
</ul>
<h4 id="heading-3-efficient-data-retrieval">3. <strong>Efficient Data Retrieval</strong></h4>
<ul>
<li><p><strong>Paginate Results</strong>: For views that display large datasets, implement pagination to limit the number of records retrieved per request.</p>
</li>
<li><p><strong>Caching</strong>: Implement caching strategies for data that doesn't change often. This can be done at various levels - per-view, per-query, or even using low-level cache frameworks.</p>
</li>
</ul>
<h4 id="heading-4-understanding-query-execution">4. <strong>Understanding Query Execution</strong></h4>
<ul>
<li><p><strong>Query Evaluation</strong>: Django's querysets are lazy, meaning they are not executed until evaluated. Understanding when a queryset is evaluated can help prevent unnecessary database hits.</p>
</li>
<li><p><strong>Use of</strong> <code>exists()</code>: If you only need to check if a queryset has results, <code>exists()</code> is more efficient than loading the entire queryset.</p>
</li>
</ul>
<h4 id="heading-5-asynchronous-orm-support-django-31-and-later">5. <strong>Asynchronous ORM Support (Django 3.1 and later)</strong></h4>
<ul>
<li><strong>Async ORM</strong>: Django 3.1 introduced support for asynchronous ORM. This allows for asynchronous query execution, which can be beneficial for IO-bound operations.</li>
</ul>
<h4 id="heading-6-profiling-and-debugging">6. <strong>Profiling and Debugging</strong></h4>
<ul>
<li><p><strong>Query Logging</strong>: Use Django's logging framework to log queries in development. Tools like Django Debug Toolbar can provide insights into query patterns and inefficiencies.</p>
</li>
<li><p><strong>Profiling Tools</strong>: Use profiling tools to understand the performance characteristics of your ORM operations.</p>
</li>
</ul>
<h4 id="heading-7-best-practices-in-model-design">7. <strong>Best Practices in Model Design</strong></h4>
<ul>
<li><p><strong>Lean Models</strong>: Keep models focused and lean. Avoid unnecessary fields and relationships.</p>
</li>
<li><p><strong>Using</strong> <code>select_for_update()</code>: In scenarios where transaction integrity is critical, such as in concurrent environments, <code>select_for_update()</code> can be used to lock rows until the transaction is complete.</p>
</li>
</ul>
<h4 id="heading-8-optimizing-orm-for-scalability">8. <strong>Optimizing ORM for Scalability</strong></h4>
<ul>
<li><p><strong>Database Sharding and Replication</strong>: For large-scale applications, consider database sharding or replication. Django ORM can be configured to work with multiple databases, allowing for scalability and improved performance.</p>
</li>
<li><p><strong>Batch Processing</strong>: For operations on large datasets, consider batch processing. The <code>bulk_create</code>, <code>bulk_update</code>, and <code>iterator()</code> methods can be used to efficiently handle large volumes of data.</p>
</li>
</ul>
<h4 id="heading-9-avoiding-orm-anti-patterns">9. <strong>Avoiding ORM Anti-Patterns</strong></h4>
<ul>
<li><p><strong>Overusing</strong> <code>all()</code>: Avoid using <code>all()</code> to fetch entire tables, especially for large datasets.</p>
</li>
<li><p><strong>Raw SQL Queries</strong>: While Django ORM is powerful, sometimes raw SQL queries are necessary for complex operations. Use them judiciously.</p>
</li>
</ul>
<h4 id="heading-10-regular-performance-audits">10. <strong>Regular Performance Audits</strong></h4>
<ul>
<li><strong>Regular Audits</strong>: Conduct regular performance audits on your ORM usage. This includes reviewing query patterns, indexing strategies, and overall database design.</li>
</ul>
<p>In conclusion, optimizing Django ORM is a multifaceted process involving query efficiency, database design, data retrieval techniques, and an understanding of Django's underlying mechanisms.</p>
]]></content:encoded></item><item><title><![CDATA[Authenticating User while testing websocket using Django Channels]]></title><description><![CDATA[Authenticating users while testing socket connections using Django Channels involves a few steps. Here's a general guide on how to achieve this:
1. Set Up Django Channels
Firstly, ensure that Django Channels is properly installed and configured in yo...]]></description><link>https://arjun.name.np/authenticating-user-while-testing-websocket-using-django-channels</link><guid isPermaLink="true">https://arjun.name.np/authenticating-user-while-testing-websocket-using-django-channels</guid><category><![CDATA[Django]]></category><category><![CDATA[Channels]]></category><category><![CDATA[drf]]></category><category><![CDATA[websockets]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Tue, 09 Jan 2024 07:10:56 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705218786144/801cf5e1-ee17-4978-9d44-ce8cac2a37ea.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Authenticating users while testing socket connections using Django Channels involves a few steps. Here's a general guide on how to achieve this:</p>
<h3 id="heading-1-set-up-django-channels">1. Set Up Django Channels</h3>
<p>Firstly, ensure that Django Channels is properly installed and configured in your Django project. This includes setting up the ASGI application and routing.</p>
<h3 id="heading-2-create-test-cases">2. Create Test Cases</h3>
<p>You will need to create test cases specifically for your Channels consumers. Django Channels offers a <code>ChannelsLiveServerTestCase</code> class that you can use to write tests for your consumers.</p>
<h3 id="heading-3-establish-a-test-websocket-connection">3. Establish a Test WebSocket Connection</h3>
<p>Using a test client (like the one provided by Channels or a third-party client such as <code>websocket-client</code>), establish a WebSocket connection to your Channels server. This is typically done in the setup phase of your test case.</p>
<h3 id="heading-4-implement-user-authentication">4. Implement User Authentication</h3>
<p>For authenticating users, you can use Django's standard authentication mechanisms. When a WebSocket connection is made, the consumer can access the user from the scope. However, during testing, you might need to simulate this.</p>
<p>You can simulate a logged-in user in tests by creating a user and then manually setting the appropriate cookies or session data in the test client. This will depend on your authentication method (e.g., token-based, session-based).</p>
<h3 id="heading-5-testing-with-authenticated-user">5. Testing with Authenticated User</h3>
<p>Once you have set up the user's authentication context, you can proceed to test your consumer's behavior with the authenticated user. Make sure to test for both authenticated and unauthenticated scenarios.</p>
<h3 id="heading-6-clean-up">6. Clean Up</h3>
<p>After your tests, ensure to clean up any created data or states to maintain test isolation.</p>
<h3 id="heading-example-code-snippet">Example Code Snippet</h3>
<p>Here is a very basic example of how a test case might look:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> channels.testing <span class="hljs-keyword">import</span> ChannelsLiveServerTestCase
<span class="hljs-keyword">from</span> django.contrib.auth.models <span class="hljs-keyword">import</span> User
<span class="hljs-keyword">from</span> myapp.consumers <span class="hljs-keyword">import</span> MyConsumer

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyConsumerTestCase</span>(<span class="hljs-params">ChannelsLiveServerTestCase</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">setUp</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># Set up user and authentication here</span>
        self.user = User.objects.create_user(username=<span class="hljs-string">'testuser'</span>, password=<span class="hljs-string">'password'</span>)
        self.client.force_login(self.user)
        <span class="hljs-comment"># More setup as needed</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">test_my_consumer</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-comment"># Connect to the WebSocket</span>
        <span class="hljs-keyword">with</span> self.client.websocket_connect(<span class="hljs-string">"/ws/myapp/"</span>) <span class="hljs-keyword">as</span> websocket:
            <span class="hljs-comment"># Test sending and receiving messages</span>
            websocket.send_json({<span class="hljs-string">"type"</span>: <span class="hljs-string">"test_message"</span>})
            response = websocket.receive_json()
            self.assertEqual(response, {<span class="hljs-string">"type"</span>: <span class="hljs-string">"response"</span>, <span class="hljs-string">"authenticated"</span>: <span class="hljs-literal">True</span>})
            <span class="hljs-comment"># More assertions and tests</span>
</code></pre>
<h3 id="heading-important-notes">Important Notes</h3>
<ul>
<li><p>Ensure that your test environment correctly mirrors your production environment, especially regarding the authentication setup.</p>
</li>
<li><p>Depending on the complexity of your application, you might need additional setup for handling channels layers, database interactions, etc.</p>
</li>
</ul>
<p>This is a basic guide, and the specifics can vary significantly based on the exact requirements and setup of your Django project.</p>
]]></content:encoded></item><item><title><![CDATA[Git Branch Naming Convention]]></title><description><![CDATA[Git branch naming conventions are essential for maintaining a clear and organized repository. Consistent and descriptive branch names make it easier for collaborators to understand the purpose of each branch and help avoid confusion. Here are some be...]]></description><link>https://arjun.name.np/git-branch-naming-convention</link><guid isPermaLink="true">https://arjun.name.np/git-branch-naming-convention</guid><category><![CDATA[Git]]></category><category><![CDATA[GitHub]]></category><category><![CDATA[branch]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Tue, 30 May 2023 06:49:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1705218511944/691bdbdd-f581-4598-aa61-55fffe62d3e5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Git branch naming conventions are essential for maintaining a clear and organized repository. Consistent and descriptive branch names make it easier for collaborators to understand the purpose of each branch and help avoid confusion. Here are some best practices for naming Git branches:</p>
<ol>
<li><p><strong>Use Descriptive Names</strong>: Choose branch names that clearly convey the purpose of the branch. Use meaningful words or phrases to describe the changes or features being worked on.</p>
</li>
<li><p><strong>Keep It Short</strong>: While descriptive, the branch names should also be concise. Long branch names can be cumbersome and may not display fully in certain tools.</p>
</li>
<li><p><strong>Use Hyphens or Underscores</strong>: Use hyphens (-) or underscores (_) to separate words in branch names. Avoid using spaces or special characters that may cause issues with some systems.</p>
</li>
<li><p><strong>Include a Prefix</strong>: Consider adding a prefix to your branch names to categorize them. For example:</p>
<ul>
<li><p><code>feature/new-login-page</code></p>
</li>
<li><p><code>bugfix/issue-123</code></p>
</li>
<li><p><code>hotfix/critical-bug</code></p>
</li>
</ul>
</li>
<li><p><strong>Use Lowercase Letters</strong>: Stick to lowercase letters for branch names. Git is case-sensitive, and using consistent lowercase makes it easier to avoid conflicts.</p>
</li>
<li><p><strong>Avoid Using Personal Names</strong>: Don't include personal names or usernames in branch names, as it doesn't provide any information about the branch's purpose.</p>
</li>
<li><p><strong>Use Issue Tracker References</strong>: If your team uses an issue tracker (like JIRA, GitHub Issues, etc.), consider referencing the issue number in the branch name. This helps link branches to specific tasks or problems.</p>
</li>
<li><p><strong>Follow a Workflow</strong>: If your team follows a specific Git workflow (e.g., Gitflow), adhere to the naming conventions recommended in that workflow.</p>
</li>
<li><p><strong>Delete Merged Branches</strong>: Once a branch has been merged into the main branch (e.g., master or main), consider deleting it to keep the repository clean and reduce clutter.</p>
</li>
</ol>
<p>Examples of good branch names:</p>
<ul>
<li><p><code>feature/user-authentication</code></p>
</li>
<li><p><code>bugfix/issue-456</code></p>
</li>
<li><p><code>refactor/update-db-models</code></p>
</li>
</ul>
<p>Examples of poor branch names:</p>
<ul>
<li><p><code>branch1</code>, <code>new-feature</code>, <code>fix</code>, etc. (non-descriptive and generic)</p>
</li>
<li><p><code>Johns-branch</code>, <code>dev_branch</code>, etc. (personal names or unclear purpose)</p>
</li>
<li><p><code>BUGFIX</code>, <code>FeAtUrE</code>, etc. (inconsistent casing)</p>
</li>
</ul>
<p>Remember that these are general best practices, and you should adapt them to suit your team's workflow and preferences. Consistency within the team is key to ensuring everyone understands the branch naming conventions and follows them consistently.</p>
]]></content:encoded></item><item><title><![CDATA[Django and HTMX - A Lovely Couple]]></title><description><![CDATA[Django is a popular Python web framework that follows the model-template-view (MVT) architectural pattern. It provides a powerful and flexible way to build web applications, with features like URL routing, database integration, and a templating engin...]]></description><link>https://arjun.name.np/django-and-htmx-a-lovely-couple</link><guid isPermaLink="true">https://arjun.name.np/django-and-htmx-a-lovely-couple</guid><category><![CDATA[Django]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[htmx]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Mon, 10 Apr 2023 16:01:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681142451480/3100e2fa-62a0-4259-a77f-6f3758ecdfc3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Django is a popular Python web framework that follows the model-template-view (MVT) architectural pattern. It provides a powerful and flexible way to build web applications, with features like URL routing, database integration, and a templating engine.</p>
<p><code>htmx</code> is a library that allows you to add dynamic behavior to your web pages using HTML attributes. It enables you to update parts of a web page without having to refresh the entire page or write a lot of JavaScript code. It works by sending small, targeted requests to the server and updating only the relevant parts of the page with the server's response.</p>
<p>Django and <code>htmx</code> can work together to create highly dynamic and interactive web applications. <code>htmx</code> can be used to add dynamic behavior to Django's HTML templates, such as updating a list of items without refreshing the page, or adding a new item to a form without having to navigate away from the page.</p>
<p>One popular <code>htmx</code> feature is its ability to easily handle form submissions with minimal JavaScript code. With <code>htmx</code>, you can submit a form using an HTTP request, and the server can return a partial HTML response that updates only the relevant parts of the page.</p>
<h3 id="heading-setup">Setup</h3>
<ol>
<li><p>Include HTMX CDN in Django template.</p>
<pre><code class="lang-javascript"> &lt;script src=<span class="hljs-string">"https://cdnjs.cloudflare.com/ajax/libs/htmx/1.8.6/htmx.min.js"</span> integrity=<span class="hljs-string">"sha512-SqV24lSRcthd1Bg0Obg/W/qWhKdSsQPIV342MQd8qDeeY/gJt+2qmsLhutblQNDuUx0Xs2Jh7D8m+7S1b0wQyA=="</span> crossorigin=<span class="hljs-string">"anonymous"</span> referrerpolicy=<span class="hljs-string">"no-referrer"</span>&gt;&lt;/script&gt;
</code></pre>
</li>
<li><p>Install <code>django-htmx</code> for better handling of HTMX requests.</p>
<pre><code class="lang-plaintext"> pip install django-htmx
</code></pre>
</li>
<li><p>Next, you need to add <code>'django_htmx'</code> to your <code>INSTALLED_APPS</code> list in your Django project's <a target="_blank" href="http://settings.py"><code>settings.py</code></a> file:</p>
<pre><code class="lang-python"> INSTALLED_APPS = [
     <span class="hljs-comment"># ... other apps ...</span>
     <span class="hljs-string">'django_htmx'</span>,
 ]
</code></pre>
</li>
<li><p>Include <code>django_htmx.middleware.HtmxMiddleware</code> in <code>MIDDLEWARE</code> list in your Django project's <code>settings.py</code> file.</p>
<pre><code class="lang-python"> MIDDLEWARE = [
     <span class="hljs-comment"># ... other middlewares ...</span>
     <span class="hljs-string">"django_htmx.middleware.HtmxMiddleware"</span>,
 ]
</code></pre>
</li>
<li><p>Also, include <code>{% django_htmx_script %}</code> in django template.</p>
<pre><code class="lang-xml"> {% django_htmx_script %}
</code></pre>
</li>
</ol>
<p>Now you're ready to use HTMX in templates.</p>
<h3 id="heading-form-submission">Form submission</h3>
<p>To submit a form using Django and htmx, you can follow these steps:</p>
<ol>
<li><p>Add the <code>hx-post</code> attribute to the <code>&lt;form&gt;</code> tag in your HTML template. This will tell htmx to submit the form using an AJAX request instead of a full page reload. You can also add the <code>hx-target</code> attribute to specify where the server response should be inserted. For example:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">action</span>=<span class="hljs-string">"{% url 'my_view' %}"</span> <span class="hljs-attr">method</span>=<span class="hljs-string">"POST"</span> <span class="hljs-attr">hx-post</span> <span class="hljs-attr">hx-target</span>=<span class="hljs-string">"#form-container"</span>&gt;</span>
     {% csrf_token %}
     <span class="hljs-comment">&lt;!-- form fields go here --&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
 <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"form-container"</span>&gt;</span>
     <span class="hljs-comment">&lt;!-- server response will be inserted here --&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
</li>
<li><p>In your Django view function, you can check if the request method is <code>POST</code> and handle the form submission accordingly. You can use the <code>render</code> function to render a template with the server response. For example:</p>
<pre><code class="lang-python"> <span class="hljs-keyword">from</span> django.shortcuts <span class="hljs-keyword">import</span> render

 <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">my_view</span>(<span class="hljs-params">request</span>):</span>
     <span class="hljs-keyword">if</span> request.method == <span class="hljs-string">'POST'</span>:
         <span class="hljs-comment"># handle form submission</span>
         <span class="hljs-comment"># ...</span>
         <span class="hljs-comment"># render the response</span>
         <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'response_template.html'</span>,    {<span class="hljs-string">'message'</span>: <span class="hljs-string">'Form submitted successfully!'</span>})
     <span class="hljs-keyword">else</span>:
         <span class="hljs-comment"># render the form</span>
         <span class="hljs-keyword">return</span> render(request, <span class="hljs-string">'form_template.html'</span>)
</code></pre>
</li>
<li><p>Create a new HTML template for the server response, and include the response message or data. For example:</p>
<pre><code class="lang-xml"> <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>{{ message }}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
</code></pre>
</li>
</ol>
<p>That's it! When the user submits the form, <code>htmx</code> will send an AJAX request to your Django view function, and the server response will be inserted into the specified target element without a full page reload.</p>
]]></content:encoded></item><item><title><![CDATA[Linux Commands]]></title><description><![CDATA[Linux is a free and open-source operating system that is often used on servers, supercomputers, embedded systems, and personal computers. One of the best things about Linux is that it has a powerful command-line interface that makes it easy and flexi...]]></description><link>https://arjun.name.np/linux-commands</link><guid isPermaLink="true">https://arjun.name.np/linux-commands</guid><category><![CDATA[Linux]]></category><category><![CDATA[cli]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Mon, 10 Apr 2023 15:38:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681141074524/884575d2-1cf9-4d5d-ad37-56abafe5ddbf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Linux is a free and open-source operating system that is often used on servers, supercomputers, embedded systems, and personal computers. One of the best things about Linux is that it has a powerful command-line interface that makes it easy and flexible to work with the system. While graphical user interfaces are also available in Linux, mastering the command line can help users to perform complex tasks, automate repetitive actions, and troubleshoot issues more effectively. In this blog post, we'll talk about some basic and advanced Linux commands that have to do with the file system, managing memory, and other useful tasks. Whether you are a Linux beginner or an experienced user, this guide can help you improve your productivity and efficiency in the command line.</p>
<h3 id="heading-basic-commands">Basic Commands</h3>
<p>Here are some basic commands in Linux:</p>
<ol>
<li><p><code>ls</code>: Lists the files and directories in the current directory.</p>
</li>
<li><p><code>cd</code>: Changes the current directory.</p>
</li>
<li><p><code>pwd</code>: Prints the working directory.</p>
</li>
<li><p><code>mkdir</code>: Creates a new directory.</p>
</li>
<li><p><code>rmdir</code>: Removes a directory.</p>
</li>
<li><p><code>touch</code>: Creates a new file.</p>
</li>
<li><p><code>rm</code>: Removes a file.</p>
</li>
<li><p><code>cp</code>: Copies a file.</p>
</li>
<li><p><code>mv</code>: Moves or renames a file.</p>
</li>
<li><p><code>cat</code>: Displays the contents of a file.</p>
</li>
<li><p><code>grep</code>: Searches for a pattern in a file.</p>
</li>
<li><p><code>sudo</code>: Executes a command as the root user.</p>
</li>
<li><p><code>apt-get</code>: Installs, updates, or removes software packages.</p>
</li>
<li><p><code>chmod</code>: Changes the permissions of a file or directory.</p>
</li>
<li><p><code>chown</code>: Changes the ownership of a file or directory.</p>
</li>
</ol>
<h3 id="heading-file-system-commands">File System Commands</h3>
<p>Here are some commands related to file system in Linux:</p>
<ol>
<li><p><code>df</code>: Displays the disk usage and available space on mounted file systems.</p>
</li>
<li><p><code>du</code>: Displays the disk usage of a file or directory.</p>
</li>
<li><p><code>fdisk</code>: A partitioning utility that can create, delete, and manipulate disk partitions.</p>
</li>
<li><p><code>mkfs</code>: Formats a file system on a disk partition.</p>
</li>
<li><p><code>mount</code>: Mounts a file system to a directory.</p>
</li>
<li><p><code>umount</code>: Unmounts a file system from a directory.</p>
</li>
<li><p><code>blkid</code>: Displays the UUID and file system type of all available block devices.</p>
</li>
<li><p><code>find</code>: Searches for files and directories based on certain criteria such as name, size, or modification time.</p>
</li>
<li><p><code>locate</code>: Searches for files and directories based on their names.</p>
</li>
<li><p><code>ln</code>: Creates a hard or symbolic link to a file.</p>
</li>
<li><p><code>tar</code>: Creates or extracts a compressed archive file.</p>
</li>
<li><p><code>rsync</code>: Synchronizes the contents of two directories or files across a network.</p>
</li>
<li><p><code>diff</code>: Compares the contents of two files and displays the differences.</p>
</li>
<li><p><code>grep</code>: Searches for a pattern in a file or multiple files.</p>
</li>
<li><p><code>awk</code>: A text processing tool that can extract and manipulate data from files.</p>
</li>
</ol>
<h3 id="heading-memory-management-commands">Memory Management Commands:</h3>
<p>Here are some commands related to memory management system in Linux:</p>
<ol>
<li><p><code>free</code>: Displays the amount of free and used memory in the system.</p>
</li>
<li><p><code>top</code>: Displays real-time information about the system's processes and memory usage.</p>
</li>
<li><p><code>ps</code>: Displays information about the currently running processes.</p>
</li>
<li><p><code>kill</code>: Sends a signal to terminate a process.</p>
</li>
<li><p><code>nice</code>: Adjusts the priority of a process to control its resource usage.</p>
</li>
<li><p><code>renice</code>: Changes the priority of a running process.</p>
</li>
<li><p><code>vmstat</code>: Displays virtual memory statistics such as page faults and swap usage.</p>
</li>
<li><p><code>swapon</code>: Activates a swap partition or file.</p>
</li>
<li><p><code>swapoff</code>: Deactivates a swap partition or file.</p>
</li>
<li><p><code>ulimit</code>: Sets limits on system resources such as memory usage and file size for user processes.</p>
</li>
<li><p><code>top</code>: Provides a dynamic real-time view of the processes running in a system, with detailed information about the memory and CPU usage of each process.</p>
</li>
<li><p><code>htop</code>: A more advanced version of top, which provides additional functionality and an interactive interface.</p>
</li>
<li><p><code>pmap</code>: Displays the memory map of a process, showing the virtual memory addresses used by each memory-mapped file or shared library.</p>
</li>
<li><p><code>sysctl</code>: Configures kernel parameters related to memory management, such as swappiness or the size of the page cache.</p>
</li>
<li><p><code>numactl</code>: Configures NUMA (non-uniform memory access) settings, such as the allocation policy for memory and CPUs.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[PostgreSQL Commands]]></title><description><![CDATA[PostgreSQL is a popular open-source relational database management system that is widely used by developers and organizations around the world. It is known for its powerful features, scalability, and flexibility. One of the primary ways to interact w...]]></description><link>https://arjun.name.np/postgresql-commands</link><guid isPermaLink="true">https://arjun.name.np/postgresql-commands</guid><category><![CDATA[PostgreSQL]]></category><category><![CDATA[psql]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Mon, 10 Apr 2023 15:29:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681140515192/a4eb5fa9-b6c6-4483-a804-f4df51b4cd2e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PostgreSQL is a popular open-source relational database management system that is widely used by developers and organizations around the world. It is known for its powerful features, scalability, and flexibility. One of the primary ways to interact with a PostgreSQL database is through the psql command-line interface.</p>
<p>In this blog post, we will explore some of the most useful psql commands that every PostgreSQL developer should know. From creating databases and tables to querying data and managing users, we'll cover a wide range of commands that will help you become more efficient and effective in working with PostgreSQL. Whether you're a beginner or an experienced PostgreSQL developer, this post will provide you with the knowledge you need to take your skills to the next level. So, let's dive in and discover some of the most essential psql commands!</p>
<ol>
<li><p><code>\du</code>: Lists all users in the current database and their roles.</p>
</li>
<li><p><code>\dt</code>: Lists all tables in the current database.</p>
</li>
<li><p><code>\d &lt;table_name&gt;</code>: Provides a description of a specified table, including the columns, their data types, and any constraints.</p>
</li>
<li><p><code>\i &lt;file_name&gt;</code>: Executes the SQL commands contained in the specified file.</p>
</li>
<li><p><code>\e</code>: Opens the default editor to edit the current command or query.</p>
</li>
<li><p><code>\timing</code>: Toggles display of the query execution time after each query.</p>
</li>
<li><p><code>\! &lt;shell_command&gt;</code>: Executes the specified shell command from within psql.</p>
</li>
<li><p><code>\conninfo</code>: Shows information about the current database connection, including the username, database name, host, and port.</p>
</li>
<li><p><code>\x</code>: Toggles expanded display mode, which shows query results in a more readable format.</p>
</li>
<li><p><code>\h</code>: Lists all available psql commands with brief descriptions.</p>
</li>
<li><p><code>psql -d &lt;database_name&gt;</code>: Connect to a database.</p>
</li>
<li><p><code>createdb &lt;database_name&gt;</code>: Create a new database.</p>
</li>
<li><p><code>\l</code>: List databases.</p>
</li>
<li><p><code>\q</code>: Quit PSQL.</p>
</li>
<li><p><code>\connect &lt;database_name&gt; or \c &lt;database_name&gt;</code>: Connect to a specific database.</p>
</li>
</ol>
<p>Note that some of these commands have additional options and arguments that can be used to modify their behavior. You can find more information on these options and arguments in the PostgreSQL documentation.</p>
<h2 id="heading-commonly-used-sql-commands">Commonly used SQL Commands</h2>
<hr />
<h2 id="heading-1-creating-a-superuser">1. Creating a Superuser</h2>
<h3 id="heading-using-sql-within-psql-or-via-a-script">Using SQL (within psql or via a script):</h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Using CREATE ROLE:</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">ROLE</span> my_superuser <span class="hljs-keyword">WITH</span> LOGIN SUPERUSER <span class="hljs-keyword">PASSWORD</span> <span class="hljs-string">'your_secure_password'</span>;

<span class="hljs-comment">-- Alternatively, using CREATE USER (they’re almost interchangeable in PostgreSQL):</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">USER</span> my_superuser <span class="hljs-keyword">WITH</span> SUPERUSER <span class="hljs-keyword">PASSWORD</span> <span class="hljs-string">'your_secure_password'</span>;
</code></pre>
<p><em>Replace</em> <code>my_superuser</code> and <code>'your_secure_password'</code> with your desired username and a strong, secure password.</p>
<blockquote>
<p><strong>Tip:</strong> On Unix-based systems, you can also create a superuser directly from the shell:</p>
<pre><code class="lang-bash">sudo -u postgres createuser --superuser my_superuser
</code></pre>
</blockquote>
<hr />
<h2 id="heading-2-commonly-used-psql-meta-commands">2. Commonly Used psql Meta-Commands</h2>
<p>When you’re inside the psql shell, these slash (\) commands are super useful:</p>
<ul>
<li><p><code>\l</code> or <code>\list</code>: List all databases.</p>
</li>
<li><p><code>\c [database_name]</code>: Connect to a specific database.</p>
</li>
<li><p><code>\du</code>: List all roles (users).</p>
</li>
<li><p><code>\d</code>: List all database objects (tables, views, indexes, etc.).</p>
</li>
<li><p><code>\dt</code>: List only tables.</p>
</li>
<li><p><code>\dv</code>: List views.</p>
</li>
<li><p><code>\df</code>: List functions.</p>
</li>
<li><p><code>\i [file_name.sql]</code>: Execute commands from an external file.</p>
</li>
<li><p><code>\?</code>: Display help on all meta-commands.</p>
</li>
<li><p><code>\q</code>: Quit the psql session.</p>
</li>
</ul>
<hr />
<h2 id="heading-3-common-sql-commands">3. Common SQL Commands</h2>
<h3 id="heading-creating-a-database-and-table">Creating a Database and Table:</h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Create a new database:</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> my_database;

<span class="hljs-comment">-- Connect to the database (if not already connected, use psql's \c command):</span>
\c my_database

<span class="hljs-comment">-- Create a table:</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">TABLE</span> my_table (
    <span class="hljs-keyword">id</span> <span class="hljs-built_in">SERIAL</span> PRIMARY <span class="hljs-keyword">KEY</span>,
    <span class="hljs-keyword">name</span> <span class="hljs-built_in">VARCHAR</span>(<span class="hljs-number">100</span>) <span class="hljs-keyword">NOT</span> <span class="hljs-literal">NULL</span>,
    created_at <span class="hljs-built_in">TIMESTAMP</span> <span class="hljs-keyword">DEFAULT</span> <span class="hljs-keyword">CURRENT_TIMESTAMP</span>
);
</code></pre>
<h3 id="heading-manipulating-data">Manipulating Data:</h3>
<pre><code class="lang-sql"><span class="hljs-comment">-- Inserting Data:</span>
<span class="hljs-keyword">INSERT</span> <span class="hljs-keyword">INTO</span> my_table (<span class="hljs-keyword">name</span>) <span class="hljs-keyword">VALUES</span> (<span class="hljs-string">'Alice'</span>), (<span class="hljs-string">'Bob'</span>);

<span class="hljs-comment">-- Querying Data:</span>
<span class="hljs-keyword">SELECT</span> * <span class="hljs-keyword">FROM</span> my_table;

<span class="hljs-comment">-- Updating Data:</span>
<span class="hljs-keyword">UPDATE</span> my_table <span class="hljs-keyword">SET</span> <span class="hljs-keyword">name</span> = <span class="hljs-string">'Charlie'</span> <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = <span class="hljs-number">1</span>;

<span class="hljs-comment">-- Deleting Data:</span>
<span class="hljs-keyword">DELETE</span> <span class="hljs-keyword">FROM</span> my_table <span class="hljs-keyword">WHERE</span> <span class="hljs-keyword">id</span> = <span class="hljs-number">2</span>;
</code></pre>
<hr />
<h2 id="heading-4-extra-tips-amp-tricks">4. Extra Tips &amp; Tricks</h2>
<ul>
<li><p><strong>Direct Connection via Command Line:</strong><br />  Use this command to jump straight into a specific database:</p>
<pre><code class="lang-bash">  psql -U postgres -d my_database
</code></pre>
</li>
<li><p><strong>Scripting:</strong><br />  Write your SQL commands in a file (e.g., <code>script.sql</code>) and run them with:</p>
<pre><code class="lang-sql">  \i script.sql
</code></pre>
</li>
<li><p><strong>Security First:</strong><br />  Always safeguard your credentials and avoid hard-coding sensitive information in your scripts.</p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[Crontab and Job Scheduling]]></title><description><![CDATA[Crontab is a time-based job scheduler in Unix-like operating systems. It allows users to schedule commands or scripts to run automatically at specified intervals, such as minutes, hours, days, or weeks. Crontab uses a configuration file called the "c...]]></description><link>https://arjun.name.np/crontab-and-job-scheduling</link><guid isPermaLink="true">https://arjun.name.np/crontab-and-job-scheduling</guid><category><![CDATA[Linux]]></category><category><![CDATA[cronjob]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Wed, 05 Apr 2023 20:05:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680725094083/da95d8ab-05f0-4c02-81ae-5007a1192c33.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Crontab is a time-based job scheduler in Unix-like operating systems. It allows users to schedule commands or scripts to run automatically at specified intervals, such as minutes, hours, days, or weeks. Crontab uses a configuration file called the "crontab file" to manage and schedule these jobs.</p>
<p>Each user on a Unix system can have their own crontab file, and each file can contain multiple jobs scheduled to run at different intervals. Crontab syntax consists of six fields separated by spaces: minute, hour, day of the month, month, day of the week, and the command to be executed.</p>
<p>Crontab is often used to do things like run backups, update databases, and take care of the system. It makes it easy for system administrators and developers to automate tasks that they do often and saves them time and effort.</p>
<h2 id="heading-example">Example</h2>
<p>Here is an example of a crontab entry that runs a script every day at 2:30 AM:</p>
<pre><code class="lang-plaintext">30 2 * * * /path/to/script.sh
</code></pre>
<p>Now, let's break down the components of this crontab entry:</p>
<ul>
<li><p><code>30</code>: This is the minute field. It specifies that the script should be executed at the 30th minute of the hour.</p>
</li>
<li><p><code>2</code>: This is the hour field. It specifies that the script should be executed at 2:30 AM.</p>
</li>
<li><p><code>*</code>: This is the day of the month field. It specifies that the script should be executed every day of the month.</p>
</li>
<li><p><code>*</code>: This is the month field. It specifies that the script should be executed every month.</p>
</li>
<li><p><code>*</code>: This is the day of the week field. It specifies that the script should be executed every day of the week.</p>
</li>
<li><p><code>/path/to/script.sh</code>: This is the command to be executed. It specifies the full path to the script that should be executed.</p>
</li>
</ul>
<p>So, in summary, this crontab entry runs the specified script every day at 2:30 AM, regardless of the day of the week or the month.</p>
<h2 id="heading-commands">Commands</h2>
<p>Here are some basic crontab commands that you can use to manage your crontab:</p>
<ul>
<li><p><code>crontab -e</code>: This command opens the crontab file in the default editor, allowing you to add or modify crontab entries.</p>
</li>
<li><p><code>crontab -l</code>: This command lists the current crontab entries for the current user.</p>
</li>
<li><p><code>crontab -r</code>: This command removes all crontab entries for the current user.</p>
</li>
<li><p><code>crontab -u [username] -e</code>: This command opens the crontab file for the specified user, allowing you to add or modify crontab entries for that user.</p>
</li>
<li><p><code>crontab -u [username] -l</code>: This command lists the crontab entries for the specified user.</p>
</li>
</ul>
<p>These are some of the most commonly used crontab commands. There are many other options available, which you can find by running <code>man crontab</code> in your terminal.</p>
<h2 id="heading-logs">Logs</h2>
<p>Logging the output of a crontab job to a file can be useful for debugging and troubleshooting. You can do this by adding <code>&gt;&gt; /path/to/logfile 2&gt;&amp;1</code> at the end of your crontab command. Here is an example:</p>
<pre><code class="lang-plaintext">30 2 * * * /path/to/script.sh &gt;&gt; /path/to/logfile 2&gt;&amp;1
</code></pre>
<p>This will redirect both standard output (stdout) and standard error (stderr) to the specified log file.</p>
<p>If you want to suppress the output of a crontab job entirely, you can add <code>&gt; /dev/null 2&gt;&amp;1</code> at the end of the command. Here is an example:</p>
<pre><code class="lang-plaintext">30 2 * * * /path/to/script.sh &gt; /dev/null 2&gt;&amp;1
</code></pre>
<p>This will redirect both stdout and stderr to the null device, effectively discarding any output.</p>
<h2 id="heading-extras">Extras</h2>
<ul>
<li><p>Always test your crontab entries before scheduling them to run automatically. You can do this by running the command manually and verifying that it produces the desired output.</p>
</li>
<li><p>Use absolute paths for all commands and files referenced in your crontab. This ensures that the correct files and commands are used, even if the current working directory is different from what you expect.</p>
</li>
<li><p>Be mindful of time zones. By default, crontab runs commands in the server's time zone. If you need to schedule jobs in a different time zone, you can use the <code>TZ</code> environment variable to set the desired time zone.</p>
</li>
<li><p>Avoid overlapping jobs. If you have multiple crontab jobs that run at the same time, make sure they don't interfere with each other or cause performance issues. Consider staggering the jobs or using a job queue to manage them.</p>
</li>
<li><p>Use descriptive comments to document your crontab entries. This makes it easier to understand what each job does and why it's scheduled to run at a specific time.</p>
</li>
</ul>
<h2 id="heading-usage">Usage</h2>
<h3 id="heading-with-django">With Django</h3>
<p>To use crontab with Django management commands, follow these steps:</p>
<ol>
<li>Open your crontab configuration file by typing the following command in your terminal:</li>
</ol>
<pre><code class="lang-plaintext">crontab -e
</code></pre>
<ol>
<li>In the crontab file, add a new line for the task you want to schedule, using the following syntax:</li>
</ol>
<pre><code class="lang-plaintext">* * * * * /path/to/python /path/to/manage.py &lt;django-management-command&gt; [options]
</code></pre>
<p>Replace <code>/path/to/python</code> with the path to your Python executable, <code>/path/to/manage.py</code> with the path to your Django project's <a target="_blank" href="http://manage.py">manage.py</a> file, <code>&lt;django-management-command&gt;</code> with the Django management command you want to run, and <code>[options]</code> with any additional options you want to pass to the management command.</p>
<p>For example, if you want to run the <code>my_custom_command</code> management command every day at midnight, you would add the following line to your crontab file:</p>
<pre><code class="lang-plaintext">0 0 * * * /usr/bin/python /path/to/myproject/manage.py my_custom_command
</code></pre>
<ol>
<li>Save and close the crontab file. Your scheduled task will now run automatically according to the schedule you specified in the crontab file.</li>
</ol>
<p>Note that when using crontab with Django management commands, you may need to set the <code>DJANGO_SETTINGS_MODULE</code> environment variable to the path of your project's settings module. You can do this by adding the following line at the beginning of your crontab file:</p>
<pre><code class="lang-plaintext">DJANGO_SETTINGS_MODULE=myproject.settings
</code></pre>
<p>Replace <code>myproject.settings</code> with the path to your project's settings module.</p>
]]></content:encoded></item><item><title><![CDATA[Django Folder Structure]]></title><description><![CDATA[The Django folder structure is a standard way to organize files and directories within a Django project. At the root level, there are typically files like manage.py and settings.py, which define project settings and configurations. A basic folder str...]]></description><link>https://arjun.name.np/django-folder-structure</link><guid isPermaLink="true">https://arjun.name.np/django-folder-structure</guid><category><![CDATA[Django]]></category><category><![CDATA[Folder Structure]]></category><category><![CDATA[convention]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Wed, 29 Mar 2023 19:48:01 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680119247129/c908b4e7-d0ce-44d0-a5c6-53241b2eb212.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The Django folder structure is a standard way to organize files and directories within a Django project. At the root level, there are typically files like <a target="_blank" href="http://manage.py"><code>manage.py</code></a> and <a target="_blank" href="http://settings.py"><code>settings.py</code></a>, which define project settings and configurations. A basic folder structure for a Django project can help you organize your files and make your project more scalable and maintainable. Here is a sample folder structure:</p>
<pre><code class="lang-plaintext">project_name/
├── config/
│   ├── settings/
│   │   ├── base.py
│   │   ├── local.py
│   │   ├── development.py
│   │   ├── staging.py
│   │   ├── production.py
│   ├── urls.py
│   ├── wsgi.py
│   ├── asgi.py
│
├── apps/
│   ├── app1/
│   │   ├── migrations/
│   │   ├── templates/
│   │   ├── static/
│   │   ├── tasks/
│   │   ├── utils/
│   │   ├── management/
│   │   ├── api/
│   │   │   ├── v1/
│   │   │   │   ├── serializers.py
│   │   │   │   ├── views.py
│   │   │   │   ├── filters.py
│   │   │   ├── v2/
│   │   ├── __init__.py
│   │   ├── admin.py
│   │   ├── apps.py
│   │   ├── choices.py
│   │   ├── models.py
│   │   ├── signals.py
│   │   ├── urls.py
│   │   ├── views.py
│   ├── app2/
│   ├── app3/│
│
├── static/
│   ├── css/
│   ├── js/
│   ├── img/
│
├── media/
│
├── templates/
│
├── utils/
│
├── tasks/
│
├── management/
│
├── manage.py
│
</code></pre>
<p>In this structure, the main project folder contains three main directories: <code>config</code>, <code>apps</code>, <code>static</code>, and <code>media</code>.</p>
<ul>
<li><p><code>config</code> directory contains all the settings and configurations of the Django project. It includes settings for different environments such as <a target="_blank" href="http://base.py"><code>base.py</code></a> (base settings), <a target="_blank" href="http://local.py"><code>local.py</code></a> (local development settings), <a target="_blank" href="http://development.py"><code>development.py</code></a> (development environment settings), <a target="_blank" href="http://staging.py"><code>staging.py</code></a> (staging environment settings), and <a target="_blank" href="http://production.py"><code>production.py</code></a> (production environment settings). It also includes <a target="_blank" href="http://urls.py"><code>urls.py</code></a> (main project URL configuration), <a target="_blank" href="http://wsgi.py"><code>wsgi.py</code></a> (Web Server Gateway Interface configuration), and <a target="_blank" href="http://asgi.py"><code>asgi.py</code></a> (Asynchronous Server Gateway Interface configuration).</p>
</li>
<li><p><code>apps</code> directory contains all the apps that are part of the Django project. Each app has its own directory containing models, views, templates, static files, and tests. This structure helps to keep the code organized and makes it easier to manage.</p>
<ul>
<li><p><code>tasks/</code>: This directory contains files for background tasks such as Celery tasks.</p>
</li>
<li><p><code>templates/</code>: This directory contains all of the app's templates.</p>
</li>
<li><p><code>static/</code>: This directory contains all of the app's static files, such as CSS, JavaScript, and images.</p>
</li>
<li><p><code>utils/</code>: This directory contains utility files that are used across multiple apps in the project, such as common helper functions, mixins, or abstract classes.</p>
</li>
<li><p><code>management/</code>: This directory contains custom management commands for the Django project. These commands can be used to automate tasks, create database entries, and perform other administrative functions.</p>
</li>
<li><p><code>api/</code>: This directory is inside each app and contains versioned subdirectories for the API views. Each versioned subdirectory has its own <a target="_blank" href="http://serializers.py"><code>serializers.py</code></a>, <a target="_blank" href="http://filters.py"><code>filters.py</code></a> and <code>views.py</code> files.</p>
<ul>
<li><code>v1/</code> and <code>v2/</code>: These directories are inside each app's <code>api/</code> directory and represent version 1 and version 2 of the API. Each versioned subdirectory can have its own <a target="_blank" href="http://serializers.py"><code>serializers.py</code></a>, <a target="_blank" href="http://filters.py"><code>filters.py</code></a> and <code>views.py</code> files. which allows for different versions of the API to have different serializers and filters.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>static</code> directory contains all the static files used in the project such as CSS, JavaScript, and images.</p>
</li>
<li><p><code>media</code> directory contains all the media files uploaded by the users of the website.</p>
</li>
<li><p><code>templates</code> directory contains all the HTML templates used in the project.</p>
</li>
<li><p><a target="_blank" href="http://manage.py"><code>manage.py</code></a> is the entry point to the Django project and is used to execute various Django commands such as starting the development server, running database migrations, etc.</p>
</li>
</ul>
<p>This is just a basic structure, and depending on the size and complexity of your project, you may need to modify it.</p>
]]></content:encoded></item><item><title><![CDATA[Docker 101]]></title><description><![CDATA[It is an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS level virtualization on Linux. In simple words, Docker is a tool for running yo...]]></description><link>https://arjun.name.np/docker-101</link><guid isPermaLink="true">https://arjun.name.np/docker-101</guid><category><![CDATA[Docker]]></category><category><![CDATA[Dockerfile]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Fri, 24 Mar 2023 19:47:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679687223101/65cd3185-179f-40da-a54b-61187642202f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>It is an open-source project that automates the deployment of software applications inside containers by providing an additional layer of abstraction and automation of OS level virtualization on Linux. In simple words, Docker is a tool for running your applications inside containers.</p>
<p>Container package all the dependencies and code your app needs to run into a single file, which will run the same way on any machine.</p>
<h2 id="heading-terminologies">Terminologies</h2>
<h3 id="heading-docker-container">Docker Container</h3>
<p>A container is a standard unit of software that packages up code and all its dependencies, so the application runs quickly and reliably from one computing environment to another.</p>
<h3 id="heading-container-image">Container Image</h3>
<p>A Docker container image is a lightweight, standalone, executable package of software that includes everything needed to run an application: code, runtime, system tools, system libraries and settings.</p>
<h3 id="heading-how-containers-work">How containers work ?</h3>
<p>By using the low-level mechanics of the host operating system, containers provide most of the isolation of virtual machines at a fraction of the computing power.</p>
<h3 id="heading-virtual-machines">Virtual Machines</h3>
<p>VMs are great at providing full process isolation for applications: there are very few ways a problem in the host operating system can affect the software running in the guest operating system, and vice-versa.</p>
<h3 id="heading-cons-of-virtual-machines">Cons of Virtual Machines</h3>
<p>However, the isolation comes at a high cost: the computational overhead associated with virtualizing hardware for use by a guest OS is significant.</p>
<h3 id="heading-image-vs-container">Image vs Container</h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Container</td><td>Image</td></tr>
</thead>
<tbody>
<tr>
<td>An instance of an image is called container.</td><td>You have an image, which is a set of layers as you describe. It you start a image, you have a running container of that image.</td></tr>
<tr>
<td>Isolated Application Platform</td><td>Read only templates used to create containers.</td></tr>
<tr>
<td>Container need to run your application based on images.</td><td>Build by you or other docker users.</td></tr>
<tr>
<td></td><td>Stored in the docker hub or your local registry.</td></tr>
</tbody>
</table>
</div><h3 id="heading-docker-daemon">Docker Daemon</h3>
<ul>
<li><p>The background service running on the host that manages building, running and distributing Docker services.</p>
</li>
<li><p>The daemon is the process that runs in the operating system which clients talk to.</p>
</li>
</ul>
<h3 id="heading-docker-client">Docker Client</h3>
<ul>
<li><p>The command line tool that allows the use to interact with the daemon.</p>
</li>
<li><p>More generally, there can be other forms of clients too - such as Kitematic which provide a GUI to the users.</p>
</li>
</ul>
<h3 id="heading-docker-hub">Docker Hub</h3>
<ul>
<li><p>A registry of Docker images.</p>
</li>
<li><p>You can think of the registry as a directory of all available Docker images.</p>
</li>
<li><p>If required, one can host their own Docker registries and use them for pulling images.</p>
</li>
</ul>
<h2 id="heading-docker-shell-commands">Docker Shell Commands</h2>
<h3 id="heading-run-command">Run command</h3>
<ol>
<li><p><code>docker run hello-world</code></p>
<ul>
<li><p>If the image of the name ‘hello-world’ is not present in the local registry, it will be pulled from the Docker Hub.</p>
</li>
<li><p>By default, it pulls the image fo the latest version from the Docker Hub.</p>
</li>
<li><p><code>pull</code> command pulls the image, and <code>run</code> command does (<code>pull</code> + <code>execute</code>)</p>
</li>
</ul>
</li>
<li><p><code>docker run -it busybox bash</code></p>
<ul>
<li><p><code>bash</code> is the command to run.</p>
</li>
<li><p>Busybox is a software suite that provides several Unix utilities.</p>
</li>
<li><p><code>-i</code> flag makes the container interactive STDIN mode.</p>
</li>
<li><p><code>-t</code> provides pseudo TTY to the container.</p>
</li>
</ul>
</li>
<li><p><code>docker run busybox echo "Hello World"</code></p>
<ul>
<li><p><code>echo</code> is a command to print the text.</p>
</li>
<li><p><code>"Hello World"</code> is the text to print.</p>
</li>
<li><p>If you’ve noticed, all of that happened pretty quickly. Imagine, booting up a virtual machine, running a command and then killing it. Now we know why they say containers are fast.</p>
</li>
</ul>
</li>
</ol>
<h3 id="heading-list-containers">List Containers</h3>
<ol>
<li><p><code>docker ps</code></p>
<ul>
<li>Lists all the running containers.</li>
</ul>
</li>
<li><p><code>docker ps -a</code></p>
<ul>
<li>Lists all the containers.</li>
</ul>
</li>
<li><p><code>docker ps -q</code></p>
<ul>
<li>Lists only the container IDs.</li>
</ul>
</li>
</ol>
<h3 id="heading-stop-container">Stop Container</h3>
<ol>
<li><p><code>docker stop &lt;container-id&gt;</code></p>
<ul>
<li>Stops the container with the given ID.</li>
</ul>
</li>
<li><p><code>docker stop $(docker ps -q)</code></p>
<ul>
<li>Stops all the running containers.</li>
</ul>
</li>
</ol>
<h3 id="heading-remove-container">Remove Container</h3>
<ol>
<li><p><code>docker rm &lt;container-id&gt;</code></p>
<ul>
<li>Removes the container with the given ID.</li>
</ul>
</li>
<li><p><code>docker rm $(docker ps -q)</code></p>
<ul>
<li>Removes all the running containers.</li>
</ul>
</li>
</ol>
<h3 id="heading-list-images">List Images</h3>
<ol>
<li><p><code>docker images -a</code></p>
<ul>
<li>Lists all the images.</li>
</ul>
</li>
<li><p><code>docker images -q</code></p>
<ul>
<li>Lists only the image IDs.</li>
</ul>
</li>
</ol>
<h3 id="heading-remove-image">Remove Image</h3>
<ol>
<li><p><code>docker rmi &lt;image-id&gt;</code></p>
<ul>
<li>Removes the image with the given ID.</li>
</ul>
</li>
<li><p><code>docker rmi $(docker images -q)</code></p>
<ul>
<li>Removes all the images.</li>
</ul>
</li>
</ol>
<h3 id="heading-list-volume">List Volume</h3>
<ol>
<li><p><code>docker volume ls</code></p>
<ul>
<li>Lists all the volumes.</li>
</ul>
</li>
<li><p><code>docker volume ls -q</code></p>
<ul>
<li>Lists only the volume IDs.</li>
</ul>
</li>
</ol>
<h3 id="heading-remove-volume">Remove Volume</h3>
<ol>
<li><p><code>docker volume rm &lt;volume-id&gt;</code></p>
<ul>
<li>Removes the volume with the given ID.</li>
</ul>
</li>
<li><p><code>docker volume rm $(docker volume ls -q)</code></p>
<ul>
<li>Removes all the volumes.</li>
</ul>
</li>
</ol>
<h3 id="heading-delete-all-containers">Delete all Containers</h3>
<ol>
<li><p><code>docker rm -f $(docker ps -a -q)</code></p>
<ul>
<li>Removes all the containers.</li>
</ul>
</li>
</ol>
<h2 id="heading-dockerfile">Dockerfile</h2>
<ul>
<li><p>A Dockerfile is a text file that describes how to build a Docker image.</p>
</li>
<li><p>It contains all the commands a user could call on the comand line to assemble a Docker image.</p>
</li>
</ul>
<h3 id="heading-commands">Commands</h3>
<ol>
<li><p><code>FROM &lt;image&gt;</code></p>
<ul>
<li><p>The FROM command specifies the base image that the Dockerfile will build on.</p>
</li>
<li><p>The image can be a Docker image name, a Docker image tag, or a Docker image ID.</p>
</li>
<li><p>The FROM command is required.</p>
</li>
<li><p>Eg: <code>FROM ubuntu:latest</code></p>
<ul>
<li>In this case, the Dockerfile will build on the latest version of the Ubuntu image.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>MAINTAINER &lt;name&gt;</code></p>
<ul>
<li><p>The MAINTAINER command specifies the person or organization that built the image.</p>
</li>
<li><p>The MAINTAINER command is optional.</p>
</li>
<li><p>Eg: <code>MAINTAINER "Arjun Adhikari"</code></p>
<ul>
<li>In this case, the Dockerfile will be built by Arjun Adhikari.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>RUN &lt;command&gt;</code></p>
<ul>
<li><p>The RUN command specifies a command that will be run when the image is built.</p>
</li>
<li><p>The RUN command is optional.</p>
</li>
<li><p>Eg: <code>RUN apt-get update</code></p>
<ul>
<li>In this case, the Dockerfile will run the apt-get update command.</li>
</ul>
</li>
<li><p>Eg: <code>RUN ["&lt;executable&gt;", "&lt;arguments&gt;"]</code></p>
<ul>
<li><p>In this case, the Dockerfile will run the executable with the arguments.</p>
</li>
<li><p>Shell form, the command is run in a shell, which by default is <code>/bin/sh -c</code> on Linux or <code>cmd /S /C</code> on Windows.</p>
</li>
</ul>
</li>
</ul>
</li>
<li><p><code>CMD &lt;command&gt;</code></p>
<ul>
<li><p>The main purpose of a CMD is to provide defaults for an executing container.</p>
</li>
<li><p>Eg: <code>CMD ["&lt;executable&gt;", "&lt;arguments&gt;"]</code></p>
<ul>
<li>In this case, the Dockerfile will execute the executable with the arguments.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>ENTRYPOINT &lt;command&gt;</code></p>
<ul>
<li><p>The ENTRYPOINT command specifies a command that will be run when the container is started.</p>
</li>
<li><p>If the <code>ENTRYPOINT</code> isn’t specified, the default command is <code>/bin/sh -c</code>.</p>
</li>
<li><p>However, if you want to override some of the system defaults, you can specify own entrypoint and therefore manipulate the environment.</p>
</li>
<li><p>The <code>ENTRYPOINT</code> command also allows arguments to be set from the Docker <code>RUN</code> command as well, whereas <code>CMD</code> cannot.</p>
</li>
<li><p>Eg: <code>ENTRYPOINT ["&lt;executable&gt;", "&lt;arguments&gt;"]</code></p>
<ul>
<li>In this case, the Dockerfile will execute the executable with the arguments.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>WORKDIR &lt;path&gt;</code></p>
<ul>
<li><p>The WORKDIR command specifies the working directory for the container.</p>
</li>
<li><p>Sets the working directory for any <code>RUN</code>, <code>CMD</code>, <code>ENTRYPOINT</code>, <code>COPY</code>, and <code>ADD</code> instructions that follow it.</p>
</li>
<li><p>It can be used multiple times in the one Dockerfile.</p>
</li>
<li><p>If a relative path is provided, it will be relative to the path of the previous <code>WORKDIR</code> command.</p>
</li>
<li><p>Eg: <code>WORKDIR /home/user</code></p>
<ul>
<li>In this case, the Dockerfile will be built in the /home/user directory.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>LABEL &lt;key&gt;=&lt;value&gt;</code></p>
<ul>
<li><p>The LABEL command specifies a label for the image.</p>
</li>
<li><p>It is mainly used for setting metadata for the images.</p>
</li>
<li><p>It can be used multiple times in the one Dockerfile.</p>
</li>
<li><p>Eg: <code>LABEL version=1.0</code></p>
<ul>
<li>In this case, the Dockerfile will be labeled with the version 1.0.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>EXPOSE &lt;port&gt;</code></p>
<ul>
<li><p>The EXPOSE command specifies a port that the container will expose to the host.</p>
</li>
<li><p>Informs Docker that the container will be listening on the specified port at runtime.</p>
</li>
<li><p><code>EXPOSE</code> doesnot make the ports of the container accessible to the host.</p>
</li>
<li><p>It can be used multiple times in the one Dockerfile.</p>
</li>
<li><p>Eg: <code>EXPOSE 8080</code></p>
<ul>
<li>In this case, the Dockerfile will expose the port 8080.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>ENV &lt;key&gt;=&lt;value&gt;</code></p>
<ul>
<li><p>The ENV command specifies an environment variable for the container.</p>
</li>
<li><p>It can be used multiple times in the one Dockerfile.</p>
</li>
<li><p>Eg: <code>ENV PATH=/usr/local/bin</code></p>
<ul>
<li>In this case, the Dockerfile will set the PATH environment variable to /usr/local/bin.</li>
</ul>
</li>
</ul>
</li>
<li><p><code>ADD &lt;source&gt; &lt;destination&gt;</code></p>
</li>
</ol>
<ul>
<li><p>The ADD command specifies a file or directory that will be copied into the container at runtime.</p>
</li>
<li><p>Eg: <code>ADD /home/user/file.txt /home/user/file.txt</code></p>
<ul>
<li>In this case, the Dockerfile will copy the file.txt from the host to the container.</li>
</ul>
</li>
</ul>
<ol>
<li><code>COPY &lt;source&gt; &lt;destination&gt;</code></li>
</ol>
<ul>
<li><p>The COPY command specifies a file or directory that will be copied into the container at runtime.</p>
</li>
<li><p>Eg: <code>COPY /home/user/file.txt /home/user/file.txt</code></p>
<ul>
<li>In this case, the Dockerfile will copy the file.txt from the host to the container.</li>
</ul>
</li>
</ul>
<blockquote>
<p>COPY only supports the basic copying of local files into the container, while ADD has some features (like local-only tar extraction and remote URL support) that are not immediately obvious. Consequently, the best use for ADD is local tar file auto-extraction into the image, as in ADD rootfs.</p>
</blockquote>
<h3 id="heading-example-lint-python-code-from-a-repository">Example - Lint Python Code from a Repository</h3>
<pre><code class="lang-shell">FROM ubuntu:latest

WORKDIR /workspace


RUN apt-get update &amp;&amp; apt-get install -y \
    git python3-pip

RUN git clone https://github.com/theArjun/python-codes 
RUN pip3 install pylint
RUN pylint python-codes
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Model Anti-patterns in Django]]></title><description><![CDATA[Hello pals,While working with Django, we all write code that does the job, but some code may be performing excessive computations or operations that we are unaware of. These operations may be ineffective and/or counterproductive in practice.
Here, I ...]]></description><link>https://arjun.name.np/model-anti-patterns-in-django</link><guid isPermaLink="true">https://arjun.name.np/model-anti-patterns-in-django</guid><category><![CDATA[optimization]]></category><category><![CDATA[patterns]]></category><category><![CDATA[orm]]></category><category><![CDATA[djagno]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Fri, 24 Mar 2023 19:41:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679686852628/0ee26ac2-7b90-41f7-b798-d8d1d3aefc88.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello pals,<br />While working with Django, we all write code that does the job, but some code may be performing excessive computations or operations that we are unaware of. These operations may be ineffective and/or counterproductive in practice.</p>
<p>Here, I am going to mention some anti-patterns in Django models.</p>
<ol>
<li><p><strong>Using</strong> <code>len(queryset)</code> instead of <code>queryset.count()</code></p>
<ul>
<li><p>The queryset in Django are lazily evaluated which means that records in database aren’t read from database until we interact with the data.</p>
</li>
<li><p><code>len(queryset)</code> performs the count of database records by Python interpreter in application level. For doing so, all the records should be fetched from the database at first, which is computationally heavy operation.<br />  Whereas, <code>queryset.count()</code> calculates the count at the database level and just returns the count.</p>
</li>
</ul>
</li>
</ol>
<p>    For a model <code>Post</code> :</p>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
        author = models.CharField(max_length=<span class="hljs-number">100</span>)
        title = models.CharField(max_length=<span class="hljs-number">200</span>)
        content = models.TextField()
</code></pre>
<p>    If we use <code>len(queryset)</code>, it handles the calculation like <code>SELECT * FROM post</code> which returns a list of records (queryset) and then python interpreter calculates the length of queryset which is similar to list data structure. Imagine the waste in downloading many records only to check the length and throw them away at the end! But, if we need the records after reading the length, then <code>len(queryset)</code> can be valid.</p>
<p>    If we use <code>queryset.count()</code>, it handles the calculation like <code>SELECT COUNT(*) FROM post</code> at database level. It makes the code execution quicker and improves database performance.</p>
<ol>
<li><p><strong>Using</strong> <code>queryset.count()</code> instead of <code>queryset.exists()</code></p>
<ul>
<li>While we kept praising the use of <code>queryset.count()</code> to check the length of a queryset, using it may be performance heavy if we want to check the existence of the queryset.<br />  For the same model <code>Post</code>, when we want to check if there are any post written by author <code>Arjun</code>, we may do something like:</li>
</ul>
</li>
</ol>
<pre><code class="lang-python">    posts_by_arjun: Queryset = Post.objects.filter(author__iexact=<span class="hljs-string">'Arjun'</span>)

    <span class="hljs-keyword">if</span> posts_by_arjun.count() &gt; <span class="hljs-number">0</span>:
        print(<span class="hljs-string">'Arjun writes posts here.'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'Arjun doesnt write posts here.)</span>
</code></pre>
<p>    The posts_by_arjun.count() performs an SQL operation that scans every row in a database table. But, if we are just interested in <code>If Arjun writes posts here or not ?</code> then, more efficient code will be:</p>
<pre><code class="lang-python">    posts_by_arjun: Queryset = Post.objects.filter(author__iexact=<span class="hljs-string">'Arjun'</span>)

    <span class="hljs-keyword">if</span> posts_by_arjun.exists():
        print(<span class="hljs-string">'Arjun writes posts here.'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'Arjun doesnt write posts here.)</span>
</code></pre>
<p>    <code>posts_by_arjun.exists()</code> returns a bool expression that finds out if at least one result exists or not. It simply reads a single record in the most optimized way (removing ordering, clearing any user-defined <code>select_related()</code> or <code>distinct()</code> methods.)</p>
<p>    Also, checking existence / truthiness of queryset like this is inefficient.</p>
<pre><code class="lang-python">    posts_by_arjun: Queryset = Post.objects.filter(author__iexact=<span class="hljs-string">'Arjun'</span>)

    <span class="hljs-keyword">if</span> posts_by_arjun:
        print(<span class="hljs-string">'Arjun writes posts here.'</span>)
    <span class="hljs-keyword">else</span>:
        print(<span class="hljs-string">'Arjun doesnt write posts here.)</span>
</code></pre>
<p>    This does the fine job in checking if there are any posts by Arjun or not but is computationally heavy for larger no of records. Hence, use of <code>queryset.exists()</code> is encouraged for checking existence / truthiness of querysets.</p>
<ol>
<li><p><strong>Using</strong> <code>signals</code> excessively</p>
<ul>
<li><p>Django signals are great for triggering jobs based on events. But it has some valid cases, and they shouldn’t be used excessively. Think of any alternative for signals within your codebase, brainstorm on its substitution and try to place signals logic in your models itself, if possible.</p>
</li>
<li><p>They are not executed asynchronously. There is no background thread or worker to execute them. If you want some background worker to do your job for you, try using <code>celery</code>.</p>
</li>
<li><p>As signals are spread over separate files if you’re working on a larger project, they can be harder to trace for someone who is a fresh joiner to the company and that’s not great. Although, <code>django-debug-toolbar</code> does some help in tracing the triggered signals.</p>
</li>
</ul>
</li>
</ol>
<p>    Let’s create a scenario where we want to keep the record of <code>Post</code> writings in a separate model <code>PostWritings</code>.</p>
<pre><code class="lang-python">    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostWritings</span>(<span class="hljs-params">models.Model</span>):</span>
        author = models.CharField(max_length=<span class="hljs-number">100</span>, unique=<span class="hljs-literal">True</span>)
        posts_written = models.PositiveIntegerField(default=<span class="hljs-number">0</span>)
</code></pre>
<p>    If we want to automatically update the <code>PostWritings</code> record for a use based on records created on <code>Post</code> model, there are ways to achieve the task with / without signals.</p>
<p>    A. With Signals</p>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.db.models.signals <span class="hljs-keyword">import</span> post_save
    <span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> F
    <span class="hljs-keyword">from</span> django.dispatch <span class="hljs-keyword">import</span> receiver
    <span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post

<span class="hljs-meta">    @receiver(sender=Post, post_save)</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">post_writing_handler</span>(<span class="hljs-params">sender, instance, created, **kwargs</span>):</span>
    <span class="hljs-keyword">if</span> created:
        writing, created = PostWritings.objects.get_or_create(author=instance.author)
        writing.update(posts_written=F(<span class="hljs-string">'posts_written'</span>) + <span class="hljs-number">1</span>)
</code></pre>
<p>    B. Without Signals</p>
<p>    We need to override the <code>save()</code> method for <code>Post</code> model.</p>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
    <span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> F

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
        author = models.CharField(max_length=<span class="hljs-number">100</span>)
        title = models.CharField(max_length=<span class="hljs-number">200</span>)
        content = models.TextField()

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs:
            <span class="hljs-comment"># Overridden method.</span>
            author = self.author
            if self.id:
                writing, created = PostWritings.objects.get_or_create(<span class="hljs-params">author=author</span>)
                writing.update(<span class="hljs-params">posts_written=F(<span class="hljs-params"><span class="hljs-string">'posts_written'</span></span>) + <span class="hljs-number">1</span></span>)
            super(<span class="hljs-params">Post, self</span>).save(<span class="hljs-params">*args, **kwargs</span>)</span></span>
</code></pre>
<p>    As the same job can be accomplished without signals, the code can be easily traced and prevent unnecessary event triggers.<br />    If someone feels about not having readability on <code>save()</code> method here, breaking up code is always great. Let’s do that.</p>
<pre><code class="lang-python">    <span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
    <span class="hljs-keyword">from</span> django.db.models <span class="hljs-keyword">import</span> F

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
        author = models.CharField(max_length=<span class="hljs-number">100</span>)
        title = models.CharField(max_length=<span class="hljs-number">200</span>)
        content = models.TextField()

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">_update_post_writing</span>(<span class="hljs-params">self, created=False, author=None</span>):</span>
            <span class="hljs-keyword">if</span> author <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> <span class="hljs-literal">None</span> <span class="hljs-keyword">and</span> craeted:
                writing, created = PostWritings.objects.get_or_create(author=author)
                writing.update(posts_written=F(<span class="hljs-string">'posts_written'</span>) + <span class="hljs-number">1</span>)

        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">save</span>(<span class="hljs-params">self, *args, **kwargs:
            <span class="hljs-comment"># Overridden method.</span>
            author = self.author
            created = self.id is None
            super(<span class="hljs-params">Post, self</span>).save(<span class="hljs-params">*args, **kwargs</span>)
            self._update_post_writing(<span class="hljs-params">created, author</span>)</span></span>
</code></pre>
<ol>
<li><p><strong>Not defining an</strong> <code>__str__</code> method for a model</p>
<p> When you define a model, it is important to create a string representation of that model so that it can be displayed accurately. If the <code>__str__</code> method is not defined, then it will not be possible to access the model and display it within the user interface correctly.</p>
</li>
<li><p><strong>Not using the built-in ModelForm validation</strong></p>
<p> Using the built-in ModelForm validation can help to ensure that the data being entered into the form is valid. This is useful for form validation, preventing invalid data from being entered and ensuring that forms are processed correctly.</p>
</li>
<li><p><strong>Having complex relationships or calculations within your model</strong></p>
<p> Models should not contain too much complexity as this can lead to them becoming difficult to maintain. Keeping the relationships and any calculations within the model to a minimum helps to keep things organized and makes it easier to debug any potential issues.</p>
</li>
<li><p><strong>Not using</strong> <code>get_or_create</code> or <code>bulk_create</code></p>
<p> When creating large numbers of objects - When creating large numbers of objects, it is important to use the <code>get_or_create</code> or <code>bulk_create</code> methods rather than creating them one at a time. This can help to make the process faster and more efficient by avoiding unnecessary extra steps.</p>
</li>
<li><p><strong>Ignoring the</strong> <code>unique_together</code> or <code>unique_for_date</code> fields</p>
<p> When creating model instances - It is important to pay attention to the <code>unique_together</code> and <code>unique_for_date</code> fields when creating model instances, as they are used to ensure that data is unique and consistent. Failing to take these fields into account can lead to duplicate data being written to the database.</p>
</li>
</ol>
<p>We appear to have learned how to mitigate some Django Model Anti Patterns. For now, thank you everyone for having me here. I'll be back with more Django-related content soon. You can also find me on <a target="_blank" href="https://github.com/thearjun/">GitHub</a>. Till then <code>keep coding :)</code></p>
]]></content:encoded></item><item><title><![CDATA[Style Django Admin with Jazzmin]]></title><description><![CDATA[Hello Geeks, First of all, I would like to thank you for reaching here. You will undoubtedly be a successful Django developer in the future.
Introduction
In this blog, I am guiding to integrate django-jazzmin theme to the Django project. According to...]]></description><link>https://arjun.name.np/style-django-admin-with-jazzmin</link><guid isPermaLink="true">https://arjun.name.np/style-django-admin-with-jazzmin</guid><category><![CDATA[Django]]></category><category><![CDATA[admin]]></category><category><![CDATA[style]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Fri, 24 Mar 2023 19:38:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679686692881/49416490-6aa1-4f9e-8970-4b220729ff53.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello Geeks, First of all, I would like to thank you for reaching here. You will undoubtedly be a successful Django developer in the future.</p>
<h2 id="heading-introduction">Introduction</h2>
<p>In this blog, I am guiding to integrate <code>django-jazzmin</code> theme to the Django project. According to their <a target="_blank" href="https://django-jazzmin.readthedocs.io/">documentation</a> :</p>
<blockquote>
<p>Django Jazzmin is intended as a drop-in app to jazz up your Django admin site, with plenty of things you can easily customise, including a built-in UI customizer.</p>
</blockquote>
<p>The default admin dashboard provided by Django isn’t best fitted for our need every time and we need to customize a lot to match the theme with our need. And some of us may not prefer to go with the default theme which looks like this :</p>
<p><img src="https://i.imgur.com/pRGyc5T.png" alt="question.png" /></p>
<p>For the developers who want to get a customized and better-looking admin dashboard for Django, <code>django-jazzmin</code> is the one with better UI components with features like :</p>
<ul>
<li><p>Drop-in admin skin, all configuration optional</p>
</li>
<li><p>Select2 drop-downs</p>
</li>
<li><p>Bootstrap 4 &amp; AdminLTE UI components</p>
</li>
<li><p>Search bar for any given model admin</p>
</li>
<li><p>Modal windows instead of popups</p>
</li>
<li><p>Customisable side menu</p>
</li>
<li><p>Customisable top menu</p>
</li>
<li><p>Customisable user menu</p>
</li>
<li><p>Responsive</p>
</li>
<li><p>Customisable UI (via Live UI changes, or custom CSS/JS)</p>
</li>
<li><p>Based on the latest adminlte + bootstrap</p>
</li>
</ul>
<p>which looks like this:</p>
<p><img src="https://i.imgur.com/gP87rSk.png" alt="list_view.png" /></p>
<p>To achieve a good looking AdminLTE dashboard on our Django project, we need to follow a sequence of instructions.</p>
<h2 id="heading-instructions">Instructions</h2>
<p>Navigate to your workspace:</p>
<pre><code class="lang-plaintext"># Terminal
# =========

$ mkdir - ~/workspace/integrate-django-jazzmin
$ cd ~/workspace/integrate-django-jazzmin
</code></pre>
<h3 id="heading-setup-virtual-environment-optional">Setup Virtual Environment (Optional)</h3>
<pre><code class="lang-plaintext"># Terminal
# =========

$ python -m virtualenv venv

created virtual environment CPython3.8.6.final.0-64 in 116ms
  creator CPython3Posix(dest=/home/ubuntu/workspace/integrate-django-jazzmin/venv, clear=False, global=False)
  seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=/home/ubuntu/.local/share/virtualenv)
    added seed packages: pip==20.2.4, setuptools==50.3.2, wheel==0.35.1
  activators BashActivator,CShellActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator
</code></pre>
<p>This will set up a virtualenv named <code>venv</code> which isolates libraries and dependencies from the global installation. Now, activate the virtual environment.</p>
<pre><code class="lang-plaintext">$ source venv/bin/activate
</code></pre>
<h3 id="heading-installing-libraries">Installing libraries</h3>
<p>Now, we are good to install the libraries we need to set up the Django project.</p>
<pre><code class="lang-plaintext">$ pip install django django-jazzmin
</code></pre>
<p>This will install the <code>django</code> and <code>django-jazzmin</code> library.</p>
<h3 id="heading-create-django-project">Create Django Project</h3>
<p>It’s time to create a Django project.</p>
<pre><code class="lang-plaintext">$ django-admin startproject dj_jazzmin_demo .
</code></pre>
<p>For a better demonstration of the theme, I’m going to create a Django app named <code>blog</code>.</p>
<pre><code class="lang-plaintext">$ python manage.py startapp blog
</code></pre>
<p>which created directory structure like this:</p>
<pre><code class="lang-plaintext"># Directory Structure
# ====================
.
├── blog
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── dj_jazzmin_demo
│   ├── asgi.py
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-36.pyc
│   │   └── settings.cpython-36.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── manage.py
</code></pre>
<h3 id="heading-register-apps">Register Apps</h3>
<p>Now, let’s register the <code>blog</code> app inside <code>INSTALLED_APPS</code> in <a target="_blank" href="http://settings.py"><code>settings.py</code></a>. Add <code>blog.apps.BlogConfig</code> after the pre-registered django apps. Also, we are good to add our theme to the django project. For that, register <code>jazzmin</code> theme to <code>INSTALLED_APPS</code>. But, we’re registering <code>jazzmin</code> on the top of other pre-registered apps because we want the theme to load earlier than other apps.</p>
<pre><code class="lang-python"><span class="hljs-comment"># dj_jazzmin_demo/settings.py</span>
<span class="hljs-comment"># =============================</span>

INSTALLED_APPS = [
    <span class="hljs-comment"># Pre-loading Third Party apps</span>
    <span class="hljs-string">'jazzmin'</span>, 

    <span class="hljs-string">'django.contrib.admin'</span>,
    <span class="hljs-string">'django.contrib.auth'</span>,
    <span class="hljs-string">'django.contrib.contenttypes'</span>,
    <span class="hljs-string">'django.contrib.sessions'</span>,
    <span class="hljs-string">'django.contrib.messages'</span>,
    <span class="hljs-string">'django.contrib.staticfiles'</span>,

    <span class="hljs-comment"># Local Apps</span>
    <span class="hljs-string">'blog.apps.BlogConfig'</span>,

]
</code></pre>
<h3 id="heading-create-model-and-modeladmin">Create Model and ModelAdmin</h3>
<p>Now, we have our app and theme registered in our project. Then, we can write models for the app <code>blog</code>. Let’s write a model named <code>Post</code> in <a target="_blank" href="http://models.py"><code>models.py</code></a> inside <code>blog</code> app.</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/models.py</span>
<span class="hljs-comment"># ================</span>

<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
<span class="hljs-keyword">from</span> django.utils.translation <span class="hljs-keyword">import</span> ugettext_lazy <span class="hljs-keyword">as</span> _

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Post</span>(<span class="hljs-params">models.Model</span>):</span>
    <span class="hljs-string">'''Model definition for Post.'''</span>

    title = models.CharField(_(<span class="hljs-string">'Post'</span>), max_length=<span class="hljs-number">50</span>)
    content = models.TextField(_(<span class="hljs-string">'Content'</span>))
    is_publishable = models.BooleanField(_(<span class="hljs-string">'Is Publishable ?'</span>), default=<span class="hljs-literal">False</span>)
    created_at = models.DateTimeField(_(<span class="hljs-string">'Created at '</span>),auto_now_add=<span class="hljs-literal">True</span>)
    updated_at = models.DateTimeField(_(<span class="hljs-string">'Updated at '</span>),auto_now=<span class="hljs-literal">True</span>)

    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Meta</span>:</span>
        <span class="hljs-string">'''Meta definition for Post.'''</span>

        verbose_name = <span class="hljs-string">'Post'</span>
        verbose_name_plural = <span class="hljs-string">'Posts'</span>

    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-string">'''Unicode representation of Post.'''</span>
        <span class="hljs-keyword">return</span> self.title
</code></pre>
<p>For making our app accessible via the admin dashboard, we’re going to register the model <code>Post</code> in <a target="_blank" href="http://admin.py"><code>admin.py</code></a>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/admin.py</span>
<span class="hljs-comment"># ==============</span>

<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Post


<span class="hljs-meta">@admin.register(Post)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">PostAdmin</span>(<span class="hljs-params">admin.ModelAdmin</span>):</span>
    <span class="hljs-string">'''Admin View for Post'''</span>

    list_display = (
        <span class="hljs-string">'title'</span>,
        <span class="hljs-string">'is_publishable'</span>,
        <span class="hljs-string">'created_at'</span>,
        <span class="hljs-string">'updated_at'</span>,
    )
    list_filter = (
        <span class="hljs-string">'is_publishable'</span>,
        <span class="hljs-string">'created_at'</span>,
        <span class="hljs-string">'updated_at'</span>,
    )
</code></pre>
<h3 id="heading-make-migrations-and-migrate-models">Make Migrations and Migrate Models</h3>
<p>Now, we’re good to make migrations and migrate the model we created.</p>
<pre><code class="lang-plaintext"># Terminal
# =========

$ python manage.py makemigrations blog
Migrations for 'blog':
  blog/migrations/0001_initial.py
    - Create model Post
</code></pre>
<pre><code class="lang-plaintext"># Terminal
# =========

$ python manage.py migrate
Operations to perform:
  Apply all migrations: admin, auth, blog, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying auth.0010_alter_group_name_max_length... OK
  Applying auth.0011_update_proxy_permissions... OK
  Applying auth.0012_alter_user_first_name_max_length... OK
  Applying blog.0001_initial... OK
  Applying sessions.0001_initial... OK
</code></pre>
<p>For accessing the admin panel, we need to create a superuser which has the privilege to access the admin dashboard and perform operations over there.</p>
<pre><code class="lang-plaintext"># Terminal
# =========

$ python manage.py createsuperuser
Username (leave blank to use 'ubuntu'): ubuntu
Email address: 
Password: 
Password (again): 
Superuser created successfully.
</code></pre>
<h3 id="heading-enjoy-the-output">Enjoy the output</h3>
<p>Finally, we’ve completed the procedure to create a basic Django project and integrate <code>django-jazzmin</code> theme. Now, we can run our django project.</p>
<pre><code class="lang-plaintext"># Terminal
# =========

$ python manage.py runserver

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
November 13, 2020 - 19:46:51
Django version 3.1.3, using settings 'dj_jazzmin_demo.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C
</code></pre>
<p>We have our Django project running. To access it through a web browser, visit the URL <a target="_blank" href="http://127.0.0.1:8000/admin/"><code>http://127.0.0.1:8000/admin/</code></a> on a web browser. It loads to a different login interface than default login UI provided by Django.</p>
<p><img src="https://i.imgur.com/vUauSfL.png" alt="Screenshot from 2020-11-14 01-35-56.png" /></p>
<p>After entering credentials, we’re navigated to a jazzy looking admin interface provided by <code>django-jazzmin</code>.</p>
<p><img src="https://i.imgur.com/HFqmUxu.png" alt="Screenshot from 2020-11-14 01-39-00.png" /></p>
<p>For now, we’ve successfully integrated <code>django-jazzmin</code> theme to our django_project.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Implement Autocompletion in Django]]></title><description><![CDATA[Hello pals,
In this blog, I'll show you how to add autocomplete to the Django admin interface. I chose the admin interface because it lets me create, read, update, and delete (CREATE, READ, UPDATE, DELETE) models.
For implementing the auto completion...]]></description><link>https://arjun.name.np/implement-autocompletion-in-django</link><guid isPermaLink="true">https://arjun.name.np/implement-autocompletion-in-django</guid><category><![CDATA[Django]]></category><category><![CDATA[auto-complete]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Fri, 24 Mar 2023 19:32:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679686395646/e12224f1-df24-4372-bc77-2e41a3827d3a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello pals,</p>
<p>In this blog, I'll show you how to add autocomplete to the Django admin interface. I chose the admin interface because it lets me create, read, update, and delete (CREATE, READ, UPDATE, DELETE) models.</p>
<p>For implementing the auto completion feature, I am going to use <code>django-ajax-selects</code> currently maintained by <a target="_blank" href="https://github.com/crucialfelix">crucialfelix</a>.</p>
<h2 id="heading-setup">Setup</h2>
<p>Let's begin by making a Django project. First of all, I’ll create a virtual environment <code>.venv</code>. You can create a virtual environment just by <code>python -m venv .venv</code>. Let’s activate the virtual environment <code>.venv\Scripts\activate</code> as I am currently on Windows.</p>
<p>After that, install <code>django</code> and <code>django-ajax-selects</code> using pip.</p>
<pre><code class="lang-plaintext">pip install django django-ajax-selects
</code></pre>
<p>Following installing libraries, let’s create django project named <code>autocomplete_demo_project</code>.</p>
<pre><code class="lang-plaintext">django-admin startproject autocomplete_demo_project
</code></pre>
<p>Subsequently, Let’s create a django app named <code>blog</code> .</p>
<pre><code class="lang-plaintext">python manage.py startapp blog
</code></pre>
<p>And register the app <code>'blog'</code> and <code>'ajax_select'</code> in <code>INSTALLED_APPS</code> inside <a target="_blank" href="http://settings.py"><code>settings.py</code></a>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># autocomplete_demo_project/settings.py</span>
INSTALLED_APPS  = [
    <span class="hljs-string">'django.contrib.admin'</span>,
    <span class="hljs-string">'django.contrib.auth'</span>,
    <span class="hljs-string">'django.contrib.contenttypes'</span>,
    <span class="hljs-string">'django.contrib.sessions'</span>,
    <span class="hljs-string">'django.contrib.messages'</span>,
    <span class="hljs-string">'django.contrib.staticfiles'</span>,
    <span class="hljs-string">'ajax_select'</span>, <span class="hljs-comment"># new apps</span>
    <span class="hljs-string">'blog.apps.BlogConfig'</span>,
]
</code></pre>
<p>Thereafter, let’s define URLConfs for <code>ajax_select</code> so it may load the necessary javascripts, stylesheets for autocompletion.</p>
<pre><code class="lang-python"><span class="hljs-comment"># autocomplete_demo_project/urls.py</span>
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin
<span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path, include
<span class="hljs-keyword">from</span> django.conf <span class="hljs-keyword">import</span> settings
<span class="hljs-keyword">from</span> django.conf.urls.static <span class="hljs-keyword">import</span> static
<span class="hljs-keyword">from</span> ajax_select <span class="hljs-keyword">import</span> urls <span class="hljs-keyword">as</span> ajax_select_urls

urlpatterns = [
    path(<span class="hljs-string">'ajax_select/'</span>, include(ajax_select_urls)),
    path(<span class="hljs-string">'admin/'</span>, admin.site.urls),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
</code></pre>
<h2 id="heading-models-and-lookups">Models and Lookups</h2>
<p>We have to start by defining models which will later be used for observing auto-completion in admin panel. Without adding any complexity, I’ll just start with a single field <code>name</code> in Blog model.</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/models.py</span>
<span class="hljs-keyword">from</span> django.db <span class="hljs-keyword">import</span> models
<span class="hljs-keyword">from</span> django.utils.translation <span class="hljs-keyword">import</span> gettext_lazy <span class="hljs-keyword">as</span> _

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Blog</span>(<span class="hljs-params">models.Model</span>):</span>
    name = models.CharField(_(<span class="hljs-string">"Blog"</span>), max_length=<span class="hljs-number">50</span>)

<span class="hljs-function"><span class="hljs-keyword">def</span>  <span class="hljs-title">__str__</span>(<span class="hljs-params">self</span>):</span>
    <span class="hljs-keyword">return</span>  self.name
</code></pre>
<p>Let’s also create a lookup for the field <code>name</code> which fetches the most suitable result by matching the query entered while entering a record in admin panel. For doing so, let’s create LookupChannel for our field <code>name</code> (<code>NameLookup</code>) in <a target="_blank" href="http://lookup.py"><code>lookup.py</code></a> inside <code>blog</code> app directory.</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/lookups.py</span>
<span class="hljs-keyword">from</span> ajax_select <span class="hljs-keyword">import</span> register, LookupChannel

<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Blog

<span class="hljs-meta">@register('names')</span>
<span class="hljs-class"><span class="hljs-keyword">class</span>  <span class="hljs-title">NameLookup</span>(<span class="hljs-params">LookupChannel</span>):</span>
    model = Blog

    <span class="hljs-function"><span class="hljs-keyword">def</span>  <span class="hljs-title">get_query</span>(<span class="hljs-params">self, q, request</span>):</span>
        <span class="hljs-keyword">return</span>  self.model.objects.filter(name__icontains=q).order_by(<span class="hljs-string">'name'</span>)[:<span class="hljs-number">50</span>]

    <span class="hljs-function"><span class="hljs-keyword">def</span>  <span class="hljs-title">format_item_display</span>(<span class="hljs-params">self, item</span>):</span>
        <span class="hljs-keyword">return</span>  <span class="hljs-string">u"&lt;span class='blog_name'&gt;%s&lt;/span&gt;"</span>  % item.name
</code></pre>
<p>Here, we’ve observed two methods inside our <code>NameLookup</code> class. Let’s dig into both of them:</p>
<ol>
<li><p><code>get_query</code> method takes <code>q</code> parameter as query which will be used to filter the record in database. Here, we’ve used the <code>name__icontains</code> approach which will filter the matched records in DB with sub string query <code>q</code> and return the filtered records. We may also proceed with <code>name__startswith</code> approach which only tries to match the starting string with the records in DB with sub string query <code>q</code> and return the filtered records. But, let’s just stick into one approach ( <code>name__icontains</code> approach) to implement the auto completion.</p>
</li>
<li><p><code>format_item_display</code> methods takes each filtered records and <a target="_blank" href="http://displaysblog.name">displays<code>blog.name</code></a> (data) which is the need in our case with proper styling. We can override the display properties to make it look better and match with our preferences.</p>
</li>
</ol>
<p>Also notice that we’ve registered a lookup name <code>names</code> with <code>register</code> decorator which will later be used with form to match with required form field i.e. The form field with the property <code>names</code> will match with the above lookup.</p>
<h2 id="heading-modeladmin-and-forms">ModelAdmin and Forms</h2>
<p>Ensuing step will be to create Django forms which will be provided as property to our ModelAdmin which we’ll later create in <a target="_blank" href="http://admin.py"><code>admin.py</code></a> .</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/forms.py</span>
<span class="hljs-keyword">from</span> ajax_select.fields <span class="hljs-keyword">import</span> AutoCompleteField
<span class="hljs-keyword">from</span> django <span class="hljs-keyword">import</span> forms

<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Blog

<span class="hljs-class"><span class="hljs-keyword">class</span>  <span class="hljs-title">BlogForm</span>(<span class="hljs-params">forms.ModelForm</span>):</span>

    name = AutoCompleteField(<span class="hljs-string">'names'</span>)
    <span class="hljs-class"><span class="hljs-keyword">class</span>  <span class="hljs-title">Meta</span>:</span>
        model = Blog
        fields = [
            <span class="hljs-string">'name'</span>
        ]
</code></pre>
<p>It’s worth noticing that the field name is an <code>AutoCompleteField</code> with the property <code>names</code> which is a lookup name we’ve registered in <code>NameLookup</code> class inside <code>blog/lookups.py</code>. It’s how we interlink forms and lookups using <code>django-ajax-selects.</code></p>
<p>Following this, let’s create <code>ModelAdmin</code> inside <a target="_blank" href="http://admin.py"><code>admin.py</code></a>.</p>
<pre><code class="lang-python"><span class="hljs-comment"># blog/admin.py</span>
<span class="hljs-keyword">from</span> ajax_select.admin <span class="hljs-keyword">import</span> AjaxSelectAdmin
<span class="hljs-keyword">from</span> django.contrib <span class="hljs-keyword">import</span> admin

<span class="hljs-keyword">from</span> .forms <span class="hljs-keyword">import</span> BlogForm
<span class="hljs-keyword">from</span> .models <span class="hljs-keyword">import</span> Blog

<span class="hljs-meta">@admin.register(Blog)</span>
<span class="hljs-class"><span class="hljs-keyword">class</span>  <span class="hljs-title">BlogAdmin</span>(<span class="hljs-params">AjaxSelectAdmin</span>):</span>

    form = BlogForm
</code></pre>
<p>What we’ve done here is overriding the default <code>form</code> property provided by Django Admin and get it replaced by our <code>BlogForm</code> form object.</p>
<p>Also note that, the use of <code>BlogForm</code> isn’t limited to ModelAdmin for auto completion. It can also be used in used defined templates by passing <code>form</code> inside <code>context</code> parameter from <a target="_blank" href="http://views.py"><code>views.py</code></a>. For doing so,</p>
<pre><code class="lang-html">{{ form.media }}
{{ form }}
</code></pre>
<p>We need to load <code>((</code><a target="_blank" href="http://form.media"><code>form.media</code></a><code>}}</code> to load the necessary JS and CSS files defined by <code>ajax_selects</code> app.</p>
<h2 id="heading-observation">Observation</h2>
<p>After defining lookups, models, forms and modeladmin, now we can make migrations and run the migration files.<br /><code>python</code> <a target="_blank" href="http://manage.py"><code>manage.py</code></a> <code>makemigrations blog</code></p>
<p>Post hoc, let’s run those migration files.<br /><code>python</code> <a target="_blank" href="http://manage.py"><code>manage.py</code></a> <code>migrate</code></p>
<p>Then, create a superuser for accessing admin interface,<br /><code>python</code> <a target="_blank" href="http://manage.py"><code>manage.py</code></a> <code>createsuperuser</code></p>
<p>Then, log into <code>127.0.0.1:8000/admin</code> to access admin interface and navigate to <code>Blog</code> model.</p>
<p>Try adding some records and you’ll notice auto completion making work easy for you.</p>
<h3 id="heading-demo">Demo</h3>
<p>I’ve added some records in my models.</p>
<p><img src="https://i.imgur.com/MOTFNvP.png" alt="Added Records" /></p>
<p>Let’s try to add another record to observe auto-completion.</p>
<p><img src="https://i.imgur.com/fjoYRXx.png" alt="Autcompletion Demo" /></p>
<p>Notice that, when I am typing <code>A</code>, the records with the letter <code>A</code> in their name appeared as a dropdown so the user may autocomplete the record.</p>
<p>Thank you for reading.</p>
]]></content:encoded></item><item><title><![CDATA[Download required folder only from GitHub]]></title><description><![CDATA[Hello pals, We've all been in a situation where we needed to download a folder from GitHub but were forced to clone an entire large repository before we could access the required folder. Well, there's no more reason to fear or worry about these situa...]]></description><link>https://arjun.name.np/download-required-folder-only-from-github</link><guid isPermaLink="true">https://arjun.name.np/download-required-folder-only-from-github</guid><category><![CDATA[Git]]></category><dc:creator><![CDATA[Arjun Adhikari]]></dc:creator><pubDate>Fri, 24 Mar 2023 19:27:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1679686012141/d0dda8ca-beea-49aa-b04f-e2f0d3771e1c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Hello pals, We've all been in a situation where we needed to download a folder from GitHub but were forced to clone an entire large repository before we could access the required folder. Well, there's no more reason to fear or worry about these situations. This blog tutorial will show you how to download only the required folder from GitHub without cloning the entire repository.</p>
<h2 id="heading-navigate-the-repository-and-directory-you-want">Navigate the repository and directory you want</h2>
<p>First of all, navigate to the repository from which you want to access the folder. Here, I am taking my <a target="_blank" href="https://github.com/theArjun/machine-learning">Machine Learning</a> repository as an example.</p>
<p><img src="https://i.ibb.co/W3c5Gd1/image.png" alt="ML Repo" /></p>
<p>Then, I am navigating to the directory named <code>data-visualization</code> which I want to download. Then copy the URL from the browser address bar which is <a target="_blank" href="https://github.com/theArjun/machine-learning/tree/master/data-visualization">https://github.com/theArjun/machine-learning/tree/master/data-visualization</a> in my case. Note this or get it stored in the clipboard.</p>
<p><img src="https://i.ibb.co/WB5XBGf/image.png" alt="Data Visualization Repo" /></p>
<h2 id="heading-install-subversion">Install Subversion</h2>
<p>I am using <code>subversion</code> to download the required directory. Make sure you have it installed on your system before proceeding.<br /><code>apt-get install subversion</code></p>
<h2 id="heading-tweak-url">Tweak URL</h2>
<p>I hope you’ve noted the directory URL from GitHub or got it stored on your clipboard, which was <a target="_blank" href="https://github.com/theArjun/machine-learning/tree/master/data-visualization">https://github.com/theArjun/machine-learning/tree/master/data-visualization</a> in my case. Now replace the <code>tree/master</code> with <code>trunk</code> which results in <a target="_blank" href="https://github.com/theArjun/machine-learning/trunk/data-visualization">https://github.com/theArjun/machine-learning/trunk/data-visualization</a> and note it again. Good going, pals, We’re now at the final stage.</p>
<h2 id="heading-download-the-directory">Download the Directory</h2>
<p>Launch the terminal and type the following command:<br /><code>svn checkout</code> <a target="_blank" href="https://github.com/theArjun/machine-learning/trunk/data-visualization"><code>https://github.com/theArjun/machine-learning/trunk/data-visualization</code></a></p>
<p>The URL was the tweaked URL that I instructed in the Tweak URL section. The execution of the command looks like the following in the terminal.</p>
<pre><code class="lang-shell">$ svn checkout https://github.com/theArjun/machine-learning/trunk/data-visualization

A    data-visualization/Data Generation - Classification.ipynb
A    data-visualization/Data Generation - Regression Data.ipynb
A    data-visualization/Data Normalization and Standardization.ipynb
A    data-visualization/Data Visualization - Subplots.ipynb
A    data-visualization/Exploring Sklearn Datasets.ipynb
A    data-visualization/Generating Data using Sk-Learn.ipynb
A    data-visualization/Matplotlib Basics.ipynb
A    data-visualization/Multivariate Normal Distribution  .ipynb
A    data-visualization/Normal Distribution &amp; Histogram.ipynb
A    data-visualization/Numeric Spacing.ipynb
A    data-visualization/PyCharts, BarCharts and Legends.ipynb
A    data-visualization/Template.ipynb
A    data-visualization/Working with Pandas - MNIST Dataset.ipynb
A    data-visualization/Working with Pandas.ipynb
A    data-visualization/csv
A    data-visualization/csv/linearX.csv
A    data-visualization/csv/linearY.csv
A    data-visualization/csv/movie_data.csv
Checked out revision 103.
</code></pre>
<p>and a directory named data-visualization gets created in the working folder.</p>
<pre><code class="lang-shell">$ ls

data-visualization
</code></pre>
<p>This folder contains all the files that are in the <code>data-visualization</code> folder on GitHub, i.e., files that are synced with the remote (GitHub).</p>
<p>So, no worries, create as many folders as you need and download them as required without cloning the whole bulky repository.</p>
<p>Thanks for reading.</p>
]]></content:encoded></item></channel></rss>