<?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 Snehal Shelar on Medium]]></title>
        <description><![CDATA[Stories by Snehal Shelar on Medium]]></description>
        <link>https://medium.com/@snehal.shelar?source=rss-4fa19db701b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*JySaTdk1lu0b0j3c</url>
            <title>Stories by Snehal Shelar on Medium</title>
            <link>https://medium.com/@snehal.shelar?source=rss-4fa19db701b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 21:36:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@snehal.shelar/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[Build Dynamic Behavior: Registry-Based Strategy for Scalable FastAPI App]]></title>
            <link>https://medium.com/@snehal.shelar/build-dynamic-behavior-registry-based-strategy-for-scalable-fastapi-app-3e74c1f5952e?source=rss-4fa19db701b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e74c1f5952e</guid>
            <category><![CDATA[software-design-patterns]]></category>
            <category><![CDATA[registry-pattern]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <dc:creator><![CDATA[Snehal Shelar]]></dc:creator>
            <pubDate>Thu, 20 Nov 2025 05:51:00 GMT</pubDate>
            <atom:updated>2025-11-20T05:51:00.609Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Dynamic Behavior: Registry-Driven Strategy Pattern for Scalable FastAPI Apps</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hvSNBZZECJ2kHk54" /><figcaption>Photo by <a href="https://unsplash.com/@georgebakos?utm_source=medium&amp;utm_medium=referral">George Bakos</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote><strong><em>Introduction</em></strong></blockquote><p>When building scalable APIs, one of the most common challenges developers face is managing multiple implementations of the same functionality while keeping the codebase maintainable and extensible. Whether you’re implementing feature flags, A/B testing, or simply need to support multiple algorithms, the combination of Strategy and Registry patterns offers an elegant solution.</p><p>In this article, I’ll walk you through how I used the <strong>Strategy</strong> design pattern together with a <strong>registry-based factory</strong> in a FastAPI app to dynamically swap out implementations at runtime and making the system clean, testable, and truly extensible.</p><blockquote><strong><em>The Problem</em></strong></blockquote><p>Imagine you’re building an API that needs to support multiple strategies for processing data, perhaps you have a legacy implementation and a new improved version, or different algorithms for different client requirements. You need a clean way to:</p><ul><li>Switch between implementations without changing client code</li><li>Add new strategies without modifying existing code</li><li>Keep the codebase maintainable and testable</li><li>Configure which strategy to use at runtime</li></ul><blockquote><strong><em>The Solution: Registry-Driven Strategy Pattern</em></strong></blockquote><p>The architecture I implemented uses two complementary patterns:</p><ol><li><strong>Strategy Pattern<br></strong>This pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. This lets the algorithm vary independently from clients that use it.</li><li><strong>Registry Pattern<br></strong>This Pattern provides a centralized repository where objects or services are registered and retrieved by key, enabling different parts of an application to access shared instances without tightly coupling to their creation.</li></ol><blockquote><strong><em>Architecture Overview</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*C5303hCCOmTzP6XEvV2-dw.png" /><figcaption>Approach Class Diagram</figcaption></figure><p>Let me break down the key components of this implementation:</p><ol><li><strong>Context</strong></li></ol><ul><li>This serves as the main entry point that clients interact with. It holds a reference to the concrete strategy and delegates the work to it. The context doesn’t -know the specifics of how each strategy works, it just knows the interface.</li></ul><pre>class StrategyContext:<br>  def __init__(self, strategy: StrategyProviderInterface):<br>    self._strategy = strategy<br><br>  def set_strategy(self, strategy: StrategyProviderInterface):<br>    self._strategy = strategy<br><br>  def play(self) -&gt; str:<br>    result = self._strategy.select_choice()<br>    return result</pre><p><strong>2. Strategy Interface</strong></p><ul><li>This defines the contract that all concrete strategies must follow. It ensures that the context can work with any strategy implementation interchangeably.</li></ul><pre>from abc import ABC, abstractmethod<br><br><br>class StrategyProviderInterface(ABC):<br><br>    @abstractmethod<br>    def select_choice(self) -&gt; str:<br>        pass</pre><p><strong>3. Concrete Strategies<br></strong>Each strategy implements the same interface but provides different business logic.</p><pre>from app.strategy_interface import StrategyProviderInterface<br><br><br>class RockStrategy(StrategyProviderInterface):<br><br>    def select_choice(self) -&gt; str:<br>        return &quot;Rock&quot;<br><br>class PaperStrategy(StrategyProviderInterface):<br><br>    def select_choice(self) -&gt; str:<br>        return &quot;Paper&quot;<br><br>class ScissorsStrategy(StrategyProviderInterface):<br><br>    def select_choice(self) -&gt; str:<br>        return &quot;Scissors&quot;</pre><p><strong>4. Factory Registry</strong></p><ul><li>The factory is responsible for creating the appropriate strategy instance based on configuration or runtime parameters. This is where the magic happens, deciding which implementation to use.</li></ul><pre>class StrategyProviderFactory:<br>    <br>    _providers: Dict[str, Type[StrategyProviderInterface]] = {<br>        &quot;rock&quot;: RockStrategy,<br>        &quot;paper&quot;: PaperStrategy,<br>        &quot;scissor&quot;: ScissorsStrategy<br>    }<br><br>    @classmethod<br>    def get_provider(cls, provider_name: str) -&gt; StrategyProviderInterface:<br>       provider_cls = cls._providers.get(provider_name)<br>       if not provider_cls:<br>           raise ValueError(f&quot;Unsupported strategy provider: {provider_name}&quot;)<br>       return provider_cls()<br><br><br>def get_strategy_provider() -&gt; StrategyProviderInterface:<br>    provider_name = &quot;rock&quot;<br>    return StrategyProviderFactory.get_provider(provider_name)</pre><blockquote><strong><em>Key Benefits</em></strong></blockquote><ol><li><strong>Open/Closed Principle:</strong> The system is open for extension (adding new strategies) but closed for modification (existing code doesn’t need to change).</li><li><strong>Single Responsibility: </strong>Each strategy class has one job: implementing its specific algorithm. The factory has one job: creating strategies. The context has one job: executing strategies.</li><li><strong>Easy Testing: </strong>Each strategy can be tested independently. You can also mock strategies when testing the context or factory.</li><li><strong>Runtime Flexibility: </strong>Switching strategies is as simple as passing a different parameter, no code deployment required.</li><li><strong>Clean Dependency Management: </strong>FastAPI’s dependency injection works beautifully with this pattern, making it easy to configure strategies based on environment variables, user permissions, or feature flags.</li></ol><blockquote><strong><em>Real-World Use Cases</em></strong></blockquote><p>This pattern shines in scenarios like:</p><ul><li>Feature rollouts: Gradually migrate users from old to new implementations.</li><li>A/B testing: Run different algorithms for different user segments.</li><li>Multi-tenancy: Different clients get different implementations.</li><li>Algorithm optimization: Test performance of different approaches in production.</li><li>Backward compatibility: Support legacy and modern approaches simultaneously.</li></ul><blockquote><strong><em>Final Thoughts</em></strong></blockquote><p>The <strong>Registry-Driven Factory Pattern</strong> creates a powerful architecture not just for FastAPI, but for any applications that need to adapt and scale. We’ve seen how clean separation of concerns, factory for creation, strategy for execution, interface for contracts, leads to code that’s not just maintainable, but enjoyable to work with.</p><p>The beauty of this approach lies in its simplicity: <strong>one interface, multiple implementations, zero coupling</strong>.</p><p><strong>Remember:</strong> Good design patterns aren’t about adding complexity, they’re about managing it. These patterns give you the structure to build features quickly today while keeping your options open for tomorrow.</p><p><strong>Ready to refactor?</strong> Start small. Pick one area where you’re switching between implementations, apply these patterns, and watch your code transform from rigid to flexible.</p><blockquote><em>“Want to dive into the full code? Check out the boilerplate on GitHub, It’s the registry-based Strategy + Factory setup from this article.”</em></blockquote><p><a href="https://github.com/SnehaShelar/strategy-pattern">GitHub - SnehaShelar/strategy-pattern</a></p><blockquote><strong><em>Further Readings</em></strong></blockquote><ul><li><a href="https://refactoring.guru/design-patterns/strategy">https://refactoring.guru/design-patterns/strategy</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e74c1f5952e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying a FastAPI App Serverlessly: AWS Lambda Function URL+Mangum]]></title>
            <link>https://medium.com/@snehal.shelar/deploying-fastapi-app-serverlessly-aws-lambda-function-url-mangum-e87f6c643c67?source=rss-4fa19db701b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e87f6c643c67</guid>
            <dc:creator><![CDATA[Snehal Shelar]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 13:09:19 GMT</pubDate>
            <atom:updated>2026-06-16T05:46:11.371Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Introduction</em></strong></blockquote><p>After completing AWS’s <em>Technical Essentials</em> and <em>Cloud Essentials</em> courses, I’m continuing to learn AWS Cloud. To apply what I’ve learned into practice, I decided to redeploy an older project using a serverless architecture. My <strong>FastAPI</strong> backend now runs on <strong>AWS</strong> <strong>Lambda</strong> (wrapped with <strong>Mangum</strong> for ASGI support), and <strong>CloudWatch </strong>to<strong> </strong>handles logs and monitoring.</p><p>In this post, I will walk you through every step I took and how I packaged dependencies, configured <strong>Lambda</strong> via the <strong>AWS</strong> <strong>Console</strong>, connected the static frontend, enabled logging, and resolved some of the frustrating pitfalls along the way. Whether you’re exploring serverless for the first time or trying to make your deployment cleaner, I hope this guide gives you real-world insights plus theoretical grounding.</p><blockquote><strong><em>Understanding the Key Players</em></strong></blockquote><p>Here’s how the components interact:</p><ul><li><strong>FastAPI</strong> handles the API endpoints.</li><li><strong>Mangum</strong> adapts FastAPI (an <strong>ASGI </strong>framework) to work within AWS Lambda’s event model.</li><li><strong>AWS Lambda</strong> hosts the backend without needing a persistent server.</li><li><strong>CloudWatch</strong> is used for monitoring logs, errors, and performance metrics.</li><li><strong>S3 Static Website Hosting</strong> serves your HTML templates and front-end static assets.</li></ul><blockquote><strong><em>Prerequisites</em></strong></blockquote><ul><li>FastAPI Application</li><li>AWS account + IAM permissions</li><li>Python environment + Mangum installed</li></ul><blockquote><strong><em>Step-by-Step Deployment</em></strong></blockquote><h4>1. FastAPI + Mangum Setup</h4><p><strong>a. Install dependencies</strong></p><pre>pip install fastapi mangum</pre><p><strong>b. Create a Handler function</strong></p><pre>from fastapi import FastAPI<br>from mangum import Mangum<br>from fastapi.middleware.cors import CORSMiddleware<br><br>app = FastAPI()<br>app.add_middleware(<br>    CORSMiddleware,<br>    allow_origins=[&quot;*&quot;],<br>    allow_credentials=True,<br>    allow_methods=[&quot;*&quot;],<br>    allow_headers=[&quot;*&quot;],<br>)<br><br>@app.get(&quot;/&quot;)<br>def read_root():<br>    return {&quot;message&quot;: &quot;Hello from FastAPI!&quot;}<br><br>lambda_handler = Mangum(app)</pre><ul><li>In <strong>main.py</strong>, create a function using <strong>Mangum</strong> to wrap your FastAPI application. This function will be the entry point for your Lambda function call.</li></ul><h4>2. Bundle your application and dependencies</h4><p><strong>a. Create a dependencies directory</strong></p><pre>pip install -t dependencies -r requirements.txt</pre><ul><li>This command gathers all your project dependencies into a dedicated <strong>dependencies</strong> folder.</li></ul><p><strong>b. Zip the dependencies</strong></p><pre>(cd dependencies; zip ../aws_lambda_artifact.zip -r .)</pre><ul><li>Zipping these dependencies ensures they’re packaged together for smooth deployment.</li></ul><p><strong>c. Add your main.py file to the zip</strong></p><pre>zip aws_lambda_artifact.zip -u main.py</pre><ul><li>Include your <strong>main.py</strong> file within the zip, ensuring everything is ready for lambda.</li></ul><h4>3. Deploy to AWS Lambda using Console</h4><ul><li>Now that our <strong>FastAPI</strong> app is bundled with the <strong>Mangum</strong> handler, it’s time to deploy to AWS Lambda.</li></ul><p><strong>Step 1</strong>: Open the AWS Management Console, go to <em>Lambda → Functions</em>, and click <strong>Create function</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W39dN2A4-tEUKL7iGveehg.png" /><figcaption>1.0 AWS Console -&gt; Search Lambda -&gt; Create Function</figcaption></figure><p><strong>Step 2</strong>: In the <em>Function Configuration</em> section, Choose “<strong>Author from scratch</strong>” and provide the function name, select the Python runtime (e.g. Python 3.x), and choose or create an IAM execution role with basic Lambda permissions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUY4Y3eLGZEoHrE3ud_RdA.png" /><figcaption>1.1 Function Config.</figcaption></figure><p><strong>Step 3</strong>: Go to the <em>Code</em> tab, upload your aws_lambda_artifact.zip file containing your application code and dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FzwtAtpqpsX57q-RMA2qyg.png" /><figcaption>1.2 Function Code</figcaption></figure><p><strong>Step 4</strong>: Under <em>Runtime settings</em>, set the handler to the Mangum object you defined in main.py (e.gmain.lambda_handler). This tells Lambda how to invoke your ASGI app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mBuiNe76dNmrfTql3oBRrg.png" /><figcaption>1.3 Runtime settings</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tgIkg3NiCqjnbWpUuCJ6A.png" /><figcaption>1.4 Update runtime</figcaption></figure><p><strong>Step 5</strong>: Next, navigate to <em>Configuration → Function URL</em>, click <strong>Create Function URL</strong>, select the authorization type (e.g. NONE for public access), configure CORS if needed, and copy the generated URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u5BbGM6CfkG1bEDfSzQPcQ.png" /><figcaption>1.5 Configuration -&gt; Function URL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*or7AiIAtLt5MPZRpsu5RUg.png" /><figcaption>1.6 Configure Function URL Auth</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gU5rhx4mBr27QfHPPqoHMA.png" /><figcaption>1.7 Configure CORS</figcaption></figure><ul><li>After clicking the Save, you can copy the generated function URL and access the interactive API documentation at https://&lt;your-function-url&gt;/docs. That’s Swagger UI, automatically provided by FastAPI (via its OpenAPI schema).</li></ul><p><strong>Step 6</strong>: Finally, to verify everything is working and for debugging, go to <strong>CloudWatch</strong> <strong>Logs</strong>. Open the log group associated with your Lambda function to inspect invocation logs, error messages, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CxMV4k68N9bGZGIlBTtqqw.png" /><figcaption>1.8 View CloudWatch Logs</figcaption></figure><h4><strong>4. Integrate the Lambda Function URL with Static Frontend</strong></h4><ul><li>Now that your Lambda Function URL is up and running, you’ll want your static frontend (hosted on S3) to call it. Here is how to do that safely and correctly.</li></ul><p><strong>a. Configure CORS</strong></p><p>Make sure when you created the Function URL, you configured CORS settings:</p><ul><li>Allowed Origins (e.g. https://your-static-site-domain or * for public)</li><li>Allowed Methods (e.g. GET, POST)</li><li>Allowed Headers (e.g. Content-Type, Authorization if needed)</li></ul><p>This ensures your browser isn’t blocked by cross-origin restrictions.</p><h4>b. In static HTML / JS, call the Function URL</h4><p>Here’s a simple example of how your HTML + JavaScript might look:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>&lt;head&gt;<br>  &lt;title&gt;Static Frontend&lt;/title&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>  &lt;h1&gt;Fetch data from backend&lt;/h1&gt;<br>  &lt;button id=&quot;fetchBtn&quot;&gt;Get Message&lt;/button&gt;<br>  &lt;pre id=&quot;result&quot;&gt;&lt;/pre&gt;<br><br>  &lt;script&gt;<br>    const functionUrl = &#39;https://&lt;url-id&gt;.lambda-url.&lt;region&gt;.on.aws&#39;;<br><br>    document.getElementById(&#39;fetchBtn&#39;).addEventListener(&#39;click&#39;, async () =&gt; {<br>      try {<br>        const response = await fetch(functionUrl, {<br>          method: &#39;GET&#39;,<br>          headers: {<br>            &#39;Content-Type&#39;: &#39;application/json&#39;<br>          }<br>        });<br>        if (!response.ok) {<br>          throw new Error(`HTTP error! status: ${response.status}`);<br>        }<br>        const data = await response.json();<br>        document.getElementById(&#39;result&#39;).textContent = JSON.stringify(data, null, 2);<br>      } catch (err) {<br>        document.getElementById(&#39;result&#39;).textContent = &#39;Error: &#39; + err;<br>      }<br>    });<br>  &lt;/script&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>c. Deploy / Upload Static Frontend to S3</h4><ul><li>Upload the HTML / JS files to your S3 bucket.</li><li>Ensure S3 hosting is enabled and the bucket allows public access (or is set up via CloudFront / domain etc.)</li><li>If using HTTPS or a custom domain, ensure your static site is served securely.</li></ul><blockquote><strong><em>Common Challenges &amp; Solutions</em></strong></blockquote><p><strong>a. CORS Issues</strong>: If your frontend and backend are hosted on different origins (domains), you’ll need to properly configure CORS in several places:</p><ul><li>In your FastAPI app (via CORSMiddleware)</li><li>In the Lambda Function URL CORS configuration (via AWS Console or CLI)</li><li>And ensure that the static frontend (on S3) serves the correct headers.</li></ul><p><strong>b. Deployment Size</strong>: Lambda has a deployment size limit. Use Lambda layers or container images for larger applications.</p><blockquote><strong><em>Lambda Function URL Use Cases &amp; Limitations</em></strong></blockquote><p><strong>a. Use Cases</strong></p><ul><li>Quickly set up an HTTP endpoint for a single Lambda function (e.g. webhooks, small APIs).</li><li>Let a static frontend (on S3 or elsewhere) call the backend via HTTP without needing <strong>API</strong> <strong>Gateway</strong> overhead.</li><li>Prototyping / testing, getting something live fast.</li></ul><p><strong>b. Limitations</strong></p><ul><li>Less built-in security: Function URLs support only basic auth types like IAM or NONE, but don’t natively offer API keys, custom authorizers, etc.</li><li>If you need to restrict HTTP methods, you’ll have to enforce that in your Lambda code.</li><li>CORS must be correctly configured (both in Lambda Function URL and/or in app) to avoid browser errors.</li></ul><blockquote><strong><em>Further Readings</em></strong></blockquote><ul><li><a href="https://pypi.org/project/mangum/">https://pypi.org/project/mangum/</a></li><li><a href="https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html">https://docs.aws.amazon.com/lambda/latest/dg/urls-configuration.html</a></li></ul><blockquote><strong><em>Final Thoughts</em></strong></blockquote><p>That’s everything I’ve learned so far about <strong>Lambda Function URLs</strong> in my cloud journey. If you know of other use cases I might have missed, or limitations you’ve run into, I’d love to hear in the comments, always open to learning more.</p><p>Thanks for reading, and best of luck with your own deployments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e87f6c643c67" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modified Preorder Tree Traversal in Django]]></title>
            <link>https://medium.com/@snehal.shelar/modified-preorder-tree-traversal-a133de10f8b7?source=rss-4fa19db701b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a133de10f8b7</guid>
            <dc:creator><![CDATA[Snehal Shelar]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 14:05:56 GMT</pubDate>
            <atom:updated>2022-12-06T10:09:33.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LrpUZPvnhs7vVOERoUA-2A.jpeg" /></figure><p><strong>What is django-MPTT?</strong></p><p>MPTT is <a href="https://django-mptt.readthedocs.io/en/latest/overview.html">Modified Preorder Tree Traversal</a>. It’s an efficient way to store hierarchical data to your Django models. You can easily determine parent-child relationships.The aim is to make retrieval operations very efficient. Django-mptt is a reusable Django app which aims to make it easy for you to use MPTT with your own Django models.</p><p>It takes care of the details of managing a database table as a tree structure and provides tools for working with trees of model instances.</p><p><strong>What is Preorder Tree Traversal?</strong></p><p>The preorder traversal is a hierarchical data structure such as tree, there are multiple ways to traverse the data.</p><p>In preorder traversal, first, root node is visited, then left sub-tree and after that right sub-tree is visited. The process of preorder traversal can be represented as -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*CTfvDBPERLCzaOWKwFXN7A.png" /></figure><p>Root node is always traversed first in preorder traversal, while it is the last item of postorder traversal. Preorder traversal is used to get the prefix expression of a tree.</p><p>The steps to perform the preorder traversal are listed as follows -</p><ul><li>First, visit the root node.</li><li>Then, visit the left subtree.</li><li>At last, visit the right subtree.</li></ul><p>The preorder traversal technique follows the <strong>Root Left Right</strong> policy. The name preorder itself suggests that the root node would be traversed first.</p><blockquote><strong>Example of preorder traversal</strong></blockquote><p>Now, let’s see an example of preorder traversal. It will be easier to understand the process of preorder traversal using an example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/0*2miteT-JpGSnyNY1" /><figcaption>image 1.0</figcaption></figure><p>The nodes with blue color are not visited yet. Now, we will traverse the nodes of the above tree using preorder traversal.</p><p>Start with the root node 27. First, <strong>print 27</strong> and then recursively traverse the left subtree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/0*XdYXYP5zXVVnEfKJ" /><figcaption>image 1.1</figcaption></figure><p>Now, move to the left subtree. For left subtree, the root node is 02. <strong>print 02</strong>, and move towards the left subtree of 02.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/0*pySawKTT6SiG-7uS" /><figcaption>image 1.2</figcaption></figure><p>In left subtree of 02, there is an element 12, and 12 has no subtree. So, <strong>print 12</strong>, and move to the right subtree of 02.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*7yKWomG3mBUsyCBB" /><figcaption>image 1.3</figcaption></figure><p>In right subtree of 02, there is 15, and 15 has no subtree. So, <strong>print 15</strong>, and move to the right subtree of 27.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/0*F6VoZ2xBVvHw_hUN" /><figcaption>image 1.4</figcaption></figure><p>In the right subtree of 27, there is 24. <strong>print 24</strong>, and traverse the left subtree of 24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*LoGJohMn0j9o7KSr" /><figcaption>image 1.5</figcaption></figure><p>In the left subtree of 24, there is 17 that do not have any child. So, <strong>print 17</strong>, and traverse the right subtree of 24.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*ajP_RwjC5QlLj2x6" /><figcaption>image 1.6</figcaption></figure><p>In the right subtree of 24, there is 28 that do not have any child. So, <strong>print 28</strong> and stop the process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*692aSLX5UXh_CDDt" /><figcaption>image 1.7</figcaption></figure><p>After the completion of preorder traversal, the final output is -</p><p><strong>27, 02, 12, 15, 24, 17, 28</strong></p><p><strong>Implementation of django-MPTT</strong></p><p><strong>Installation</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*9UafvycVoAGyeVx_ULgBAw.png" /></figure><p>Add <strong>mptt</strong> to the <strong>INSTALLED_APPS</strong> in your settings.py file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3b0da30771a278774178834e6ef125e/href">https://medium.com/media/c3b0da30771a278774178834e6ef125e/href</a></iframe><p>I’ve used MPTT in one of my projects. Consider following models for django app.</p><p><strong>Example Models</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51e77a64f364202ed25982c51cbda05f/href">https://medium.com/media/51e77a64f364202ed25982c51cbda05f/href</a></iframe><p>We firstly add imports for the MPTTModel and TreeForeignKey classes from the django-mptt library. MPTTModel provides a base model. Then the Book and Chapter are defined. Chapter model will also have a number of other fields: level, lft, rght, and tree_id.</p><ul><li>lft : The name of a field which contains the left tree node edge indicator, which should be a PositiveIntegerField. Defaults to ‘lft’.</li><li>rght: The name of a field which contains the right tree node edge indicator, which should be a PositiveIntegerField. Defaults to ‘rght’.</li><li>level : The name of a field which contains the (zero-based) level at which an item sits in the tree, which should be a PositiveIntegerField. Defaults to ‘level’.</li><li>tree_id: The name of a field which contains the tree id of each node, which should be a PositiveIntegerField. Defaults to ‘tree_id’.</li></ul><p>It also provides following instance methods:</p><ul><li>get_ancestors(ascending=False, include_self=False)</li><li>get_children()</li><li>get_descendants(include_self=False)</li><li>get_descendant_count()</li><li>get_family()</li><li>get_next_sibling()</li><li>get_previous_sibling()</li><li><strong>get_root()</strong></li><li>get_siblings(include_self=False)</li><li><strong>insert_at(target, position=’first-child’, save=False)</strong></li><li>is_child_node()</li><li>is_leaf_node()</li><li>is_root_node()</li><li><strong>move_to(target, position=’first-child’)</strong></li></ul><p>Now create and apply the migrations to create the table in the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*r0j7Kh_u89RLSq0vLIbfAw.png" /></figure><p>Create new objects in shell :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gWRHGZf85PYg7607gyZmXQ.png" /></figure><blockquote><strong>get_descendants(include_self=False)</strong></blockquote><p>To get all the childs of <strong>MVT</strong> chapter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ojaI72APlwFPjwKcVI3mSg.png" /></figure><blockquote><strong>get_ancestors(ascending=False, include_self=False)</strong></blockquote><p>To get a listing of parent of <strong>Model Inheritance</strong> chapter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w_uwlWGN_9xl7nDQWSH0Wg.png" /></figure><blockquote><strong>get_root()</strong></blockquote><p>To get the root node of the MPTT tree (Dictionary):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAYej3ig_AtV11bt9WAuOA.png" /></figure><blockquote><strong>get_siblings(include_self=False)</strong></blockquote><p>To see all chapter on the same level as another:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E2XqzNKIfD8gW28whwxXQ.png" /></figure><p>To see the levels of all nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MsjuNLYZ_24_Qt9MBTjHZw.png" /></figure><blockquote><strong>get_children</strong>()</blockquote><p>To get the immediate children of particular node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iUmKSM20pjgpeS0cDqYQ4g.png" /></figure><blockquote><strong>get_family</strong>()</blockquote><p>To get the family of particular parent node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n-S6TZKO0O_LQnhL6b8PWw.png" /></figure><blockquote><strong>get_next_sibling</strong>()</blockquote><p>To get next sibling of particular node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yPOfH_TWPJqdW3KfrXlxw.png" /></figure><blockquote><strong>get_previous_sibling</strong>()</blockquote><p>To get previous sibling of particular node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bPTgcRc-AKyQeGKiIEKSvg.png" /></figure><blockquote><strong>move_to(target, position=’first-child’)</strong></blockquote><p>To move record to specific target node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XCFGsAY0MunQlkFd7FYGfQ.png" /></figure><blockquote><strong>insert_at(target, position=’first-child’, save=False)</strong></blockquote><p>https://gist.github.com/snehals21/1acb759dbe84099bd204b3335a4b8e75</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/286ff76c923876cf6f1d435088d749e4/href">https://medium.com/media/286ff76c923876cf6f1d435088d749e4/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a133de10f8b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>