<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Saurabh Pandey on Medium]]></title>
        <description><![CDATA[Stories by Saurabh Pandey on Medium]]></description>
        <link>https://medium.com/@dextrop?source=rss-2aabcad7f5ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dcnO0KMmMSxlck1I37FCCg.jpeg</url>
            <title>Stories by Saurabh Pandey on Medium</title>
            <link>https://medium.com/@dextrop?source=rss-2aabcad7f5ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:01:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dextrop/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[My Lazy Secret to Cleaner Code: Python Decorators]]></title>
            <link>https://blog.devgenius.io/my-lazy-secret-to-cleaner-code-python-decorators-d43d673a1ba2?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/d43d673a1ba2</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[logging]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 11:05:12 GMT</pubDate>
            <atom:updated>2025-07-01T17:12:22.555Z</atom:updated>
            <content:encoded><![CDATA[<p>I kept copy-pasting the same code again and again mostly for things like validation &amp; logging without thinking much. I didn’t even realize how messy it looked until I came across decorators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_mztXdWE-gWNxUCB6iylRQ.png" /></figure><h3>🧠 What Are Decorators in Python?</h3><blockquote><em>Decorators are a special feature in Python that let you add extra functionality to your functions without changing their actual code.</em></blockquote><p>Here’s a <strong>sample Python decorator</strong> that logs function calls, their arguments, and the return value — useful for debugging &amp; monitoring purposes.</p><pre>import functools<br>import logging<br>from datetime import datetime<br><br># Configure application logger<br>logging.basicConfig(level=logging.INFO, format=&#39;%(asctime)s - %(levelname)s - %(message)s&#39;)<br><br>def log_function_call(func):<br>    &quot;&quot;&quot;<br>    A decorator that logs function call details: <br>    name, arguments, and return value.<br>    &quot;&quot;&quot;<br>    @functools.wraps(func)<br>    def wrapper(*args, **kwargs):<br>        # Log the function call with arguments<br>        logging.info(f&quot;Called {func.__name__}() with args: {args} kwargs: {kwargs}&quot;)<br>        <br>        start_time = datetime.now()<br>        result = func(*args, **kwargs)  # Call the original function<br>        end_time = datetime.now()<br>        <br>        # Log the return value and execution time<br>        logging.info(f&quot;{func.__name__}() returned {result} (Execution time: {end_time - start_time})&quot;)<br>        return result<br><br>    return wrapper<br><br># Example usage<br>@log_function_call<br>def add(a, b):<br>    return a + b<br><br>@log_function_call<br>def greet(name=&quot;World&quot;):<br>    return f&quot;Hello, {name}!&quot;<br><br># Calling the functions<br>if __name__ == &quot;__main__&quot;:<br>    add(5, 7)<br>    greet(name=&quot;Saurabh&quot;)</pre><p>We can see we created a decorator named as <strong>log_function_call </strong>which simply logs function name to which this decorator will be attached, also logs information related to parameters passed to the function and its execution time.</p><p>So when this decorator is applied to any function, before even the function is called decorator would run until</p><pre>result = func(*args, **kwargs)  # Call the original function</pre><p>And once the function is completed it will run the remaining code inside decorator.</p><p>When I used the decorator in <strong>add</strong> and <strong>greet</strong> function, below was my output.</p><pre>2025-06-05 16:11:21,396 - INFO - Called add() with args: (5, 7) kwargs: {}<br>2025-06-05 16:11:21,396 - INFO - add() returned 12 (Execution time: 0:00:00.000001)<br>2025-06-05 16:11:21,396 - INFO - Called greet() with args: () kwargs: {&#39;name&#39;: &#39;Saurabh&#39;}<br>2025-06-05 16:11:21,396 - INFO - greet() returned Hello, Saurabh! (Execution time: 0:00:00.000001)</pre><h3>Where You Can Use Decorators</h3><p>1️⃣ <strong>Logging</strong>Automatically logs function calls, arguments, return values.</p><p>2️⃣ <strong>Authentication / Authorization</strong>Checks if a user has permission before allowing function execution.</p><p>3️⃣ <strong>Input Validation</strong>Validates arguments before the function runs (e.g., check if email is valid).</p><p>4️⃣ <strong>Caching / Memoization</strong>Stores results of expensive functions so you don’t recalculate. Example: @lru_cache</p><p>5️⃣<strong> Timing / Benchmarking</strong>Measures how long a function takes to execute.</p><p>6️⃣<strong> Retry Logic</strong>Automatically retries a function if it fails due to temporary issues (like API calls).</p><p>7️⃣ <strong>Rate Limiting</strong>Restricts how often a function can be called (used in APIs).</p><p>8️⃣ <strong>Transaction Management</strong>Wraps DB operations to ensure commit/rollback is handled cleanly.</p><p>9️⃣ <strong>Access Logging in APIs</strong>Logs who accessed what endpoint, especially in frameworks like FastAPI or Flask.</p><p>🔟 <strong>Unit Testing Helpers</strong>Automatically skip or mark tests based on conditions (like @pytest.mark.skip).</p><h3>🎯 Connect with us:</h3><p>For further queries, you can contact us on <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a></p><p>Join our discord community for a better learning experience <a href="https://discord.gg/ysEBHtSwfe">https://discord.gg/ysEBHtSwfe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d43d673a1ba2" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/my-lazy-secret-to-cleaner-code-python-decorators-d43d673a1ba2">My Lazy Secret to Cleaner Code: Python Decorators</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Middlewares and Exeption Handler in FastAPI.]]></title>
            <link>https://blog.devgenius.io/middlewares-in-fastapi-1f0b30b84b66?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0b30b84b66</guid>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[middleware]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 11:34:42 GMT</pubDate>
            <atom:updated>2025-02-19T15:53:05.372Z</atom:updated>
            <content:encoded><![CDATA[<p>In this tutorial, we will try to cover up about</p><ul><li>Middleware</li><li>Custom Exception Handler</li><li>CORSMiddleware</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Fgs2AKyulKVzSSJNMB2Mw.png" /></figure><p>Middleware in the context of APIs are components that sit between the server and the application, handling requests and responses before they reach the application logic or after the logic has been executed. Middleware functions as a pipeline through which all HTTP requests and responses must pass, allowing you to execute code, modify requests, and alter responses.</p><p>In FastAPI, Middleware is a way to run some custom code before and after each request. They are useful for a variety of tasks such as processing requests, modifying responses, managing sessions, or handling security operations like authentication. Here’s how you can work with middlewares in FastAPI</p><p>Let&#39;s dig deeper and try to add some middleware to our FastAPI project.<br>to add middleware make sure you create a <strong>Python package</strong> <strong>middleware</strong> and keep all your middleware in the same.<br>We are using src as our application so middleware will be kept inside <strong>src/middleware/*</strong></p><h3>Log Middleware</h3><p>Log Middleware will be a simple middleware that can log requests and responses in our project.</p><p>To do this create a <strong>src/middleware/logger.py</strong> file in our application and add the code below.</p><pre>from fastapi import FastAPI, Request<br>from starlette.middleware.base import BaseHTTPMiddleware<br>from starlette.responses import Response<br>import time<br><br>class LoggerMiddleware(BaseHTTPMiddleware):<br>    async def dispatch(self, request: Request, call_next):<br>        start_time = time.time()<br>        response = await call_next(request)<br>        process_time = time.time() - start_time<br>        # Log the request and response details<br>        print(f&quot;Request: {request.method} {request.url} - Response: {response.status_code} - Time: {process_time:.4f} sec&quot;)<br>        return response</pre><p>and inside your main.py file or wherever you have placed your main application, add the code below to the above-created middleware class to our main application.</p><pre>app = FastAPI()<br>...<br>...<br>...<br># Add the middleware to the FastAPI application<br>app.add_middleware(LoggerMiddleware)</pre><p>To add a middleware in FastAPI, you can use the add_middleware method of the FastAPI class. You typically add this to the main application file where your app instance is created.</p><h3>CORSMiddleware</h3><p>Cross-Origin Resource Sharing (CORS) middleware is crucial for web applications that interact with resources from different domains. This middleware allows you to specify which domains can communicate with your API, which methods are allowed, and what headers can be used.</p><pre>from fastapi import FastAPI<br>from starlette.middleware.cors import CORSMiddleware<br><br>app = FastAPI()<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;https://example.com&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)</pre><h3>Custom Exception Handler</h3><p>Creating a custom exception handler in FastAPI allows you to manage how your application responds to different types of errors, providing a cleaner and more user-friendly error-handling strategy. Here’s how you can set up a custom exception handler in FastAPI:</p><p><strong>1: Define Your Custom Exception</strong></p><p>First, you define a custom exception class. This class will be used to raise exceptions in your application whenever something goes wrong.</p><pre>&quot;&quot;&quot;<br>Generic custom exception handler for elevate.<br>How to use.<br><br>Import<br>from elevate_api.util.exception_handler import CustomException<br><br>to use.<br>    raise CustomException(msg=&quot;Custom error occurred&quot;, code=&lt;Optional:default=404&gt;)<br><br>&quot;&quot;&quot;<br>from fastapi.exceptions import HTTPException<br><br><br>class CustomException(HTTPException):<br>    def __init__(self, msg: str, code=400):<br>        super().__init__(status_code=code, detail=msg)<br>        self.msg = msg<br>        self.status_code = code<br><br>    def __str__(self):<br>        return f&quot;{self.status_code}: {self.msg}&quot;</pre><p>Once the custom exception handler is ready we need to add it to the main application</p><p>Update the below code where ever you main application code is present.</p><pre>@app.exception_handler(CustomException)<br>async def custom_exception_handler(request: Request, exc: CustomException):<br>    return JSONResponse(<br>        status_code=exc.status_code,<br>        content={&quot;error&quot;: {&quot;statusCode&quot;: exc.status_code, &quot;message&quot;: exc.msg}},<br>    )</pre><p>For further queries, you can contact us on <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a></p><p>Join our discord community for a better learning experience <a href="https://discord.gg/ysEBHtSwfe">https://discord.gg/ysEBHtSwfe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0b30b84b66" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/middlewares-in-fastapi-1f0b30b84b66">Middlewares and Exeption Handler in FastAPI.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[12 Most Common GIT Commands]]></title>
            <link>https://blog.devgenius.io/12-most-common-git-commands-4468001571b6?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/4468001571b6</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 10:06:31 GMT</pubDate>
            <atom:updated>2025-02-17T15:45:09.030Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wrlJc7VhQE1vtoYIzRz9Pw.jpeg" /></figure><h3>What is Git?</h3><p>So, what is Git in a nutshell? This is an important section to absorb, because if you understand what Git is and the fundamentals of how it works, then using Git effectively will probably be much easier for you. As you learn Git, try to clear your mind of the things you may know about other VCSs, such as CVS, Subversion or Perforce — doing so will help you avoid subtle confusion when using the tool. Even though Git’s user interface is fairly similar to these other VCSs, Git stores and thinks about information in a very different way, and understanding these differences will help you avoid becoming confused while using it.</p><h3>12 Most Common GIT Commands</h3><ul><li><strong>git clone: </strong>Creates a new local repository in the current directory. Copies an existing remote repository to your local machine.</li></ul><pre>git clone &lt;github_link_or_ssl&gt;</pre><ul><li><strong>git status: </strong>Shows the state of your working directory and staging area.</li></ul><pre>git status</pre><ul><li><strong>git add</strong>: Adds changes in your working directory to the staging area, which is a temporary area where you can prepare your next commit.</li></ul><pre>git add &lt;filepath/folder&gt;</pre><ul><li><strong>git pull: </strong>Downloads the latest commits from a remote repository and merges them with your local branch.</li></ul><pre>git pull origin &lt;branch_name&gt;</pre><ul><li><strong>git commit: </strong>Records the changes in the staging area as a new snapshot in the local repository, along with a message describing the changes.</li></ul><pre>git commit -m &quot;&lt;Your Commit Message&gt;&quot;</pre><ul><li><strong>git branch</strong>: Lists, creates, renames, or deletes branches in your local repository. A branch is a pointer to a specific commit.</li></ul><pre>git branch -b &lt;branch_name&gt; # create a new branch<br>git branch -a #(see all branches, remote and local)<br>git branch #(see local branches)<br>git branch -d &lt;branch_name&gt; # (delete branch)</pre><ul><li><strong>git push: </strong>Uploads the local changes to the remote repository usually on a platform like GitHub or GitLab.</li></ul><pre>git push origin &lt;branch_name&gt;</pre><ul><li><strong>git checkout: </strong>Switches your working directory to a different branch or commit, discarding any uncommitted changes</li></ul><pre>git checkout &lt;branch_name&gt; # switch to a different branch<br>git checkout &lt;file/folder path&gt; # discarding any uncommitted changes from directory. </pre><ul><li><strong>git merge: </strong>Combines the changes from one branch into another branch, creating a new commit if there are no conflicts</li></ul><pre>git merge &lt;branch_1&gt; &lt;branch_2&gt;  # merged branch_2 into branch_1</pre><ul><li><strong>git diff: </strong>Shows the differences between two commits, branches, files, or the working directory and the staging area.</li></ul><pre>git diff &lt;filepath&gt; # see all non commited modifications<br>git diff &lt;branch_1&gt; &lt;branch_2&gt; # see diff between branch 1 and branch 2</pre><ul><li><strong>git log: </strong>Shows the history of commits in the current branch, along with their messages, authors, and dates.</li></ul><pre>git log</pre><p>For further queries, you can contact us on <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a></p><p>Join our discord community for a better learning experience <a href="https://discord.gg/ysEBHtSwfe">https://discord.gg/ysEBHtSwfe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4468001571b6" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/12-most-common-git-commands-4468001571b6">12 Most Common GIT Commands</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django ORM Join Queries: Simplifying Complex Data Relationships]]></title>
            <link>https://blog.devgenius.io/django-orm-join-queries-simplifying-complex-data-relationships-307ab450f68b?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/307ab450f68b</guid>
            <category><![CDATA[django-framework]]></category>
            <category><![CDATA[sql-joins]]></category>
            <category><![CDATA[django-orm]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 13:54:30 GMT</pubDate>
            <atom:updated>2025-02-07T15:08:15.666Z</atom:updated>
            <content:encoded><![CDATA[<p>In SQL, joins are used to combine rows from two or more tables based on a related column between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*7cJEOWDVuNN98lyIEOd4RA.jpeg" /></figure><p>To understand more around the topic Let’s use an example involving two tables: stores and products. Here are the tables:</p><p><strong>stores</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SzpjW3STvFB0V-KdKBZuhw.png" /></figure><p><strong>products</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wgD2cpnCfBfBx0W2xtAoBg.png" /></figure><p>Assuming we have Django models for Store and Product , it would look like below.</p><pre>from django.db import models<br><br>class Store(models.Model):<br>    store_name = models.CharField(max_length=100)<br><br>class Product(models.Model):<br>    product_name = models.CharField(max_length=100)<br>    store = models.ForeignKey(Store, on_delete=models.CASCADE)</pre><p>Let’s explore the different types of joins using these tables:</p><h3>1. INNER JOIN</h3><p>An <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Inner_join"><strong>INNER JOIN</strong></a> in SQL returns rows when there is at least one match in both tables. If there are rows in the first table that do not have matches in the second table, those rows will not be included in the result set.</p><p><strong>let take an example query:</strong></p><pre>SELECT stores.store_name, products.product_name<br>FROM stores<br>INNER JOIN products ON stores.store_id = products.store_id;</pre><p>The above query will produce result as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6m02vNGA-NACHzr5OoebrA.png" /></figure><p>Traslating the above query to Django ORM query it would be.</p><pre>from myapp.models import Store<br><br>stores_with_products = Store.objects.prefetch_related(&#39;product_set&#39;)</pre><p>Using inner join could be a complicated process, check out below points to identify when to use inner join or when to not</p><p><strong>When to Use INNER JOIN</strong></p><ol><li>When you only need rows that have matching data in both tables.</li><li>When you are confident that both tables will have related data and you do not need to consider non-matching rows.</li><li>For straightforward one-to-one or many-to-one relationships where you need a clean, matched result set.</li></ol><p><strong>When Not to Use INNER JOIN</strong></p><ol><li>If you need to include non-matching rows from one or both tables, consider using LEFT JOIN, RIGHT JOIN, or FULL JOIN.</li><li>When you need a complete dataset including all entries from one table regardless of matching, INNER JOIN will exclude non-matching data.</li><li>In some cases, with large datasets or complex join conditions, INNER JOINs may not be the most performant option. Consider evaluating query plans and indexes.</li></ol><h3>2. Left (Outer) Join</h3><p>A <a href="https://en.wikipedia.org/wiki/Join_(SQL)#Left_outer_join"><strong>LEFT JOIN</strong> (or <strong>LEFT OUTER JOIN</strong>)</a> in SQL returns all rows from the left table and the matched rows from the right table. If there is no match, the result is NULL on the side of the right table.</p><p><strong>let take an example query:</strong></p><pre>SELECT stores.store_name, products.product_name<br>FROM stores<br>LEFT JOIN products ON stores.store_id = products.store_id;</pre><p>The above query will produce result as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TJst39OjJJtlFYXC_DHTWw.png" /></figure><p>Translating the above query to Django ORM query it would be very</p><pre>from myapp.models import Store<br><br>stores_with_products = Store.objects.prefetch_related(&#39;products&#39;).all()</pre><p>Using left join could be a complicated process, check out below points to identify when to use inner join or when to not</p><p><strong>When to Use LEFT JOIN</strong></p><ol><li><strong>Including Non-Matching Rows</strong>: When you need to include all records from the left table, even if there are no corresponding matches in the right table.</li><li><strong>Data Completeness</strong>: When you want to ensure that all records from the left table are represented, and you want to see where matches are missing.</li><li><strong>Hierarchical Data</strong>: Useful for hierarchical data where the parent table (left table) must always be included even if there are no child records (right table).</li></ol><p><strong>When Not to Use LEFT JOIN</strong></p><ol><li><strong>Only Matching Rows</strong>: If you only need rows that have matches in both tables, use an INNER JOIN instead.</li><li><strong>Performance Concerns</strong>: If performance is critical and the dataset is large, consider the impact of including all rows from the left table.</li><li><strong>Simplicity</strong>: When you want a simpler, matched dataset without NULL values for unmatched rows, an INNER JOIN is preferable.</li></ol><h3>3. Right (Outer) Join</h3><p>A <strong>RIGHT JOIN</strong> (or <strong>RIGHT OUTER JOIN</strong>) in SQL returns all rows from the right table and the matched rows from the left table. If there is no match, the result is NULL on the side of the left table.</p><p><strong>let take an example query:</strong></p><pre>SELECT stores.store_name, products.product_name<br>FROM stores<br>LEFT JOIN products ON stores.store_id = products.store_id;</pre><p>The above query will produce result as</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*My8D3i152tqde1GaWSeKCg.png" /></figure><p>Translating the above query to Django ORM query it would be very</p><pre><br>from myapp.models import Store<br><br>stores_with_products = Store.objects.prefetch_related(&#39;products&#39;).all()</pre><p>Using right outer join could be a complicated process, check out below points to identify when to use inner join or when to not</p><p><strong>When to Use RIGHT OUTER JOIN</strong></p><ol><li><strong>Including Non-Matching Rows</strong>: When you need to include all records from the right table, even if there are no corresponding matches in the left table.</li><li><strong>Data Completeness</strong>: When you want to ensure that all records from the right table are represented, and you want to see where matches are missing.</li><li><strong>Hierarchical Data</strong>: Useful for hierarchical data where the child table (right table) must always be included even if there are no parent records (left table).</li></ol><p><strong>When Not to Use RIGHT JOIN</strong></p><ol><li><strong>Only Matching Rows</strong>: If you only need rows that have matches in both tables, use an INNER JOIN instead.</li><li><strong>Performance Concerns</strong>: If performance is critical and the dataset is large, consider the impact of including all rows from the right table.</li><li><strong>Simplicity</strong>: When you want a simpler, matched dataset without NULL values for unmatched rows, an INNER JOIN is preferable.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=307ab450f68b" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/django-orm-join-queries-simplifying-complex-data-relationships-307ab450f68b">Django ORM Join Queries: Simplifying Complex Data Relationships</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Git: GitHub Handbook]]></title>
            <link>https://dextrop.medium.com/getting-started-with-git-github-handbook-849bfc9efb30?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/849bfc9efb30</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[version-control-system]]></category>
            <category><![CDATA[versioning]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Fri, 07 Feb 2025 13:52:38 GMT</pubDate>
            <atom:updated>2025-02-07T14:04:19.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*A6gQws1oE4C6wO1LP8bJog.png" /></figure><p>Let&#39;s try to understand what git is and what is GitHub.</p><p>Git is a free, open-source version control system (VCS) that helps developers store, track, and manage code. It&#39;s a kind of protocol that software can use for free.</p><p>while GitHub is a web-based platform that uses Git to manage codes in the form of repositories (repos).</p><p>Why do we use Git or GitHub?</p><p>Let&#39;s suppose we are creating a project ( e-commerce ) that has frontend code and backend code and has 3 people working on the frontend and 3 on the backend.</p><p>The basic problem that occurs are</p><ul><li><strong>Code Sharing:</strong></li></ul><p>How will code sharing happen between users and organizations? Git stores a developer’s code and its history locally in a repository both locally and remotely. So code sharing becomes easy.</p><p>Github as feature of the branch, one could hold multiple snaps of code in different branches, To understand it in a better way, we can create two repositories one for the backend and one for the frontend. The development path will be broken down into tasks and each task can have a branch. When the task is done the branch can be merged to dev where integration happens and once everything is working it can be merged to master or to any release branch/tag. So our main/master/release branch will always hold stable code and each bug and feature can be tracked based on their branch.</p><ul><li><strong>Getting to an older version in case of emergency.</strong></li></ul><p>We could say the emergency could be any, code is unstable, not liked by the client, etc, etc. But getting to an older version becomes easy, if a person is deploying a release with proper tags he/she can get to tag easily and get the previous code else one can see all commits and check the stable branch, create a release branch, and deploy.</p><ul><li><strong>Deployment</strong></li></ul><p>The deployment itself is a big problem which can be solved using GitHub as it provides CI/CD pipelines for almost all languages and frameworks. Deployment with proper testing and that to all automated is possible with Git Hub.</p><h3>Basic Git Commands and Their Inner Workings</h3><p><strong>git init</strong></p><ul><li>Initializes a new Git repository.</li><li>Creates the .git folder in the project directory, setting up the necessary database and reference files for version control.</li></ul><p><strong>git clone</strong></p><ul><li>Copies a repository from Git remote to your local machine.</li><li>Clones are not just the current version of the repository but the entire history with all branches.</li></ul><p><strong>git add</strong></p><ul><li>Stages changes for the next commit. Add your files to the ongoing changes.</li></ul><p><strong>git commit</strong></p><ul><li>Creates a commit, a kind of code snapshot with a message. Records the snapshot of the staged changes to the project history.</li></ul><p><strong>git status</strong></p><ul><li>Displays the state of the working directory and staging area.</li></ul><p><strong>git push</strong></p><ul><li>Transfers all commit from your local repository to a remote repository (like GitHub).</li></ul><p><strong>git pull</strong></p><ul><li>Fetches changes from the remote repository to the local machine and merges them.</li><li>A combination of git fetch and git merge.</li></ul><p><strong>git branch</strong></p><ul><li>Manages branches in your repository.</li></ul><p><strong>git checkout &lt;branch_name&gt;</strong></p><ul><li>Switches branches inside the git repo.</li></ul><p><strong>git checkout &lt;filename&gt;</strong></p><ul><li>discard all changes from a file.</li></ul><p><strong>git checkout -b &lt;branch_name&gt;</strong></p><ul><li>Create a new branch and switch to it.</li></ul><p><strong>git merge</strong></p><ul><li>Combines multiple sequences of commits into one unified history.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=849bfc9efb30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Containerizing FastAPI with PostgreSQL using Docker.]]></title>
            <link>https://blog.devgenius.io/containerizing-fast-api-application-using-docker-99491ec0d0bf?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/99491ec0d0bf</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[dockerfiles]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Thu, 06 Feb 2025 04:26:45 GMT</pubDate>
            <atom:updated>2025-04-20T10:13:13.666Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5F8A_wcYo8NRjhymmhlPaQ.png" /></figure><p>In this tutorial, we will try to figure out how we can containerize our FastAPI application. In this tutorial, we will also learn how we can add a database to the container itself. For this purpose, we will use <strong>Docker</strong></p><p>Make sure you have Docker installed in your local system, and we would also need the fastapi project, which needs a database as well. If you do not have any such project, you can download it from the <a href="https://github.com/dextrop/SimpleFastAPI/tree/authentication"><strong>Github_Repo</strong></a><strong>. </strong>We would do some practical today.</p><p>Docker is like a <strong>tiffin box</strong> 📦 for your software.</p><p>When your mom packs lunch, she puts <strong>everything you need to eat</strong> — sabzi, roti, achar — into one single box. You can open it anywhere — in the office, train, or even mountain.</p><p>Similarly, Docker packs your <strong>code, settings, and dependencies</strong> (like Python, database drivers, packages, etc.) into a single container. That container can run <strong>anywhere</strong> — on your computer, a colleague’s laptop, or even on a cloud server (like AWS or GCP).</p><h3>🚧 The Problem Before Docker</h3><p>Earlier, you’d hear things like:</p><blockquote><em>“It works on my machine!” 😩</em></blockquote><p>That’s because maybe you had Python 3.10 and your friend had Python 3.6. Or your machine had PostgreSQL and theirs didn’t. Every system had slight differences, and those differences caused <strong>bugs and crashes</strong>.</p><p>Docker solves it all, One could simply create a yml configuration file adding all requirements; this file may use a Dockerfile as a build file, which tells Docker how to build the application.</p><p>Let’s start by checking the configuration below.</p><pre>version: &#39;3.8&#39;  # Specify the Compose file format version<br>services:<br>  postgres:<br>    image: postgres:13  # Use the official PostgreSQL image, version 13<br>    container_name: postgres-db<br>    restart: always  # Automatically restart the container if it crashes<br>    environment:<br>      # Set up default PostgreSQL credentials and database name.<br>      POSTGRES_USER: sampleuser<br>      POSTGRES_PASSWORD: samplepass<br>      POSTGRES_DB: sample_db<br>    ports:<br>      - &quot;9999:5432&quot;  # Map container port 5432 to host port 5432<br>    volumes:<br>      # Persist PostgreSQL data on the host using a named volume.<br>      - postgres_data:/var/lib/postgresql/data<br><br># Define named volumes for data persistence.<br>volumes:<br>  postgres_data:</pre><p>The above configuration tells Docker to create a service named<strong>postgres</strong>, which will use the image<strong>postgres:13</strong>, and have a restart policy set to <strong>always</strong> ensure the container restarts in case of a crash. It is also provided with environment variables: <strong>POSTGRES_USER</strong>, <strong>POSTGRES_PASSWORD</strong>, and <strong>POSTGRES_DB</strong>, along with a port configuration <strong>9999:5432</strong>.</p><p>Docker will first try to find the image <strong>postgres:13</strong> locally; if not found, it will download the image from Docker Hub. The official PostgreSQL image from Docker can be used directly with environment variables to create a database container on a local machine or a server.</p><p>This container will have PostgreSQL running inside on port <strong>5432</strong>, which will be mapped to the external port <strong>9999</strong> as declared in the port configuration above, i.e., <strong>9999:5432</strong>.</p><p>We have also declared a volume, which will tell Docker Hey, I want to store the database data <strong>outside</strong> the container, in a place that won’t get deleted even if the container is removed.</p><p>We can save the configuration in a <strong>docker-compose.yml</strong> file.</p><p>To run it just type the below command</p><pre>docker compose up --build</pre><p>The command will then build the Docker configuration file and run.</p><p>Once Docker is up and running, you can access it on port 9999 with the following configuration</p><pre>USER: sampleuser<br>PASSWORD: samplepass<br>DB: sample_db<br>PORT: 9999<br>HOST: localhost</pre><p>You could simply connect your application with PostgreSQL using the above configuration.</p><p>We also need to add FastAPI build configuration and FastAPI service to the above configuration.</p><p>Create a Dockerfile and write below content in it</p><pre># Use the official lightweight Python image.<br># You can change the version as needed.<br>FROM python:3.9-slim<br><br># Set the working directory in the container to /app<br>WORKDIR /app<br># Copy your application code to the container.<br># This assumes your FastAPI code (e.g., main.py, requirements.txt etc) is in the current directory.<br>COPY . .<br># Install the Python dependencies.<br># The &#39;--no-cache-dir&#39; flag reduces the image size by not caching the installation packages.<br>RUN pip install --upgrade pip &amp;&amp; pip install --no-cache-dir -r requirements.txt<br><br># Install netcat-openbsd for waiting on Postgres.<br>RUN apt-get update &amp;&amp; apt-get install -y netcat-openbsd &amp;&amp; rm -rf /var/lib/apt/lists/*<br><br># Expose port 80 to allow external access to the FastAPI application.<br>EXPOSE 8080<br># Define the command to run the application using Uvicorn.<br># Here, &#39;main:app&#39; means that the FastAPI app is instantiated in a file named &#39;main.py&#39;<br># with the variable &#39;app&#39; (e.g., app = FastAPI()).<br>CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8080&quot;]</pre><p>The configuration tells Docker that it needs to build the application and a container with the image python:3.9-slim, create our working directory as /app, and copy all files in the working folder. Then, install all dependencies required for the project, expose the 8080 port, and finally run our application.</p><blockquote>To avoid extra file while copying simply use .dockerignore file same as .gitignore</blockquote><p>Now our build configuration for FastAPI is ready. Now we need to add it to our FastAPI application</p><p>update the docker-compose.yml file with the below content</p><pre>version: &#39;3.8&#39;  # Specify the Compose file format version<br>services:<br>  fastapi:<br>    # Build the FastAPI app using the Dockerfile in the current directory.<br>    build: .<br>    container_name: backend-server<br>    ports:<br>      - &quot;8080:8080&quot;  # Map container port 80 to host port 80<br>    environment:<br>      # Define the database connection URL.<br>      # Here, &#39;postgres&#39; is the service name of our PostgreSQL container.<br>      # Change &#39;postgres&#39; (username), &#39;postgres&#39; (password), and &#39;mydatabase&#39; as needed.<br>      DATABASE_URL: &quot;postgresql://sampleuser:samplepass@postgres:5432/sample_db&quot;<br>    depends_on:<br>      - postgres<br><br>  postgres:<br>    image: postgres:13  # Use the official PostgreSQL image, version 13<br>    container_name: postgres-db<br>    restart: always  # Automatically restart the container if it crashes<br>    environment:<br>      # Set up default PostgreSQL credentials and database name.<br>      POSTGRES_USER: sampleuser<br>      POSTGRES_PASSWORD: samplepass<br>      POSTGRES_DB: sample_db<br>    ports:<br>      - &quot;9999:5432&quot;  # Map container port 5432 to host port 5432<br>    volumes:<br>      # Persist PostgreSQL data on the host using a named volume.<br>      - postgres_data:/var/lib/postgresql/data/v1<br><br># Define named volumes for data persistence.<br>volumes:<br>  postgres_data:</pre><p>We can see we have added a new service named fastapi that will build from the current directly, so instead of using an image, it will build an image using the Dockerfile we provided, which will then be mapped to the 8080 port</p><p>We can see we are also passing environment variables, but</p><pre>postgresql://sampleuser:samplepass@postgres:5432/sample_db</pre><p>The above configuration says to use postgresql driver with sampleuser and samplepass, and host postgres and port 5432 to connect to sample_db.</p><p>Now you must be thinking why <strong>PostgreSQL</strong> as host and why port 5432 when we have opened our PostgreSQL on 9999 from the container. This is simply because when a Docker container connects with another container, it will use the internal network and have access to 5432 on the host PostgreSQL, as we have named our service as postgresql for the database.</p><p>You also have to change your alembic.ini configuration file, the environment variables can be used inside our FastAPI application.</p><p>Now let’s try.</p><pre>docker compose up --build -d</pre><p>This time, I have also added <strong><em>-d</em></strong> as a parameter. This will tell Docker to run the container in the background.</p><p>Once the container is up and running, you can go inside the container with the below command</p><pre>docker exec -it postgres bash</pre><p>for getting into the fastapi container use</p><pre>docker exec -it fastapi bash</pre><p>for postgres use</p><pre>docker exec -it postgres bash</pre><p>The command simply tells Docker to get me into the postgres/fastapi container with bash as an interface.</p><p>Once you are inside your container in FastAPI, you can perform migration. You dont have to go inside /app, it will directly land you in the working directly and you can perform migration directly.</p><p>To do it in a better way, we can add an entry script to our Dockerfile, create a file named entrypoint.sh, and make it executable using the below command</p><pre>chmod a+x entrypoint.sh</pre><p>Once done, update the code below inside the file</p><pre>#!/bin/sh<br># entrypoint.sh<br><br># Wait for PostgreSQL to be ready<br># The loop uses netcat (nc) to check if postgres service is listening on port 5432.<br>echo &quot;Waiting for Postgres to be ready...&quot;<br>while ! nc -z postgres 5432; do<br>  sleep 1<br>done<br>echo &quot;Postgres is up and running!&quot;<br># Run migration script (using Alembic in this example)<br>echo &quot;Running database migrations...&quot;<br>alembic upgrade head<br># Start the FastAPI server with Uvicorn<br>echo &quot;Starting FastAPI application...&quot;<br>exec uvicorn main:app --host 0.0.0.0 --port 80</pre><p>Simply update Dockerfile</p><pre># Use the official lightweight Python image.<br># You can change the version as needed.<br>FROM python:3.9-slim<br><br># Set the working directory in the container to /app<br>WORKDIR /app<br># Copy your application code to the container.<br># This assumes your FastAPI code (e.g., main.py, requirements.txt etc) is in the current directory.<br>COPY . .<br># Install the Python dependencies.<br># The &#39;--no-cache-dir&#39; flag reduces the image size by not caching the installation packages.<br>RUN pip install --upgrade pip &amp;&amp; pip install --no-cache-dir -r requirements.txt<br># Install netcat-openbsd for waiting on Postgres.<br>RUN apt-get update &amp;&amp; apt-get install -y netcat-openbsd &amp;&amp; rm -rf /var/lib/apt/lists/*<br># Expose port 80 to allow external access to the FastAPI application.<br>EXPOSE 8080<br># Define the command to run the application using Uvicorn.<br># Here, &#39;main:app&#39; means that the FastAPI app is instantiated in a file named &#39;main.py&#39;<br># with the variable &#39;app&#39; (e.g., app = FastAPI()).<br># CMD [&quot;uvicorn&quot;, &quot;main:app&quot;, &quot;--host&quot;, &quot;0.0.0.0&quot;, &quot;--port&quot;, &quot;8080&quot;]<br>CMD [&quot;./entrypoint.sh&quot;]</pre><p>All we have changed is that instead of directly using uvicorn, we are calling our entry script, which does migration and then runs the application.</p><p>Make sure your application has a proper migration file.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99491ec0d0bf" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/containerizing-fast-api-application-using-docker-99491ec0d0bf">Docker Containerizing FastAPI with PostgreSQL using Docker.</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure Your FastAPI Application: Implementing JWT Authentication for Login & Signup]]></title>
            <link>https://blog.devgenius.io/secure-your-fastapi-application-implementing-jwt-authentication-for-login-signup-738eab93f6a9?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/738eab93f6a9</guid>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[sign-up]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[login]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 08:48:03 GMT</pubDate>
            <atom:updated>2025-02-15T08:34:27.624Z</atom:updated>
            <content:encoded><![CDATA[<p>In the last article, we learned how to <a href="https://medium.com/dev-genius/fastapi-tutorial-build-a-rest-api-in-15-minutes-f57e2f91424a">create a simple fast API</a> and then how to <a href="https://blog.devgenius.io/connecting-fastapi-to-postgresql-from-installation-to-integration-2d367eefad62">add a database (PostgreSQL)</a> to our FastAPI project.</p><p>Link for base code for the article <a href="https://github.com/dextrop/SimpleFastAPI/tree/connected_with_db">( Github Link )</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwPPKOnMwNo5aXZq5YEdjA.png" /></figure><p><strong>In this article, we will try to</strong></p><ul><li>Add Users table to our project</li><li>Create Signup API</li><li>Add Login with JWT for the project.</li><li>Create a protected API ( API only for authenticated users)</li><li>Proper folder structure for the FastAPI project.</li></ul><h3>About JWT</h3><p>JWT means “JSON Web Tokens”.</p><p>It’s a standard to codify a JSON object in a long dense string without spaces. It looks like this:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c</pre><p>It is not encrypted, so, anyone could recover the information from the contents.</p><p>But it’s signed. So, when you receive a token that you emitted, you can verify that you actually emitted it.</p><p><strong>So let&#39;s start</strong></p><p>Let&#39;s first create a proper folder structure for our project. Our projects current looks like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*6tKehUmsQlBsQEyK6_Zs8w.png" /></figure><p>We have a model file where all our models are declared, and we have db.py for the database adapter code and main.py for the rest of the server code. For adding data to the database and fetching it back we do have controller.py as well.</p><p>Create a Python package named “<strong>src</strong>”, you can keep any name, I keep it as “<strong>src</strong>” referring to the source, inside “<strong>src</strong>” all my source code related to projects is stored.</p><p>Inside the src folder create 4 more Python packages,</p><ul><li><strong>src/controllers</strong>: for storing all controllers for different module</li><li><strong>src/models</strong>: for storing all tables-related information ( all models stored here)</li><li><strong>src/utils</strong>: For all reused classes and functions ( helpers and constants are stored here )</li><li><strong>src/views: </strong>Stored views. Views are URLs mapped to a controller function for fetching and adding information to the database.</li></ul><p>The folder structure will look something like the one below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*N5LjryHylZGOFjpEmMPTQA.png" /></figure><p>In our previous article we have already learned how to create a table for our project refer to <a href="https://blog.devgenius.io/connecting-fastapi-to-postgresql-from-installation-to-integration-2d367eefad62">here</a>. So we won&#39;t go deep into understanding the user model.</p><p>Let&#39;s focus on creating a user table, before doing it we need to create a base_model class which we will use in our tables, this model will be passed to the migration file to make sure all models are included.</p><p>create a file <strong>src/models/base.py</strong> and write below code in it.</p><pre>import datetime<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy import Column, DateTime, Integer, Table<br><br>Base = declarative_base()<br><br>class BaseModel(Base):<br>    &quot;&quot;&quot;<br>    ElevateBase is extended version of Base Model with extra column and functions<br>    &quot;&quot;&quot;<br><br>    __abstract__ = True<br>    __table__: Table<br><br>    id = Column(Integer, unique=True, autoincrement=True, nullable=False, index=True, primary_key=True)<br><br>    # Do we need to enable timezone for below two fields<br>    created_at = Column(DateTime, default=datetime.datetime.now)<br>    updated_at = Column(DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)<br><br></pre><p>We have just declared our BaseModel with 3 columns, id, created_at and updated_at which will be required in all our models.</p><p>Now let&#39;s create a file inside the models file named <strong>src/models/books.py.</strong> This will hold the code for our books table. You will note we have removed some columns as they are already defined in <strong>BaseModel. </strong>We inherited our user model from BaseModel.</p><pre>from src.models.base import BaseModel<br>from sqlalchemy import Column, String, Boolean<br><br>class Books(BaseModel):<br>    __tablename__ = &quot;books&quot;<br><br>    title = Column(String(200),nullable=False)<br>    author_name = Column(String(200),nullable=False)<br>    description = Column(String(500), nullable=False)<br>    is_published = Column(Boolean, default=False)</pre><p>Lastly, create a file named ‘<strong>src/models/users.py</strong>’ and copy the code below.</p><pre>from src.models.base import BaseModel<br>from sqlalchemy import Column, String, Boolean<br><br>class Users(BaseModel):<br>    __tablename__ = &quot;users&quot;<br><br>    name = Column(String(200), nullable=False)<br>    email = Column(String(200), nullable=False)<br>    password = Column(String(200), nullable=False)<br>    bio = Column(String(500), nullable=True)<br>    is_active = Column(Boolean, default=True)</pre><p>The model simply holds basic user information with a password in encrypted format using <strong>passlib</strong> and <strong>bcrypt</strong></p><p>Make sure<strong> src/models/__init__.py</strong> files have all the models imported.</p><pre>from src.models.books import Books<br>from src.models.users import Users</pre><p>also, change the <strong>alembic/env.py</strong> code to include all models</p><pre>from alembic import context<br>from sqlalchemy import engine_from_config, pool<br>from logging.config import fileConfig<br>from src.models.base import BaseModel  # Import Base from models/base.py<br><br># this is the Alembic Config object, which provides access to the .ini file values<br>config = context.config<br><br># Interpret the config file for Python logging<br>fileConfig(config.config_file_name)<br><br># Add your model&#39;s MetaData object here for &#39;autogenerate&#39; support<br>target_metadata = BaseModel.metadata<br><br>def run_migrations_online():<br>    connectable = engine_from_config(<br>        config.get_section(config.config_ini_section),<br>        prefix=&quot;sqlalchemy.&quot;,<br>        poolclass=pool.NullPool,<br>    )<br><br>    with connectable.connect() as connection:<br>        context.configure(connection=connection, target_metadata=target_metadata)<br><br>        with context.begin_transaction():<br>            context.run_migrations()<br><br>run_migrations_online()</pre><p>Now let&#39;s generate the Users model using the below command</p><pre>alembic revision --autogenerate -m &quot;Added User Model&quot;</pre><p>The command simply generates a migration script for model changes. We have added a simple message to the same saying “Added User Model”</p><p>once done you can see a new migration file found inside alembic/version with the name *********_create_books_table.py having output similar to the one below.</p><pre>INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.<br>INFO  [alembic.runtime.migration] Will assume transactional DDL.<br>INFO  [alembic.autogenerate.compare] Detected added table &#39;users&#39;<br>INFO  [alembic.ddl.postgresql] Detected sequence named &#39;books_id_seq&#39; as owned by integer column &#39;books(id)&#39;, assuming SERIAL and omitting<br>INFO  [alembic.autogenerate.compare] Detected added column &#39;books.updated_at&#39;<br>  Generating /Users/saurabhpandey/Desktop/SimpleAPI/alembic/versions/5579a1e3be84_added_user_model.py ...  done</pre><p>Now let&#39;s run migration and create a user table. run below command</p><pre>alembic upgrade head</pre><p>The output will somehow look like</p><pre>INFO  [alembic.runtime.migration] Context impl PostgresqlImpl.<br>INFO  [alembic.runtime.migration] Will assume transactional DDL.<br>INFO  [alembic.runtime.migration] Running upgrade 479ae90fb649 -&gt; 5579a1e3be84, Added User Model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tr5y9WlPDKWZ1P8LA541wg.png" /></figure><p>Once done you will be able to see new table users. let&#39;s continue with making a login API.</p><p>Login API will involve checking login credentials ( email and password ) and generating an access token. for this purpose, we will be using a JTW token for authentication.</p><p>To use JWT and encryption we need to update our dependencies with <strong>passlib</strong> (used for password hashing ) <strong>pyjwt</strong> (jwt python library) . Update requirement.txt</p><pre>fastapi<br>uvicorn<br>sqlalchemy<br>psycopg2<br>alembic<br>passlib<br>pyjwt<br>bcrypt</pre><p>Once done install the dependencies</p><pre>pip install -r requirements.txt</pre><p>We need to have a secret key created.<br>create a file outside of src named create_secret.py and add below code</p><pre>import secrets<br>import string<br><br>def generate_secret_key(length=64):<br>    # Create a reliable and secure random string for the secret key<br>    # Using choices from secrets, which is secure for cryptographic use<br>    alphabet = string.ascii_letters + string.digits<br>    key = &#39;&#39;.join(secrets.choice(alphabet) for _ in range(length))<br>    return key<br><br>if __name__ == &quot;__main__&quot;:<br>    # Generate a 32-character long secret key<br>    secret_key = generate_secret_key()<br>    print(f&quot;Generated SECRET_KEY: {secret_key}&quot;)</pre><p>Run the code using python/python3 create_secret.py and you shall get the secret key generated on your screen. Just Copy the secret key.</p><p>create a file constants.py with the below code inside src/utils/constants.py</p><pre># Constants for JWT encoding<br>SECRET_KEY = &quot;a223c50ddf4fa223c50ddf4fa223c50ddf4fa223c50ddf4fa223c50ddf4f&quot;  # Replace with a strong secret key<br>ALGORITHM = &quot;HS256&quot;  # HMAC SHA256 algorithm<br>ACCESS_TOKEN_EXPIRE_MINUTES = 30         # default expiry time is 30 mins.     </pre><p>Create a file <strong>src/utils/helpers.py</strong> inside the utils folder. this file will hold all our reusable functions. Add the below code to the file.</p><pre>import jwt<br>from passlib.context import CryptContext<br>from datetime import datetime, timedelta, timezone<br>from src.utils.constants import SECRET_KEY, ALGORITHM, ACCESS_TOKEN_EXPIRE_MINUTES<br><br>pwd_context = CryptContext(schemes=[&quot;bcrypt&quot;], deprecated=&quot;auto&quot;)<br><br>def verify_password(plain_password, hashed_password):<br>    &#39;&#39;&#39; match plain with hash password &#39;&#39;&#39;<br>    return pwd_context.verify(plain_password, hashed_password)<br><br>def get_password_hash(password):<br>    &#39;&#39;&#39; hash plain password &#39;&#39;&#39;<br>    return pwd_context.hash(password)<br><br>def create_access_token(data: dict, expires_after: int = ACCESS_TOKEN_EXPIRE_MINUTES):<br>    &#39;&#39;&#39; encode dict with provided expiry ion minutes &#39;&#39;&#39;<br>    to_encode = data.copy()<br>    expire = datetime.now(timezone.utc) + timedelta(minutes=expires_after)<br>    to_encode.update({&quot;exp&quot;: expire})<br>    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)<br>    return encoded_jwt</pre><p>The file currently has only 1 function that takes, password and salt. If salt is not passed it generates a random salt of 8 characters, else uses the salt to hash the password and return, hashed_password, and salt used.</p><p>We will use the function for storing hash_password and salt in the database rather than storing simple strings.</p><p>create a controller as <strong>src/controllers/users_controller.py</strong> and write the below code to it.</p><pre>from src.models import Users<br>from src.utils.helpers import get_password_hash<br>from fastapi import HTTPException, status<br><br>class UserController():<br>    def __init__(self, db):<br>        self.db = db<br><br>    def validate_user_info(self, user_info):<br>        &#39;&#39;&#39; Validate required user field &#39;&#39;&#39;<br>        required_fields = [&quot;name&quot;, &quot;email&quot;, &quot;password&quot;]<br>        validated = True<br>        for key in required_fields:<br>            if key not in user_info:<br>                raise HTTPException(<br>                    status_code=status.HTTP_400_BAD_REQUEST,<br>                    detail=f&#39;Missing {key} in request&#39;<br>                )<br><br>        selected_user = self.db.query(Users).filter(Users.email == user_info[&quot;email&quot;]).first()<br>        if selected_user:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;User with email {user_info[&quot;email&quot;]} already exits&#39;<br>            )<br><br>        return validated<br><br>    def signup(self, user_info):<br>        &#39;&#39;&#39;<br>        Validate required field for user, create user<br>        object and add it to database ( commit )<br>        :param user_info: {&quot;name&quot;: &quot;USER_NAME&quot;, &quot;email&quot;: &quot;USER_EMAIL&quot;, &quot;password&quot;: &quot;SOMEPASS&quot;, &quot;bio&quot;: &quot;OPTIONAL&quot; }<br>        :return:<br>        &#39;&#39;&#39;<br>        self.validate_user_info(user_info)<br>        user_info[&quot;password&quot;] = get_password_hash(password=user_info[&quot;password&quot;])<br>        userObj = Users(**user_info)<br>        self.db.add(userObj)<br>        self.db.commit()<br>        self.db.refresh(userObj)<br><br>        return {<br>            &quot;status&quot;: 200,<br>            &quot;message&quot;: &quot;User created successfully&quot;,<br>            &quot;payload&quot;: {<br>                &quot;name&quot;: userObj.name,<br>                &quot;id&quot;: userObj.id,<br>                &quot;email&quot;: userObj.email,<br>                &quot;bio&quot;: userObj.bio<br>            }<br>        }</pre><p>The user object does have only 2 functions i.e. signup and validate field.</p><p>create file <strong>src/controllers/books_controller.py</strong> and add below code</p><pre>from src.models import Books<br><br>class BooksController():<br>    def __init__(self, db_session):<br>        self.db = db_session<br><br>    def add_book(self, book_info):<br>        print (book_info)<br>        new_book = Books(**book_info)<br>        try:<br>            self.db.add(new_book)<br>            self.db.commit()<br>            self.db.refresh(new_book)<br>        except Exception as e:<br>            print (e)<br>            self.db.rollback()<br>            return {&quot;success&quot;: False, &quot;message&quot;: &quot;Unable to add book&quot;, &quot;payload&quot;: None}<br><br>        return {&quot;success&quot;: True, &quot;message&quot;: &quot;Book added successfully&quot;, &quot;payload&quot;: {<br>            &quot;id&quot;: new_book.id,<br>            &quot;title&quot;: new_book.title,<br>            &quot;description&quot;: new_book.description,<br>            &quot;author&quot;: new_book.author_name,<br>            &quot;created_at&quot;: new_book.created_at<br>        }}<br><br>    def get_all_books(self):<br>        all_books = self.db.query(Books).all()<br>        resp = []<br>        for book in all_books:<br>            resp.append(<br>                {<br>                    &quot;id&quot;: book.id,<br>                    &quot;title&quot;: book.title,<br>                    &quot;description&quot;: book.description,<br>                    &quot;author&quot;: book.author_name,<br>                    &quot;created_at&quot;: book.created_at<br>                }<br>            )<br>        return {&quot;success&quot;: True, &quot;message&quot;: &quot;Book added successfully&quot;, &quot;payload&quot;: resp}</pre><p>also</p><ul><li><strong>db.py</strong> to <strong>utils/db.py</strong></li><li>delete<strong> controller.py</strong></li><li>delete <strong>models.py</strong> file, we don&#39;t need it.</li></ul><p>Let&#39;s create our view to add an endpoint for a signup, to do so first let&#39;s create a view name books_view.py and separate our view code from main.py.</p><p>create a file views/books_views.py</p><pre>from typing import Dict<br>from src.utils.db import get_db<br>from sqlalchemy.orm import Session<br>from fastapi import Depends, APIRouter<br>from src.controllers.books_controller import BooksController<br><br>books_route = APIRouter()<br><br>@books_route.post(&quot;/books/&quot;)<br>def add_books_api(body: Dict, db: Session = Depends(get_db)):<br>    return BooksController(db).add_book(body)<br><br>@books_route.get(&quot;/books/&quot;)<br>def get_books_api(db: Session = Depends(get_db)):<br>    return BooksController(db).get_all_books()</pre><p>create users_view.py inside views, this will hold our signup and other user-related endpoints. Update users_views.py with the below code.</p><pre>from typing import Dict<br>from src.utils.db import get_db<br>from sqlalchemy.orm import Session<br>from fastapi import Depends, APIRouter<br>from src.controllers.users_controller import UserController<br><br>users_route = APIRouter()<br>@users_route.post(&quot;/signup/&quot;)<br>def signup(body: Dict, db: Session = Depends(get_db)):<br>    return UserController(db).signup(body)</pre><p>Update __init__.py to make sure all our views are imported in views python package.</p><pre>from src.views.books_views import books_route<br>from src.views.users_views import users_route</pre><p>update main.py</p><pre>import uvicorn<br>from fastapi import FastAPI<br>from src.views import books_route, users_route<br><br>app = FastAPI()<br>app.include_router(books_route)<br>app.include_router(users_route)<br><br>@app.get(&quot;/heath_api&quot;)<br>def get_server_heath():<br>    return {&quot;status&quot;: &quot;Server up and running&quot;}<br><br>def run_server():<br>    uvicorn.run(&quot;main:app&quot;)<br><br>if __name__ == &#39;__main__&#39;:<br>    run_server()</pre><p>Now lets start our server using `uvicorn`</p><pre> uvicorn main:app --reload</pre><p>Testing the endpoint on Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*37b1_-qgQcm4xv24FiJzrw.png" /></figure><p>we got success, the user is added properly, checkout viewer inside user table we can find</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ILi4mYOnzA0jFBfWxG2bSA.png" /></figure><p>Now let&#39;s continue with login API</p><p>Update <strong>src/controllers/users_controller.py</strong> with the below code.</p><pre>from src.models import Users<br>from fastapi import HTTPException, status<br>from src.utils.helpers import get_password_hash, create_access_token, verify_password<br><br>class UserController():<br>    def __init__(self, db):<br>        self.db = db<br><br>    def validate_user_info(self, user_info):<br>        &#39;&#39;&#39; Validate required user field &#39;&#39;&#39;<br>        required_fields = [&quot;name&quot;, &quot;email&quot;, &quot;password&quot;]<br>        validated = True<br>        for key in required_fields:<br>            if key not in user_info:<br>                raise HTTPException(<br>                    status_code=status.HTTP_400_BAD_REQUEST,<br>                    detail=f&#39;Missing {key} in request&#39;<br>                )<br><br>        return validated<br><br>    def signup(self, user_info):<br>        &#39;&#39;&#39;<br>        Validate required field for user, create user<br>        object and add it to database ( commit )<br>        :param user_info: {&quot;name&quot;: &quot;USER_NAME&quot;, &quot;email&quot;: &quot;USER_EMAIL&quot;, &quot;password&quot;: &quot;SOMEPASS&quot;, &quot;bio&quot;: &quot;OPTIONAL&quot; }<br>        :return:<br>        &#39;&#39;&#39;<br>        self.validate_user_info(user_info)<br>        selected_user = self.db.query(Users).filter(<br>            Users.email == user_info[&quot;email&quot;]<br>        ).first()<br>        if selected_user:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;User with email {user_info[&quot;email&quot;]} already exits&#39;<br>            )<br><br>        user_info[&quot;password&quot;] = get_password_hash(user_info[&quot;password&quot;])<br>        userObj = Users(**user_info)<br>        self.db.add(userObj)<br>        self.db.commit()<br>        self.db.refresh(userObj)<br><br>        return {<br>            &quot;status&quot;: 200,<br>            &quot;message&quot;: &quot;User created successfully&quot;,<br>            &quot;payload&quot;: {<br>                &quot;name&quot;: userObj.name,<br>                &quot;id&quot;: userObj.id,<br>                &quot;email&quot;: userObj.email,<br>                &quot;bio&quot;: userObj.bio<br>            }<br>        }<br><br>    def login(self, login_info):<br>        email = login_info.get(&quot;email&quot;, None)<br>        password = login_info.get(&quot;password&quot;, None)<br><br>        if not email:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;Missing email in request&#39;<br>            )<br><br>        if not password:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;Missing password in request&#39;<br>            )<br><br>        selected_user = self.db.query(Users).filter(Users.email == email).first()<br>        if not selected_user:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;User with email {email} not found&#39;<br>            )<br><br>        if not selected_user.is_active:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;User is inactive&#39;<br>            )<br><br>        password_hash = verify_password(<br>            plain_password=login_info[&quot;password&quot;], <br>            hashed_password=selected_user.password<br>        )<br><br>        if  not password_hash:<br>            raise HTTPException(<br>                status_code=status.HTTP_400_BAD_REQUEST,<br>                detail=f&#39;Password mismatch&#39;<br>            )<br><br>        return {<br>            &quot;status&quot;: 200,<br>            &quot;message&quot;: &quot;User created successfully&quot;,<br>            &quot;payload&quot;: {<br>                &quot;token&quot;: create_access_token(<br>                    {<br>                        &quot;name&quot;: selected_user.name,<br>                        &quot;id&quot;: selected_user.id,<br>                        &quot;email&quot;: selected_user.email,<br>                        &quot;bio&quot;: selected_user.bio<br>                    }<br>                )<br>            }<br>        }</pre><p>All we have done is update the code with 2 new functions, one is for login and the other to generate a JWT token, We have used the <em>HMAC SHA256 algorithm with a secret key which we will generate for each project.</em></p><p>update <strong>src/views/users_views.py</strong></p><pre>from typing import Dict<br>from src.utils.db import get_db<br>from sqlalchemy.orm import Session<br>from fastapi import Depends, APIRouter<br>from src.controllers.users_controller import UserController<br><br>users_route = APIRouter()<br>@users_route.post(&quot;/signup/&quot;)<br>def signup(body: Dict, db: Session = Depends(get_db)):<br>    return UserController(db).signup(body)<br><br><br>@users_route.post(&quot;/login/&quot;)<br>def login(body: Dict, db: Session = Depends(get_db)):<br>    return UserController(db).login(body)</pre><p>once done just stop the server start again, and test it on Postman.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDtATY_HWCMOJ46gX9Xdtw.png" /></figure><p>We can see our login API is working perfectly well.</p><p>Now we need to protect our books add API that only authenticated users can access them. To do so we will create a simple function that will take request and db_session and verify that is auth header is present properly. If the auth header is present verify the user and return backs user object, then we can use the function in views to protect them with authenticated user requests only. let&#39;s start.</p><p>create a file <strong>src/utils/auth.py</strong> and write the below code in it.</p><pre>from typing import Annotated<br><br>import jwt<br>from src.models import Users<br>from src.utils.db import SessionLocal<br>from jwt.exceptions import InvalidTokenError<br>from starlette.responses import JSONResponse<br>from fastapi.security import OAuth2PasswordBearer<br>from fastapi import HTTPException, Depends, status<br>from src.utils.constants import SECRET_KEY, ALGORITHM<br><br>oauth2_scheme = OAuth2PasswordBearer(tokenUrl=&quot;token&quot;)<br><br>async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):<br>    credentials_exception = HTTPException(<br>        status_code=status.HTTP_401_UNAUTHORIZED,<br>        detail=&quot;Could not validate credentials&quot;,<br>        headers={&quot;WWW-Authenticate&quot;: &quot;Bearer&quot;},<br>    )<br>    try:<br>        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])<br>        print (payload)<br>        email: str = payload.get(&quot;email&quot;)<br>        if email is None:<br>            raise credentials_exception<br>    except InvalidTokenError:<br>        raise credentials_exception<br><br>    try:<br>        with SessionLocal() as db:<br>            user_Obj = db.query(Users).filter(<br>                Users.email == email<br>            ).first()<br>            return user_Obj<br>    except HTTPException as e:<br>        return JSONResponse(status_code=e.status_code, content={&quot;message&quot;: e.detail})</pre><p>Now let&#39;s update our <strong>src/views/books_views.py</strong> to make sure only authenticated users can add books to our database. To do so simply update the books_views.py code below.</p><pre>from src.models import Users<br>from src.utils.db import get_db<br>from sqlalchemy.orm import Session<br>from typing import Dict, Annotated<br>from fastapi import Depends, APIRouter<br>from src.utils.auth import get_current_user<br>from src.controllers.books_controller import BooksController<br><br>books_route = APIRouter()<br>@books_route.post(&quot;/books/&quot;)<br>def add_books_api(body: Dict, current_user: Annotated[Users, Depends(get_current_user)], db: Session = Depends(get_db)):<br>    print (&quot;User is found, continue adding data&quot;, current_user)<br>    return BooksController(db).add_book(body)<br><br>@books_route.get(&quot;/books/&quot;)<br>def get_books_api(db: Session = Depends(get_db)):<br>    return BooksController(db).get_all_books()</pre><p>Test add book requests without headers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3wm47O2fp4XS6pZVxQUdrg.png" /></figure><p>Now when we try to add a book without an Authentication header it throws an error.</p><pre>{<br>    &quot;detail&quot;: &quot;Your are not authorised to add book, kindly login&quot;<br>}</pre><p>With proper Authentication headers, we can add our book successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9kkTC0Y7gWeSDMQMYA7uvA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nb9PFNCAdph9G70z7QCckg.png" /></figure><p>To get the complete code for the above tutorial kindly refer to <a href="https://github.com/dextrop/SimpleFastAPI/tree/authentication">Github Link</a></p><p>Check out the video tutorial</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAk8yiKnyqyA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAk8yiKnyqyA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAk8yiKnyqyA%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/33644ee14d412910aa113351320da005/href">https://medium.com/media/33644ee14d412910aa113351320da005/href</a></iframe><p>For further queries, you can contact us on <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a></p><p>Join our discord community for a better learning experience <a href="https://discord.gg/ysEBHtSwfe">https://discord.gg/ysEBHtSwfe</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738eab93f6a9" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/secure-your-fastapi-application-implementing-jwt-authentication-for-login-signup-738eab93f6a9">Secure Your FastAPI Application: Implementing JWT Authentication for Login &amp; Signup</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[10 Advanced PythonTricks for Experienced Developers]]></title>
            <link>https://blog.devgenius.io/10-advanced-pythontricks-for-experienced-developers-c283e637d534?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/c283e637d534</guid>
            <category><![CDATA[python-tips-and-tricks]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-tricks]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 13:25:00 GMT</pubDate>
            <atom:updated>2025-02-04T17:31:50.419Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Here’s a list of 10 Python tricks and tips with real-life examples to make your coding more efficient and powerful:</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sbFIfw8TJFJAH6RPXuNZUw.png" /></figure><h3><strong>Walrus Operator (</strong><strong>:=)</strong></h3><p>Allows you to assign values to variables as part of an expression. Useful in loops and comprehensions for efficiency.</p><p>The Walrus Operator is useful in while loops to assign and test a value in the same expression, especially when dealing with input or iterative calculations.</p><pre># User input processing<br>user_input = input(&quot;Enter a number (or &#39;quit&#39; to exit): &quot;)<br>while (user_input := input(&quot;Enter a number (or &#39;quit&#39; to exit): &quot;)) != &#39;quit&#39;:<br>    print(f&#39;You entered: {user_input}&#39;)</pre><h3><strong>Dictionary Merge and Update Operators:</strong></h3><p>In Python 3.9 and later, two new dictionary operators were introduced: the merge operator (|) and the update operator (|=).</p><p><strong>Merging Two Dictionaries</strong></p><p>The merge operator | creates a new dictionary by combining the contents of two dictionaries. If there are overlapping keys, the values from the right-hand dictionary overwrite those from the left-hand dictionary.</p><pre># Define two dictionaries<br>dict1 = {&#39;a&#39;: 1, &#39;b&#39;: 2}<br>dict2 = {&#39;b&#39;: 3, &#39;c&#39;: 4}<br><br># Merge dictionaries<br>merged_dict = dict1 | dict2<br>print(merged_dict)  # Output: {&#39;a&#39;: 1, &#39;b&#39;: 3, &#39;c&#39;: 4}</pre><p>This example shows how to merge two dictionaries into a new one, where the second dictionary’s values override the first if the keys overlap.</p><p><strong>Updating a Dictionary In-Place</strong></p><p>The update operator |= updates the original dictionary in place by adding items from another dictionary. Similar to the merge operator, overlapping keys in the original dictionary are overwritten.</p><pre># Define two dictionaries<br>dict1 = {&#39;a&#39;: 1, &#39;b&#39;: 2}<br>dict2 = {&#39;b&#39;: 3, &#39;c&#39;: 4}<br><br># Update dict1 with dict2<br>dict1 |= dict2<br>print(dict1)  # Output: {&#39;a&#39;: 1, &#39;b&#39;: 3, &#39;c&#39;: 4}</pre><p>In this example, dict1 is updated in place, incorporating the values from dict2.</p><h3><strong>Lru_cache for Memoization</strong></h3><p>Use functools.lru_cache to cache expensive function calls.</p><pre>from functools import lru_cache<br><br>@lru_cache(maxsize=100)<br>def fib(n):<br>    if n &lt; 2:<br>        return n<br>    return fib(n-1) + fib(n-2)</pre><h3>Enum for Readable Constants</h3><p>The Enum class in Python is used to define enumerations, which are a set of symbolic names bound to unique, constant values. Using enums makes code more readable and maintainable by ensuring that symbolic names are used instead of arbitrary, often unexplained numeric values.</p><pre>from enum import Enum<br><br>class Day(Enum):<br>    MONDAY = 1<br>    TUESDAY = 2<br>    WEDNESDAY = 3<br>    THURSDAY = 4<br>    FRIDAY = 5<br>    SATURDAY = 6<br>    SUNDAY = 7<br># Accessing an enum member<br>print(Day.MONDAY)<br>print(Day.FRIDAY.value)  # Output the associated value</pre><p>Enums are perfect for representing a group of related values like days of the week, where each day can be referred to by a symbolic name instead of a number.</p><h3><strong>Zip to Iterate Over Multiple Iterables Simultaneously</strong>:</h3><p>Useful for iterating over two lists in parallel.</p><pre>names = [&quot;Alice&quot;, &quot;Bob&quot;, &quot;Charlie&quot;]<br>ages = [24, 30, 18]<br>for name, age in zip(names, ages):<br>    print(f&quot;{name} is {age} years old&quot;)</pre><h3>Context Managers for Resource Management</h3><p>Context managers in Python are a powerful feature for resource management, providing a way to allocate and release resources precisely when needed.</p><p>Use with statement to handle automatic resource management.</p><pre>with open(&#39;file.txt&#39;, &#39;r&#39;) as f:<br>    file_contents = f.read()</pre><h3><strong>Dynamic Imports with </strong><strong>importlib</strong>:</h3><p>Import modules dynamically.</p><pre>from importlib import import_module<br>math = import_module(&#39;math&#39;)<br>math.sqrt(4)</pre><p>Dynamic imports in Python, facilitated by the importlib module, allow for loading modules programmatically at runtime rather than at the start of a script. This feature is especially useful in various scenarios and offers numerous benefits:</p><p><strong>1. Reducing Startup Time</strong></p><p>Dynamic imports can significantly decrease the initial loading time of an application by postponing the import of a module until it’s actually needed. This is particularly advantageous for large applications with many dependencies, where importing everything upfront can lead to unnecessary delays.</p><p><strong>2. Managing Memory Efficiently</strong></p><p>By importing modules only when required, dynamic imports help manage memory more efficiently. Modules that are only occasionally used do not occupy memory permanently, which is beneficial in environments with memory constraints.</p><p><strong>3. Flexibility in Loading Modules</strong></p><p>importlib allows developers to import modules based on variable names and conditions. This flexibility is key in situations where the module names might not be known ahead of time, such as when they depend on user inputs or configuration files.</p><pre>import importlib<br><br>module_name = &quot;math&quot;<br>math_module = importlib.import_module(module_name)<br>print(math_module.sqrt(16))  # Dynamically imported and used</pre><p><strong>4. Plugin and Extension Systems</strong></p><p>Dynamic imports are ideal for applications that support plugins or extensions. Developers can add new features or modules to the software without modifying the core application. This allows for loading only the plugins that are needed based on user configuration or runtime decisions.</p><pre># Suppose `plugin_name` is defined based on user input or a configuration file<br>plugin = importlib.import_module(f&quot;plugins.{plugin_name}&quot;)<br>plugin.run()  # Use the dynamically imported pluginp</pre><p><strong>5. Handling Optional Dependencies</strong></p><p>In cases where certain features of an application depend on libraries that not all users might have installed, dynamic imports make it possible to load those libraries only when the features are accessed. This practice avoids forcing all users to install all dependencies.</p><pre>def optional_feature():<br>    try:<br>        optional_lib = importlib.import_module(&quot;optional_lib&quot;)<br>    except ImportError:<br>        optional_lib = None<br><br>    if optional_lib:<br>            optional_lib.do_something()<br>        else:<br>            print(&quot;Optional feature not available.&quot;)</pre><p><strong>6. Custom Import Logic</strong></p><p>importlib provides the tools necessary to customize the import system itself, allowing for advanced behaviors like importing from non-standard sources, or implementing custom loaders that might handle security, compression, or encryption differently.</p><p><strong>7. Testing and Mocking</strong></p><p>Dynamic imports make it easier to substitute modules with mock implementations during testing, which can be particularly useful in unit testing where certain modules should not be loaded in their standard form.</p><p><strong>8. Conditional Imports for Cross-Platform Compatibility</strong></p><p>Applications that need to run on multiple platforms may use dynamic imports to conditionally import platform-specific modules. This ensures compatibility without loading unnecessary modules on a given platform.</p><pre>import sys<br>if sys.platform == &#39;win32&#39;:<br>    windows_specific = importlib.import_module(&quot;win_specific&quot;)<br>else:<br>    posix_specific = importlib.import_module(&quot;posix_specific&quot;)</pre><p>Overall, importlib and dynamic imports provide a powerful set of tools for managing the modularization of Python applications, enhancing the flexibility, scalability, and maintainability of large projects. They allow developers to optimize resource usage and tailor module loading to the specific requirements and conditions of their applications.</p><h3><strong>Attribute Existence Check with </strong><strong>hasattr</strong></h3><p>Check if an object has an attribute.</p><pre>class Car:<br>    def __init__(self, model, year):<br>        self.model = model<br>        self.year = year<br><br>car = Car(&quot;Toyota Camry&quot;, 2021)<br><br># Check if the car has a &#39;color&#39; attribute before accessing it<br>if hasattr(car, &#39;color&#39;):<br>    print(f&#39;The car color is: {car.color}&#39;)<br>else:<br>    print(&quot;No color information available.&quot;)<br><br># Output: No color information available.</pre><h3><strong>Dictionary </strong><strong>get() Method</strong></h3><p>Safely access dictionary keys.</p><pre>d = {&#39;a&#39;: 1, &#39;b&#39;: 2}<br>d.get(&#39;c&#39;, 0)</pre><h3><strong>Advanced Exception Handling</strong></h3><p>Catch multiple exceptions.</p><pre>try:<br>    # risky code<br>except (TypeError, ValueError) as e:<br>    # handle multiple exceptions</pre><h3>Slicing Tricks</h3><p>Python slicing is a powerful feature that allows you to access parts of sequences such as lists, strings, and tuples using a straightforward and concise syntax.</p><p><strong>Reverse strings or lists with slicing.</strong></p><p>You can reverse any sequence easily with the slicing trick [::-1]. This is one of the most well-known tricks in Python for quickly reversing a list or string.</p><pre># Reversing a list<br>my_list = [1, 2, 3, 4, 5]<br>reversed_list = my_list[::-1]<br>print(reversed_list)  # Output: [5, 4, 3, 2, 1]<br><br># Reversing a string<br>my_string = &quot;hello&quot;<br>reversed_string = my_string[::-1]<br>print(reversed_string)  # Output: &#39;olleh&#39;</pre><p><strong>Skipping Elements</strong></p><p>he slicing syntax allows you to skip elements within a sequence. You can do this by specifying a step in the slicing operation. This is particularly useful for selecting every nth element.</p><pre># Skipping elements in a list<br>numbers = list(range(10))<br>every_second = numbers[::2]<br>print(every_second)  # Output: [0, 2, 4, 6, 8]<br><br># Selecting every third character in a string<br>my_string = &quot;abcdefghijklmn&quot;<br>every_third = my_string[::3]<br>print(every_third)  # Output: &#39;adgjm&#39;</pre><p><strong>Creating Subsequences</strong></p><p>You can create subsequences by combining start and stop indices with a step. This allows for more complex selections and is handy for processing parts of sequences.</p><pre># Extracting a subsequence from a list<br>numbers = list(range(20))<br>subsequence = numbers[5:15:2]  # Start at index 5, end before index 15, step by 2<br>print(subsequence)  # Output: [5, 7, 9, 11, 13]<br><br># Substring from a string with steps<br>my_string = &quot;Hello, World!&quot;<br>substring = my_string[1:10:2]  # Start at index 1, end before index 10, step by 2<br>print(substring)  # Output: &#39;el,W&#39;</pre><p><strong>Using Negative Indices</strong></p><p>Python supports negative indexing in slices, which is extremely useful for referencing the end of a sequence without needing to know its length.</p><pre># Accessing last elements<br>my_list = [1, 2, 3, 4, 5, 6]<br>last_three = my_list[-3:]<br>print(last_three)  # Output: [4, 5, 6]<br><br># Substring from the end of a string<br>my_string = &quot;Hello, World!&quot;<br>last_part = my_string[-5:]<br>print(last_part)  # Output: &#39;orld!&#39;</pre><p><strong>Modifying Lists In-Place</strong></p><p>Slices can also be used to modify lists in place. This can include changing values or inserting and deleting elements.</p><pre># Replacing elements<br>my_list = [1, 2, 3, 4, 5]<br>my_list[1:4] = [9, 9, 9]  # Replace elements at index 1 to 3<br>print(my_list)  # Output: [1, 9, 9, 9, 5]<br><br># Deleting elements using slices<br>my_list = [1, 2, 3, 4, 5]<br>del my_list[::2]  # Delete every second element<br>print(my_list)  # Output: [2, 4]<br><br># Inserting elements without replacing<br>my_list = [1, 2, 3, 4, 5]<br>my_list[2:2] = [999]  # Insert at index 2 without replacement<br>print(my_list)  # Output: [1, 2, 999, 3, 4, 5]</pre><p>Join our discord community for better learning experience <a href="https://discord.gg/D2EU5N6z">https://discord.gg/D2EU5N6z</a></p><p>For further queries, you can contact me at <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a>. If you liked the article do clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c283e637d534" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/10-advanced-pythontricks-for-experienced-developers-c283e637d534">10 Advanced PythonTricks for Experienced Developers</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Django Context Processors: How to Implement Context Processors in Django]]></title>
            <link>https://blog.devgenius.io/django-context-processors-how-to-implement-context-processors-in-django-ed181ca73e74?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed181ca73e74</guid>
            <category><![CDATA[context-processor]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 07:18:49 GMT</pubDate>
            <atom:updated>2025-02-04T17:32:06.971Z</atom:updated>
            <content:encoded><![CDATA[<p>Django is a strong web framework that follows the Don’t Repeat Yourself (DRY) principle. It uses something called Context Processors to help with this. In this article, we’ll explore what Context Processors are, how they function, and how you can use them in your Django projects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*dVres_nXQ6qKhU48bwSihA.jpeg" /></figure><h3>What are Context Processors?</h3><p>A context processor is a function that takes the current HttpRequest object as input and returns a dictionary of variables that you can use in all your templates. These variables are added to the context of the request, which means you can access them in any template that comes up during that request. This lets you add common information, like a site logo or user details, to every page of your website without repeating the same code in different views.</p><h3>How do Context Processors work?</h3><p>When you make a request to your Django application, the framework processes it by going through various middleware and view functions to come up with a response. After a view function sends back a TemplateResponse object, Django starts to render the related template.</p><p>During this rendering process, Django checks for any context processors you’ve set up in your application’s settings. For each context processor it finds, Django runs the corresponding function and puts the returned dictionary of variables into the template’s context. This means that by the time the template is fully rendered, all the variables added by the context processors are available for use in the template.</p><h3>When to use Context Processors?</h3><p>Example of using a context processor in Django could be to display user-specific information — like a user’s profile picture or username — across multiple pages of a website without having to manually include these details in every view.</p><p>Here’s a detailed breakdown of how you could set this up:</p><ul><li><strong>Create the context processor</strong>: First, you’ll need to create a new Python file in one of your apps, perhaps named context_processors.py. Inside this file, you&#39;ll write a function to add the user&#39;s profile picture and username to the context:</li></ul><pre>def user_info(request):<br>    # Check if the user is authenticated<br>    if request.user.is_authenticated:<br>        return {<br>            &#39;username&#39;: request.user.username,<br>            &#39;profile_picture&#39;: request.user.profile.profile_picture.url<br>        }<br>    else:<br>        return {}  # Return an empty dict if the user is not logged in</pre><p>This assumes that the user profile picture is accessible via a related Profile model.</p><ul><li><strong>Add the context processor to your settings</strong>: Next, include this context processor in your Django settings under the TEMPLATES configuration. This will activate the context processor for use across all templates:</li></ul><pre>TEMPLATES = [<br>    {<br>        ...<br>        &#39;OPTIONS&#39;: {<br>            &#39;context_processors&#39;: [<br>                ...<br>                &#39;your_app_name.context_processors.user_info&#39;,<br>            ],<br>        },<br>    },<br>]</pre><ul><li><strong>Use the context variables in your templates</strong>: With the context processor set up, you can now use {{ username }} and {{ profile_picture }} in any of your templates. For example, in a navbar template, you could show the user&#39;s information like this:</li></ul><pre>&lt;nav&gt;<br>    &lt;span&gt;Welcome, {{ username }}!&lt;/span&gt;<br>    &lt;img src=&quot;{{ profile_picture }}&quot; alt=&quot;Profile picture&quot;&gt;<br>&lt;/nav&gt;</pre><p>This approach ensures that any page including the navbar will display the current user’s username and profile picture without each view needing to pass these details explicitly. This not only adheres to the DRY principle but also simplifies the management of user data across your application.</p><h3>Additional information about context processors:</h3><p>It is worth mentioning that context processors can also take additional arguments such as request user, session, etc.<br>For example, you can use the user object in the context processor and conditionally show or hide certain elements on the website based on user permissions and authentication.</p><p>In addition, if you are working with a large project or have multiple context processors, you can organize them in different files and different folders for better organization.</p><p>Another important thing to consider is the performance of your context processors. As context processors are called on every request, it’s important to make sure that the code inside your context processors is optimized for performance. This may include caching or pre-fetching certain data to reduce the number of database queries.</p><p>Join our discord community for better learning experience <a href="https://discord.gg/D2EU5N6z">https://discord.gg/D2EU5N6z</a></p><p>For further queries, you can contact me at <a href="https://www.linkedin.com/in/dextrop/">https://www.linkedin.com/in/dextrop/</a>. If you liked the article do clap.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed181ca73e74" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/django-context-processors-how-to-implement-context-processors-in-django-ed181ca73e74">Django Context Processors: How to Implement Context Processors in Django</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to query multiple tables using join in FastAPI + SqlAlchemy]]></title>
            <link>https://medium.com/aimonks/how-to-query-multiple-tables-using-join-in-fastapi-sqlalchemy-6c7981b408fe?source=rss-2aabcad7f5ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c7981b408fe</guid>
            <category><![CDATA[fastapi-guide]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[fastapi-tutorials]]></category>
            <dc:creator><![CDATA[Saurabh Pandey]]></dc:creator>
            <pubDate>Wed, 29 Jan 2025 09:54:14 GMT</pubDate>
            <atom:updated>2025-01-31T10:44:04.787Z</atom:updated>
            <content:encoded><![CDATA[<p>To implement a join query in FastAPI using SQLAlchemy, you’ll need to set up your models and then construct a query in one of your route handlers to fetch data from multiple tables based on certain relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*YnUrQxvOXvD_HTLgpvlHTA.png" /></figure><p>Let’s walk through a simple example from a simple blog website that involves two tables: User and Post, where a user creates each post.</p><p>Lets check below model to continue with the assignment</p><pre>from sqlalchemy import Column, Integer, String, ForeignKey, create_engine<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import relationship, sessionmaker<br><br>Base = declarative_base()<br><br>class User(Base):<br>    __tablename__ = &#39;users&#39;<br>    <br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    name = Column(String)<br>    .....<br><br>    # Relationship to posts<br>    posts = relationship(&quot;Post&quot;, back_populates=&quot;user&quot;)<br><br>class Post(Base):<br>    __tablename__ = &#39;posts&#39;<br>    <br>    id = Column(Integer, primary_key=True, autoincrement=True)<br>    title = Column(String)<br>    user_id = Column(Integer, ForeignKey(&#39;users.id&#39;))<br>    .....<br><br>    # Relationship to user<br>    user = relationship(&quot;User&quot;, back_populates=&quot;posts&quot;)</pre><p>We can see there are two tables, User and Post. the table Post contains a ForeignKey referring to the user table users.id</p><p>Apart from ForiegnKey we have also declared two extra columns 1 in user linking</p><pre>posts = relationship(&quot;Post&quot;, back_populates=&quot;user&quot;) # in user table</pre><pre>user = relationship(&quot;User&quot;, back_populates=&quot;posts&quot;) # in users table</pre><p>Although the join query can work without it, But there are benefits of using relationship columns.</p><p><strong>Benefits of </strong><strong>relationship() and </strong><strong>back_populates</strong></p><ul><li><strong>Navigation</strong>: Allows you to navigate the association between models easily. You can move from Post to User via post.user, and from User to Post via user.posts.</li><li><strong>Synchronization</strong>: Ensures that related objects remain in sync. If a Post is added to user.posts, post.user is automatically set to that user.</li><li><strong>Query Optimization</strong>: Facilitates more efficient queries. SQLAlchemy can use the relationship to automatically perform JOINs between tables when querying related objects, improving performance and reducing code complexity.</li><li><strong>Ease of Use</strong>: Simplifies the management of related objects. Adding and removing items from a relationship automatically updates foreign keys and relationship attributes.</li></ul><p>Using relationship() with back_populates thus provides a robust way to handle database relations in an object-oriented fashion, making data interactions more intuitive and maintaining integrity between related data sets.</p><p><strong>To get a user with all his posts</strong></p><pre>    user = db.query(User).filter(User.id == user_id).first()</pre><p>as we have defined the relationship column in the Users table we don&#39;t even need to use join query</p><p><strong>To get all post with user information ( Join QUERY )</strong></p><p>Now to get all post with user information we can use the below join query in FastAPI ORM</p><pre>posts = db.query(Post).join(User).filter(User.id == user_id).all() </pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c7981b408fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/aimonks/how-to-query-multiple-tables-using-join-in-fastapi-sqlalchemy-6c7981b408fe">How to query multiple tables using join in FastAPI + SqlAlchemy</a> was originally published in <a href="https://medium.com/aimonks">𝐀𝐈 𝐦𝐨𝐧𝐤𝐬.𝐢𝐨</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>