<?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 sanju saini on Medium]]></title>
        <description><![CDATA[Stories by sanju saini on Medium]]></description>
        <link>https://medium.com/@coder-sanju?source=rss-24f48e8e4e17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nGtbUv_usS9ET515_YrNWQ@2x.jpeg</url>
            <title>Stories by sanju saini on Medium</title>
            <link>https://medium.com/@coder-sanju?source=rss-24f48e8e4e17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 06:10:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coder-sanju/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[How to Serve Django Admin and API on Separate Subdomains]]></title>
            <link>https://coder-sanju.medium.com/how-to-serve-django-admin-and-api-on-separate-subdomains-18170fff851f?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/18170fff851f</guid>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 08:19:50 GMT</pubDate>
            <atom:updated>2024-10-07T08:21:25.060Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*VcbjzI7vJPEh24S8GehfWQ.jpeg" /></figure><blockquote>‘Separating Django’s Admin panel and API on different subdomains can provide added security, cleaner organization, and more manageable scaling. In this guide, we’ll configure a Django project to run the Admin panel on one subdomain, such as admin.example.com, and the API on another, such as api.example.com. Using Django’s routing along with Nginx as a reverse proxy, this setup offers flexibility and security for your project.</blockquote><h3>Why Separate Admin and API?</h3><ol><li><strong>Enhanced Security</strong>: Isolating the Admin panel from the main API reduces exposure to potential security threats.</li><li><strong>Easier Scaling</strong>: Separating components allows for targeted scaling. For instance, you can prioritize scaling the API under high user demand while isolating the admin.</li><li><strong>Organized Management</strong>: With different domains, users can easily differentiate between API and admin endpoints, reducing the chance of accidental access.</li></ol><h3>Step 1: Set Up Django Settings</h3><h4>1.1 Add Subdomains to ALLOWED_HOSTS</h4><p>In Django’s settings.py, define the subdomains that will host the Admin panel and API. This allows Django to serve requests only from these specific domains.</p><pre># settings.py<br>ALLOWED_HOSTS = [&#39;api.example.com&#39;, &#39;admin.example.com&#39;]</pre><h4>1.2 Configure Separate URL Patterns for Admin and API</h4><p>Let’s create dedicated URL configuration files for both the Admin panel and API. This way, each subdomain will direct requests to a specific set of routes.</p><ol><li><strong>Create Admin and API URL Files</strong></li></ol><ul><li><strong>Admin URLs (</strong><strong>admin_urls.py)</strong>:</li></ul><pre># admin_urls.py<br>from django.contrib import admin<br>from django.urls import path<br><br>urlpatterns = [<br>    path(&#39;admin/&#39;, admin.site.urls),  # Admin route<br>]</pre><ul><li><strong>API URLs (</strong><strong>api_urls.py)</strong>:</li></ul><pre># api_urls.py<br>from django.urls import path, include<br><br>urlpatterns = [<br>    path(&#39;v1/&#39;, include(&#39;your_app.api_urls&#39;)),  # API routes<br>]</pre><p><strong>2. Main </strong><strong>urls.py Configuration</strong><br>In the primary urls.py file, conditionally include admin_urls or api_urls based on the subdomain in use. To do this, set a HOST variable that captures the incoming request’s subdomain.</p><pre># urls.py<br>from django.conf import settings<br>from django.urls import include, path<br><br>urlpatterns = []<br><br># Determine which URLs to serve based on HOST setting<br>if settings.HOST == &#39;admin&#39;:<br>    urlpatterns += [<br>        path(&#39;&#39;, include(&#39;project_name.admin_urls&#39;)),<br>    ]<br>elif settings.HOST == &#39;api&#39;:<br>    urlpatterns += [<br>        path(&#39;&#39;, include(&#39;project_name.api_urls&#39;)),<br>    ]</pre><h4>1.3 Dynamic HOST Assignment</h4><p>To capture and use the request’s subdomain, modify wsgi.py (or asgi.py for ASGI deployments). Here, we’ll set the HOST environment variable based on the incoming request’s subdomain, which we’ll use in urls.py for routing.</p><pre># wsgi.py (or asgi.py)<br>import os<br>from django.core.wsgi import get_wsgi_application<br><br>def application(environ, start_response):<br>    os.environ[&#39;DJANGO_SETTINGS_MODULE&#39;] = &#39;project_name.settings&#39;<br>    os.environ[&#39;HOST&#39;] = environ[&#39;HTTP_HOST&#39;].split(&#39;.&#39;)[0]  # Set host based on subdomain<br>    return get_wsgi_application()(environ, start_response)</pre><h3>Step 2: Configure Nginx for Subdomain Routing</h3><p>To properly route requests to the correct Django views, use Nginx to set up reverse proxies that will direct requests from admin.example.com to the Django admin interface and api.example.com to the API.</p><h4>2.1 Define Server Blocks for Each Subdomain</h4><ol><li><strong>Admin Subdomain Configuration</strong><br>Create a new Nginx configuration file for the Admin panel:</li></ol><pre># /etc/nginx/sites-available/admin.example.com<br>server {<br>    listen 80;<br>    server_name admin.example.com;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:8000;  # Local Django server<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><ol><li><strong>API Subdomain Configuration</strong><br>Create another configuration file for the API:</li></ol><pre># /etc/nginx/sites-available/api.example.com<br>server {<br>    listen 80;<br>    server_name api.example.com;<br><br>    location / {<br>        proxy_pass http://127.0.0.1:8000;  # Same Django app instance<br>        proxy_set_header Host $host;<br>        proxy_set_header X-Real-IP $remote_addr;<br>        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;<br>        proxy_set_header X-Forwarded-Proto $scheme;<br>    }<br>}</pre><h4>2.2 Enable Nginx Configuration</h4><p>To activate these configurations, create symbolic links from sites-available to sites-enabled:</p><pre>sudo ln -s /etc/nginx/sites-available/admin.example.com /etc/nginx/sites-enabled<br>sudo ln -s /etc/nginx/sites-available/api.example.com /etc/nginx/sites-enabled</pre><p>Afterward, test the Nginx configuration to ensure no syntax errors, then reload Nginx.</p><pre>sudo nginx -t<br>sudo systemctl reload nginx</pre><h3>Step 3: Verify the Setup</h3><p>Once Django and Nginx are configured, you can test the setup by accessing each subdomain:</p><ol><li>Visit admin.example.com/admin/ to check the Admin panel.</li><li>Test the API endpoints at api.example.com/v1/.</li></ol><p>If both subdomains resolve to the correct routes, your setup is complete! This configuration enhances security, scalability, and manageability for your Django project.</p><h3>Conclusion</h3><p>Setting up Django to serve Admin and API on separate subdomains is a smart approach for applications that demand modularity and security. This guide provided step-by-step instructions for configuring Django and Nginx to achieve a seamless, subdomain-based routing structure. Now you can maintain clean, separated routes for your Admin and API, each of which can scale and secure independently.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=18170fff851f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a Pure Function in Python?]]></title>
            <link>https://coder-sanju.medium.com/what-is-a-pure-function-in-python-9df085298696?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/9df085298696</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 04:53:42 GMT</pubDate>
            <atom:updated>2024-09-30T04:53:42.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Pure Functions" src="https://cdn-images-1.medium.com/max/287/1*K01yzRpBo_2E8fGCt3UjIw.png" /></figure><p>When we talk about <strong>pure functions</strong> in Python, we’re referring to a simple concept: a function that always gives the same output for the same input and doesn’t change anything outside of itself. These functions are core to functional programming and can make your code easier to understand, test, and maintain.</p><p>Let’s break down what makes a function “pure.”</p><h3>Characteristics of a Pure Function</h3><ol><li><strong>Same Input, Same Output</strong>: A pure function always produces the same result when given the same inputs. There’s no randomness or hidden factors involved.</li><li><strong>No Side Effects</strong>: A pure function doesn’t change anything outside of itself. It won’t modify a global variable, write to a file, or print to the console. Its only job is to take inputs, process them, and return a result.</li></ol><h3>Why Are Pure Functions Useful?</h3><blockquote>Pure functions might sound like a strict way to code, but they bring some real advantages:</blockquote><blockquote><strong>Easier to Test</strong>: Because they always return the same output for the same input, you can easily test them without worrying about the system&#39;s state.</blockquote><blockquote><strong>More Predictable</strong>: Since pure functions don’t change anything outside of themselves, they behave in a way that’s predictable and easier to reason about.</blockquote><blockquote><strong>Thread-Safe</strong>: Pure functions don’t rely on or modify shared variables, making them safe to use in multi-threaded applications.</blockquote><h3>Example of a Pure Function</h3><p>Let’s look at a simple example to see how a pure function works in Python. We’ll write a function that calculates the sum of the squares of two numbers:</p><pre>def sum_of_squares(a, b):<br>    return a**2 + b**2</pre><blockquote>Why is this a Pure Function?</blockquote><blockquote><strong>Same Input, Same Output</strong>: Every time you call sum_of_squares(3, 4), it will always return 25. The result doesn’t change based on anything outside the function.</blockquote><blockquote><strong>No Side Effects</strong>: It doesn’t change any variables outside the function. It only calculates a value and returns it.</blockquote><h4>Testing the Pure Function</h4><pre>print(sum_of_squares(3, 4))  # Output: 25<br>print(sum_of_squares(5, 6))  # Output: 61</pre><p>No matter how often you run this, you’ll always get the same result for the same input values.</p><blockquote>What is a Non-Pure Function?</blockquote><blockquote>Now let’s look at a function that doesn’t follow these rules. Here’s an example of a <strong>non-pure function</strong>:</blockquote><pre>result = 0<br>def add_to_result(a):<br>    global result<br>    result += a<br>    return result</pre><blockquote>Why is This Non-Pure?</blockquote><blockquote><strong>Global State</strong>: The function changes the value of the global variable result. So the output depends not only on the input but also on the state of result.</blockquote><blockquote><strong>Side Effects</strong>: By changing the global variable result, this function affects things outside of itself.</blockquote><h4>Testing the Non-Pure Function</h4><pre>print(add_to_result(5))  # Output: 5<br>print(add_to_result(10)) # Output: 15</pre><p>Notice how the second call add_to_result(10) is produced 15 because it’s using the updated value result from the previous call. This makes the function less predictable and harder to test.</p><h3>Advantages of Using Pure Functions</h3><blockquote><strong>Easier to Understand</strong>: Since pure functions don’t rely on anything outside their scope, they are much easier to read and understand. You don’t have to worry about how they might be affecting other parts of the code.</blockquote><blockquote><strong>Better Testing</strong>: Pure functions can be tested in isolation without needing to set up a lot of context or worry about the state of the program.</blockquote><blockquote><strong>Reusable</strong>: You can reuse pure functions in different parts of your code because you know they don’t depend on or affect any external data.</blockquote><blockquote><strong>Safer in Multi-Threading</strong>: Since pure functions don’t modify shared variables, they’re safe to run in parallel, which is crucial in multi-threaded or distributed systems.</blockquote><h3>Conclusion</h3><blockquote>Pure functions are a great tool for writing clean, predictable, and easy-to-test code in Python. While they aren’t always necessary, using them where you can brings a lot of benefits to your programming. By ensuring your functions are pure, you make your code more readable, maintainable, and less prone to unexpected behavior.</blockquote><blockquote>So next time you’re writing a function, ask yourself: “Can I make this a pure function?” If you can, you’ll find your code becomes more reliable and easier to work with!</blockquote><h3>Connect with Me</h3><ul><li><a href="https://x.com/_mr_tdb">X</a></li><li><a href="https://www.linkedin.com/in/coder-sanju/">LinkedIn</a></li><li><a href="https://github.com/coder-SaNjU/">GitHub</a></li><li><a href="https://www.instagram.com/_mr_tdb/">Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9df085298696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is deep_flatten in Python..??]]></title>
            <link>https://coder-sanju.medium.com/what-is-deep-flatten-in-python-242665618426?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/242665618426</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Sat, 28 Sep 2024 09:23:28 GMT</pubDate>
            <atom:updated>2024-09-28T09:27:40.925Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Understanding </strong><strong>deep_flatten in Python: Flattening Nested Iterables</strong></p><p>When working with Python, you often encounter data structures like lists, tuples, and sets. Sometimes, these structures can be deeply nested, making it cumbersome to extract individual elements. Flattening a nested structure refers to transforming it into a single-level sequence where all the inner components are extracted and placed in one iterable, such as a list or a tuple.</p><p>Python provides various ways to flatten such structures, but handling deeply nested ones can take time and effort. This is where the deep_flatten function, often found in third-party libraries, comes into play.</p><h3>What is deep_flatten?</h3><p>deep_flatten is a function that recursively flattens an iterable, regardless of how deeply nested it is. <strong>Deep flattening</strong> involves flattening multiple levels of nested tables (like lists of lists, lists of tuples, etc.) into a one-dimensional sequence.</p><h3>Example of Deep Flattening in python</h3><pre>nested_list = [1, [2, [3, 4], 5], 6]<br>flattened = deep_flatten(nested_list)<br>print(list(flattened))</pre><p><strong>Output:</strong></p><pre>[1, 2, 3, 4, 5, 6]</pre><p>In this example, deep_flatten transforms the nested list into a single flat list containing all the individual elements.</p><h3>Implementing deep_flatten in Python</h3><p>While Python doesn’t have a built-in deep_flatten function, you can implement it using recursive techniques.</p><p>Here’s a simple implementation:</p><pre>def deep_flatten(iterable):<br>    for item in iterable:<br>        if isinstance(item, (list, tuple, set)):<br>            yield from deep_flatten(item)<br>        else:<br>            yield item</pre><h3>How It Works</h3><ul><li><strong>Recursion</strong>: If the current item is iterable (like a list, tuple, or set), the function recursively calls itself to process the sub-elements.</li><li><strong>yield from</strong>: This statement helps in yielding elements from the inner iterable (thresult of the recursive call).</li><li><strong>Base Case</strong>: If the item is not an iterable, it is yielded directly.</li></ul><h3>Example Usage</h3><pre>nested_structure = [1, [2, [3, [4, 5]], 6], 7, [8, 9]]<br>flattened = deep_flatten(nested_structure)<br>print(list(flattened))</pre><p><strong>Output:</strong></p><pre>[1, 2, 3, 4, 5, 6, 7, 8, 9]</pre><h3>Why Use deep_flatten?</h3><ol><li><strong>Simplifies Data Handling</strong>: You no longer need to manually loop through multiple levels of nested structures.</li><li><strong>Flexible</strong>: It works with various iterable types like lists, tuples, and sets.</li><li><strong>Readability</strong>: Your code becomes cleaner and more maintainable, especially when dealing with complex nested data.</li></ol><h3>Using deep_flatten External Libraries</h3><p>Some Python libraries, such as <strong>more_itertools</strong>, offer built-in solutions for deep flattening.</p><h3>Example with more_itertools</h3><p>First, install the library:</p><pre>pip install more-itertools</pre><p>Now, you can use deep_flatten directly:</p><pre>from more_itertools import deep_flatten</pre><pre>nested_list = [1, [2, [3, 4], 5], 6]<br>flattened = list(deep_flatten(nested_list))<br>print(flattened)p</pre><p><strong>Output:</strong></p><pre>[1, 2, 3, 4, 5, 6]</pre><h3>Key Considerations</h3><ul><li><strong>Non-iterable types</strong>: If your nested structure contains non-iterable types like integers, strings, or floats, ensure your deep_flatten function handles them correctly by yielding the values directly instead of attempting to iterate over them.</li><li><strong>Performance</strong>: Deep flattening can become computationally expensive for very large and complex structures. If performance is a concern, test the function on smaller datasets before using it on a large scale.</li></ul><h3>Conclusion</h3><p>Flattening deeply nested structures is a common problem in Python programming. While there’s no built-in function to handle deep flattening, writing your own deep_flatten function is straightforward, and there are external libraries like more_itertools that can help.</p><p>Whether you choose to implement it yourself or leverage external libraries, deep_flatten is a powerful tool for dealing with complex data structures in Python.</p><h3>Connect with Me</h3><ul><li><a href="https://x.com/_mr_tdb">X</a></li><li><a href="https://www.linkedin.com/in/coder-sanju/">LinkedIn</a></li><li><a href="https://github.com/coder-SaNjU/">GitHub</a></li><li><a href="https://www.instagram.com/_mr_tdb/">Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242665618426" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Secure Your REST API in Django]]></title>
            <link>https://coder-sanju.medium.com/how-to-secure-your-rest-api-in-django-cfda63d19381?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfda63d19381</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[django]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Sat, 20 May 2023 18:05:34 GMT</pubDate>
            <atom:updated>2023-05-20T18:20:13.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*-0mkVcYYQA_fsEAv0-pwbQ.png" /></figure><h3>Introduction</h3><p>REST APIs are widely used for building web and mobile applications. However, securing a REST API can be a challenging task. In this blog post, we will discuss some best practices and techniques for securing your REST API in Django.</p><h3>Use HTTPS</h3><p>The first and foremost step to secure your REST API is to use HTTPS instead of HTTP. HTTPS encrypts the communication between the client and the server, making it difficult for attackers to intercept and read the data. To use HTTPS in Django, you need to install and configure an SSL certificate on your server. Once you have installed the SSL certificate, you can enable HTTPS in your Django settings file:</p><pre># settings.py<br>SECURE_SSL_REDIRECT = True<br>SESSION_COOKIE_SECURE = True<br>CSRF_COOKIE_SECURE = True</pre><h3>Use Tokens</h3><p>Using tokens to authenticate the user is more secure than using passwords. Tokens are short-lived and can be revoked anytime. Django provides a built-in token authentication system that you can use to secure your REST API. To use token authentication, you need to install the djangorestframework-simplejwt package:</p><pre>pip install djangorestframework-simplejwt</pre><p>Once you have installed the package, you can add the following settings to your Django settings file:</p><pre># settings.py<br>INSTALLED_APPS = [<br>                    ...<br>                 &#39;rest_framework_simplejwt&#39;,<br>                ]<br><br>REST_FRAMEWORK = {<br>            &#39;DEFAULT_AUTHENTICATION_CLASSES&#39;: [<br>              &#39;rest_framework_simplejwt.authentication.JWTAuthentication&#39;,<br>              ],<br>        }</pre><p>Now, you can generate a token for a user by sending a POST request to the token endpoint:</p><pre># views.py<br>from rest_framework_simplejwt.views import TokenObtainPairView<br>class CustomTokenObtainPairView(TokenObtainPairView):<br>  serializer_class = CustomTokenObtainPairSerializer<br><br><br># serializers.py<br>from rest_framework_simplejwt.serializers import TokenObtainPairSerializer<br><br>class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):<br>    @classmethod<br>    def get_token(cls, user):<br>      token = super().get_token(user)<br>      # Add custom claims<br>      token[&#39;username&#39;] = user.username <br>      token[&#39;email&#39;] = user.email<br>    return token</pre><h3>Use OAuth2</h3><p>OAuth2 is an industry-standard protocol for authorization that provides a secure way to access user data. Django provides a built-in OAuth2 authentication system that you can use to secure your REST API. To use OAuth2 authentication, you need to install the django-oauth-toolkit package:</p><pre>pip install django-oauth-toolkit</pre><p>Once you have installed the package, you can add the following settings to your Django settings file:</p><pre># settings.py<br>INSTALLED_APPS = [<br>    .........<br>    &#39;oauth2_provider&#39;,]<br>OAUTH2_PROVIDER = {<br>                  &#39;ACCESS_TOKEN_EXPIRE_SECONDS&#39;: 3600,<br>                  &#39;REFRESH_TOKEN_EXPIRE_SECONDS&#39;: 86400,<br>                  }</pre><p>Now, you can generate an access token for a user by sending a POST request to the token endpoint:</p><pre># views.py<br>from oauth2_provider.views.generic import TokenView<br>class CustomTokenView(TokenView):<br>    def post(self, request, *args, **kwargs):<br>        response = super().post(request, *args, **kwargs)<br>         # Add custom claims to the token<br>        response.data[&#39;username&#39;] = request.user.username<br>        response.data[&#39;email&#39;] = request.user.email<br>    return response</pre><h3>Use CORS</h3><p>CORS (Cross-Origin Resource Sharing) is a security feature that restricts access to your REST API. CORS allows you to specify which domains can access your API. To use CORS in Django, you need to install the django-cors-headers package:</p><pre>pip install django-cors-headers</pre><p>Once you have installed the package, you can add the following settings to your Django settings file:</p><pre># settings.py<br>INSTALLED_APPS = [<br>                    ...<br>                 &#39;corsheaders&#39;,<br>                ]<br><br><br>MIDDLEWARE = [    ...    <br>              &#39;corsheaders.middleware.CorsMiddleware&#39;,<br>              &#39;django.middleware.common.CommonMiddleware&#39;,<br>              ]<br><br><br>CORS_ORIGIN_WHITELIST = [<br>        &#39;http://localhost:3000&#39;,<br>        &#39;https://example.com&#39;,<br>        ]</pre><h3>Use Rate Limiting</h3><p>Rate limiting is a technique that prevents abuse of your REST API. Rate limiting allows you to limit the number of requests a user can make in a given time period. Django provides a built-in rate-limiting system that you can use to secure your REST API. To use rate limiting, you need to install the django-ratelimit package:</p><pre>pip install django-ratelimit</pre><p>Once you have installed the package, you can add the following settings to your Django settings file:</p><pre># settings.py<br>INSTALLED_APPS = [<br>               ... <br>             &#39;ratelimit&#39;,<br>            ]<br>MIDDLEWARE = [  <br>                  ...    <br>                &#39;ratelimit.middleware.RatelimitMiddleware&#39;,<br>            ]<br><br># Rate limit settings<br><br>RATELIMIT_GLOBAL = &#39;500/hour&#39;<br>RATELIMIT_KEY_PREFIX = &#39;user&#39;</pre><h3>Conclusion</h3><p>In this blog post, we discussed some best practices and techniques for securing your REST API in Django. By following these best practices and techniques, you can make your REST API more secure and prevent unauthorized access to your data.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfda63d19381" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[what is the difference between decorator and middleware in Django.?]]></title>
            <link>https://coder-sanju.medium.com/what-is-the-difference-between-decorator-and-middleware-in-django-f172d19bfd89?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f172d19bfd89</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Sun, 14 May 2023 11:50:42 GMT</pubDate>
            <atom:updated>2023-05-14T11:50:42.807Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ohX5eBSdzdLSUDfKLkXhQ.jpeg" /></figure><p>In this article, We will discuss the difference between decorator and middleware in Django.</p><p>Both decorators and middlewares are used in Django to add additional functionality to the views or the application. However, they differ in the way they are implemented and the scope of their functionality.</p><p>A decorator is a function that takes another function as input and extends the behavior of the latter function without explicitly modifying it. In Django, decorators are often used to add authentication or permission checks to views.</p><p>Here&#39;s an example of a decorator in Django:</p><pre>def rate_limited(func):<br>    def wrapper(*args, **kwargs):<br>        ip_address = request.remote_addr<br>        key = f&quot;ratelimit:{request.path}&quot;<br>        count = cache.get(key)<br>        if count is None:<br>            cache.set(key, 1, ex=RATE_PERIOD)<br>        elif int(count) &gt;= RATE_LIMIT:<br>            return jsonify({&quot;message&quot;: &quot;Rate limit exceeded. Try again in 1 minute.&quot;}), 429<br>        else:<br>            # increment the request count and set the new TTL<br>            cache.incr(key)<br>            cache.expire(key, RATE_PERIOD)<br>        # call the decorated function<br>        return func(*args, **kwargs)<br>    wrapper.__name__=func.__name__<br>    return wrapper</pre><blockquote>in this example, we implement a rate-limited decorator, A rate-limited decorator is a Python function that wraps around another function, adding functionality to limit the rate at which the wrapped function can be called. The decorator checks whether the wrapped function has been called within a specified time interval and limits the number of times it can be called within that interval.</blockquote><p>A middleware, on the other hand, is a component that sits between the client and the application and intercepts the request and response objects. In Django, middleware is often used to modify the behavior of the request or response, such as adding headers, modifying cookies, or logging requests.</p><p>Here’s an example of middleware in Django</p><pre>from django.core.cache import cache<br>from django.http import JsonResponse<br><br>class RateLimitMiddleware:<br>    def __init__(self, get_response):<br>        self.get_response = get_response<br><br>    def __call__(self, request):<br>        # check if the request is rate-limited<br>        if self.is_rate_limited(request):<br>            return JsonResponse({&quot;message&quot;: &quot;Rate limit exceeded. Try again in 1 minute.&quot;}, status=429)<br>        <br>        # call the view function<br>        response = self.get_response(request)<br><br>        return response<br><br>    def is_rate_limited(self, request):<br>        ip_address = request.META.get(&#39;REMOTE_ADDR&#39;)<br>        key = f&quot;ratelimit:{request.path}:{ip_address}&quot;<br>        count = cache.get(key)<br>        if count is None:<br>            cache.set(key, 1, timeout=RATE_PERIOD)<br>        elif int(count) &gt;= RATE_LIMIT:<br>            return True<br>        else:<br>            # increment the request count and set the new TTL<br>            cache.incr(key)<br>            cache.expire(key, RATE_PERIOD)<br>        return False</pre><blockquote>In this example, the RateLimitedMiddleware class takes the web framework app and max_per_second as parameters. The middleware checks whether the endpoint has been called within the minimum interval time and limits the number of times it can be called. If the endpoint has been called too many times, the middleware returns a &quot;429 Too Many Requests&quot; response. If the endpoint can be called, the middleware calls the web framework app. The middleware is called before each request to the endpoint, ensuring that the rate limit is enforced for each request.</blockquote><h3><strong>Basic Difference between decorator and middleware.</strong></h3><blockquote>Decorators in Django are functions that are used to modify the behavior of a view function. They are defined using the @decorator_name syntax and are placed before the view function in the code. Decorators are used to add extra functionality to views such as authentication, caching, or permission checking. A decorator can be applied to a specific view or to a group of views. Decorators work by wrapping the original view function with another function that provides additional functionality.</blockquote><blockquote>Middleware in Django is a series of hooks that are executed during the request-response processing cycle. Middleware is a set of components that sits between the web server and the view function. Middleware can modify the request or response object, perform logging, or perform other operations before and after the view function is executed. Middleware is applied to all views in the application and can be used to add functionality such as authentication, caching, or request/response processing.</blockquote><blockquote>In summary, decorators modify the behavior of a single view or a group of views, while middleware modifies the request or response objects for all views in the application.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f172d19bfd89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a match statement in GDSCRIPT and how we can use it?]]></title>
            <link>https://coder-sanju.medium.com/what-is-a-match-statement-in-gdscript-and-how-we-can-use-it-aa4f7307c3?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa4f7307c3</guid>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 05:58:52 GMT</pubDate>
            <atom:updated>2023-03-25T05:58:52.723Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, We will discuss is a match statement in GDSCRIPT and how we can use it. so let’s start.</p><p>A match statement, just like a switch case statement in many other programming languages but offers some additional features, is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution in search and map.</p><p>Basically, you use a variable to ‘<strong><em>match</em></strong>’ a pattern and execute the code inside the match statement</p><p>Basic syntax :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2e18e5ec3fa7f2f4dd5349a0539bd2/href">https://medium.com/media/eb2e18e5ec3fa7f2f4dd5349a0539bd2/href</a></iframe><h3><strong>Types of match patterns</strong></h3><p>1.Constant Pattern<br> 2.Variable Pattern<br> 3.Wildcard Pattern<br> 4.Binding Pattern<br> 5.Array Pattern<br> 6.Dictionary Pattern<br> 7.Multiple Pattern</p><h3><strong>1.Constant Pattern</strong></h3><p>A constant pattern is when you use a primitive/literal data type.<br>primitive/literal data types are integers, floats, booleans, strings, etc.</p><p>Example :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb2e18e5ec3fa7f2f4dd5349a0539bd2/href">https://medium.com/media/eb2e18e5ec3fa7f2f4dd5349a0539bd2/href</a></iframe><h3><strong>2. Variable Pattern :</strong></h3><p>With Gdscript we can use variables to match a pattern</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00833128b3b5f93ba0aa18482a97db75/href">https://medium.com/media/00833128b3b5f93ba0aa18482a97db75/href</a></iframe><h3>3. Wildcard Pattern :</h3><p>wildcard pattern matches everything. It’s written as a <strong>single underscore</strong><strong>_.</strong></p><p>It can also be thought of as a “default” block statement, meaning it will always run when all other match patterns fail</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d261f50262d845a8249d37eaef88085/href">https://medium.com/media/4d261f50262d845a8249d37eaef88085/href</a></iframe><h3><strong>4.Binding pattern.</strong></h3><p>A binding pattern catches everything just like the wildcard pattern. The difference is the binding pattern assigns the value acquired into a variable that can be used inside the binding pattern match block<br>It’s especially useful in array and dictionary patterns</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa4f7307c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between a module and a package in Python . ?]]></title>
            <link>https://coder-sanju.medium.com/what-is-the-difference-between-a-module-and-a-package-in-python-d788dfc11e8?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/d788dfc11e8</guid>
            <category><![CDATA[writing]]></category>
            <category><![CDATA[blog]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Sat, 25 Mar 2023 05:36:52 GMT</pubDate>
            <atom:updated>2023-03-25T05:36:52.549Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is the difference between a module and a package in Python.?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8eiygku2pw2kca02ODeXw.jpeg" /></figure><p>In Python, a module is a single file that contains Python definitions and statements. It typically consists of functions, classes, and variables that can be imported and used in other Python codes. A module can be considered a reusable library that provides a set of functionality to a program.</p><p>On the other hand, a package is a collection of related Python modules that are organized in a directory hierarchy. A package is a way of structuring Python modules so that they can be easily imported and used by other modules or programs. A package can contain sub-packages and modules, which can also contain sub-packages and modules, forming a hierarchical structure.</p><p>To create a package, you need to create a directory that contains a __init__.py file. This file is used to mark the directory as a Python package, and it can contain code that will be executed when the package is imported.</p><p><strong><em>The main difference between a module and a package is that a module is a single file, while a package is a directory that can contain multiple Python modules and sub-packages. A module can be imported directly using its filename, while a package must be imported using its package name, followed by the module or sub-package name separated by dots.</em></strong></p><p><strong>F</strong>or example, suppose you have a package called mypackage that contains two modules called module1 and module2. You can import these modules using the following statements:</p><pre>import mypackage.module1<br>import mypackage.module2</pre><p>Alternatively, you can import these modules using the <strong>from</strong> keyword, like this:</p><pre>from mypackage import module1, module2</pre><p>In summary, a module is a single file that contains Python code, while a package is a collection of related modules and sub-packages that are organized in a directory hierarch</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d788dfc11e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is the difference between a generator and list in Python]]></title>
            <link>https://coder-sanju.medium.com/what-is-the-difference-between-a-generator-and-a-list-in-python-215bbeb4a2e6?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/215bbeb4a2e6</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Fri, 24 Mar 2023 03:50:38 GMT</pubDate>
            <atom:updated>2023-03-24T04:34:02.171Z</atom:updated>
            <content:encoded><![CDATA[<p>In Python, a list is a built-in data structure that holds a collection of items in a specific order. It allows for indexing, slicing, and iterating over the items in the list. A generator, on the other hand, is a function that produces a sequence of values using the <strong>yield</strong> keyword, which suspends the function&#39;s execution and returns the value to the caller.</p><p><strong>The main difference between a generator and a list is how they store and generate their values. A list stores all its values in memory at once, whereas a generator produces its values on the fly, as they are requested. This means that a generator can be more memory-efficient than a list, especially when working with large datasets.</strong></p><blockquote>Here are some other key differences between a generator and a list:</blockquote><ul><li><strong><em>Lists are mutable, meaning you can modify them after creation, whereas generators are immutable and their values cannot be modified once they are generated.</em></strong></li><li><strong><em>Lists can be indexed and sliced, whereas generators cannot be directly indexed or sliced. Instead, you can iterate over them using a </em></strong><strong><em>for loop or convert them to a list using the </em></strong><strong><em>list() function.</em></strong></li><li><strong><em>Lists can be iterated over multiple times, whereas generators can only be iterated over once. Once a generator has been exhausted, you cannot iterate over it again.</em></strong></li></ul><p>In summary, generators are a more memory-efficient way to generate sequences of values in Python, especially when dealing with large datasets. However, they are not as flexible as lists and cannot be directly indexed or sliced.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=215bbeb4a2e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is different between a problem class diagram and a solution class diagram]]></title>
            <link>https://coder-sanju.medium.com/what-is-different-between-a-problem-class-diagram-and-a-solution-class-diagram-39b07965c2a4?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/39b07965c2a4</guid>
            <category><![CDATA[learning-to-code]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[archtitecture]]></category>
            <category><![CDATA[oops-concepts]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 16:59:07 GMT</pubDate>
            <atom:updated>2023-02-03T16:59:07.517Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem class diagram and solution class diagram are not standard terms in software modeling, but if they are being used, they likely refer to different types of diagrams.</p><p>A problem class diagram is a type of diagram that represents the problem domain in terms of classes and their relationships. The purpose of a problem class diagram is to understand the problem space, identify the classes and relationships involved, and form a basis for designing a solution.</p><p>A solution class diagram, on the other hand, is a type of diagram that represents the solution domain in terms of classes and their relationships. It is used to visualize the static structure of a system, including the classes and their attributes, and the relationships between them. The solution class diagram is based on the problem class diagram and represents the design of the system.</p><p>In other words, a problem class diagram focuses on understanding the problem that the system is trying to solve, while a solution class diagram focuses on the implementation of the solution to that problem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39b07965c2a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is a hashable data type?]]></title>
            <link>https://coder-sanju.medium.com/what-is-a-hashable-data-type-177e286be92?source=rss-24f48e8e4e17------2</link>
            <guid isPermaLink="false">https://medium.com/p/177e286be92</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[sanju saini]]></dc:creator>
            <pubDate>Fri, 03 Feb 2023 16:51:20 GMT</pubDate>
            <atom:updated>2023-02-03T16:51:20.133Z</atom:updated>
            <content:encoded><![CDATA[<p>In software engineering, a hashable data type is a data type that can be used as an input to a hash function. A hash function takes an input, known as a hashable object, and returns a fixed-size string of characters, called the hash value.</p><p>The hash value is typically used as a unique identifier for the original object and can be used for efficient data structure operations, such as searching and sorting. For a data type to be hashable, it must have a consistent hash value for a given object throughout the object&#39;s lifetime, and it must be immutable (cannot change after it has been created).</p><p>Examples of hashable data types in Python include integers, strings, and tuples containing only hashable elements.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=177e286be92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>