<?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 Chetan Choudhary on Medium]]></title>
        <description><![CDATA[Stories by Chetan Choudhary on Medium]]></description>
        <link>https://medium.com/@choudharycodes?source=rss-c7d4cad27ae1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*28ASShs1T9WlCE_A</url>
            <title>Stories by Chetan Choudhary on Medium</title>
            <link>https://medium.com/@choudharycodes?source=rss-c7d4cad27ae1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 03:13:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@choudharycodes/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[Title: Securing Your Web Applications with JWT Authentication and Refresh Token Rotation]]></title>
            <link>https://choudharycodes.medium.com/title-securing-your-web-applications-with-jwt-authentication-and-refresh-token-rotation-63a9aa1a4b12?source=rss-c7d4cad27ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/63a9aa1a4b12</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Chetan Choudhary]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 13:31:46 GMT</pubDate>
            <atom:updated>2024-09-18T13:32:52.619Z</atom:updated>
            <content:encoded><![CDATA[<h3>Securing Your Web Applications with JWT Authentication and Refresh Token Rotation</h3><p>In today’s digital landscape, user authentication and secure access management are critical components of any web application. As developers, we strive to strike the perfect balance between security and user experience, ensuring that our users can access services seamlessly while minimizing the risk of unauthorized access. One of the most popular methods for managing authentication in modern web applications is <strong>JWT (JSON Web Token)</strong>. JWTs allow developers to handle authentication in a <strong>stateless</strong> way, but with that convenience comes the need for enhanced security measures. In particular, <strong>refresh token rotation</strong> plays a crucial role in maintaining a secure environment by mitigating risks associated with token theft and replay attacks. This article will explore <strong>JWT authentication</strong> in detail, the risks associated with token-based authentication, and how <strong>refresh token rotation</strong> can bolster your app’s security. Finally, we’ll show you how to implement this strategy in <strong>FastAPI</strong>, one of the fastest-growing Python frameworks.</p><h4>What is JWT Authentication?</h4><p><strong>JSON Web Tokens (JWTs)</strong> are a compact, URL-safe means of representing claims between two parties — most commonly the client (browser or mobile app) and the server (API). JWTs are popular for user authentication because they enable <strong>stateless</strong> communication, where the server doesn’t need to maintain session data, which simplifies scalability.</p><p>A JWT consists of three parts:</p><ol><li><strong>Header</strong>: Contains the algorithm used to sign the token and the type (JWT).</li><li><strong>Payload</strong>: Contains the actual data or claims (e.g., user ID, expiration time).</li><li><strong>Signature</strong>: Ensures the token hasn’t been altered using the server’s secret key.</li></ol><p>When a user logs in, the server generates a JWT and sends it to the client. The client then includes this token in subsequent requests, allowing the server to verify the user’s identity without needing to track sessions.</p><h4>The Lifespan of Tokens: The Trade-off</h4><p>To balance security and usability, we often divide tokens into two types:</p><ol><li><strong>Access Tokens</strong>: Short-lived tokens (usually 15–30 minutes) that allow users to access protected resources.</li><li><strong>Refresh Tokens</strong>: Long-lived tokens (days or weeks) that allow the client to obtain new access tokens without forcing the user to log in again.</li></ol><p>While short-lived <strong>access tokens</strong> provide better security (since they expire quickly), they can become a usability problem if the user is forced to log in repeatedly. On the other hand, <strong>refresh tokens</strong> help solve this issue by allowing users to stay logged in for longer without sacrificing security. — -</p><h4>The Problem with Refresh Tokens: The Security Risk</h4><p>Though refresh tokens help solve the usability issue, they come with a security risk: <strong>What happens if a refresh token is stolen?</strong></p><p>If an attacker steals a refresh token, they could continually request new access tokens, effectively keeping the attacker “logged in” even if the original access token expires. This is where <strong>refresh token rotation</strong> comes into play. — -</p><h4>What is Refresh Token Rotation?</h4><p><strong>Refresh token rotation</strong> is a security strategy designed to mitigate the impact of stolen refresh tokens. The idea is simple: every time a refresh token is used to obtain a new access token, the server also issues a <strong>new refresh token</strong>. The old refresh token is invalidated and can no longer be used.</p><p>Here’s how it works:</p><ol><li><strong>Initial Login</strong>: The user logs in and receives both an access token (short-lived) and a refresh token (long-lived).</li><li><strong>Access Token Expiration</strong>: When the access token expires, the client sends the refresh token to the server to get a new access token.</li><li><strong>Token Rotation</strong>: The server verifies the refresh token, issues a new access token, and <strong>rotates</strong> the refresh token — issuing a new one and invalidating the old one.</li><li><strong>Increased Security</strong>: If a refresh token is stolen, it can only be used once. After it’s used, the token is no longer valid, minimizing the risk of replay attacks. This approach ensures that even if an attacker gets hold of a refresh token, they can only use it one time before it becomes useless.</li></ol><h4>Benefits of Refresh Token Rotation</h4><ol><li><strong>Mitigates Replay Attacks</strong>: Once a refresh token is used, it’s no longer valid, making it difficult for attackers to reuse a stolen token.</li><li><strong>Improves User Experience</strong>: Users don’t need to log in frequently since the refresh token enables them to obtain new access tokens automatically.</li><li><strong>Reduces Long-Term Vulnerabilities</strong>: Even if an attacker gets hold of a refresh token, the damage is limited to a single session.</li></ol><h3>General Strategies for Securing JWT-Based Systems</h3><p>When implementing JWT authentication, it’s important to adopt some best practices to minimize security risks:</p><h4>1. Short Access Token Lifetimes</h4><p>The shorter the access token lifetime, the smaller the window for potential misuse. However, make sure to balance this with user experience — too short a lifespan may force users to refresh tokens too often.</p><h4>2. Use Secure Algorithms</h4><p>Always use secure algorithms (e.g., HS256 or RS256) for signing JWTs. This ensures that tokens cannot be tampered with without detection.</p><h4>3. Secure Refresh Token Storage</h4><p>Store refresh tokens securely on the client side. For web applications, use <strong>HTTP-only cookies</strong>. Avoid localStorage or sessionStorage, which are vulnerable to XSS attacks.</p><h4>4. Implement Token Rotation</h4><p>Rotate refresh tokens every time they are used. This ensures that even if a refresh token is stolen, it cannot be reused after the first use.</p><h4>5. Revoke Tokens on Logout</h4><p>Always have a mechanism to revoke refresh tokens on logout or when suspicious activity is detected. This can be done by tracking tokens in a database or using a blacklist.</p><h4>6. Multi-Factor Authentication (MFA)</h4><p>Enhance security by implementing multi-factor authentication (MFA), especially for sensitive actions or after token expiration.</p><h4>7. Use Secure Cookies</h4><p>When using cookies to store tokens, make them <strong>HTTP-only</strong> and <strong>SameSite=Strict</strong> to prevent XSS and CSRF attacks.</p><h3>Example: JWT Authentication with Refresh Token Rotation in FastAPI</h3><p>Let’s see how all this theory translates into a real-world implementation using <strong>FastAPI</strong>.</p><h4>Step 1: Install Dependencies</h4><pre>pip install fastapi[all] pyjwt passlib bcrypt</pre><h4>Step 2: Create Utility Functions for Tokens</h4><pre>import jwt<br>from datetime import datetime, timedelta<br>SECRET_KEY = &quot;your_secret_key&quot;<br>ALGORITHM = &quot;HS256&quot;<br><br>def create_access_token(data: dict):<br>  expire = datetime.utcnow() + timedelta(minutes=15)<br>  data.update({&quot;exp&quot;: expire})<br>  return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)<br><br>def create_refresh_token(data: dict):<br>  expire = datetime.utcnow() + timedelta(days=7)<br>  data.update({&quot;exp&quot;: expire})<br>  return jwt.encode(data, SECRET_KEY, algorithm=ALGORITHM)<br><br>def decode_token(token: str):<br>  try:<br>   return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])<br>  except jwt.ExpiredSignatureError:<br>   return None<br>  except jwt.InvalidTokenError:<br>   return None</pre><h4>Step 3: Implement the Token Rotation Endpoint</h4><pre>from fastapi import FastAPI, HTTPException, status<br><br>app = FastAPI()<br>used_refresh_tokens = set()<br><br>@app.post(&quot;/token/refresh&quot;)<br>async def refresh_token(refresh_token: str):<br>  payload = decode_token(refresh_token)<br>  if not payload or refresh_token in used_refresh_tokens:<br>   raise HTTPException(<br>     status_code=status.HTTP_401_UNAUTHORIZED,<br>     detail=&quot;Invalid or expired refresh token&quot;,<br>     )<br>   username = payload.get(&quot;sub&quot;)<br>   used_refresh_tokens.add(refresh_token) # Mark the token as used<br>   new_access_token = create_access_token({&quot;sub&quot;: username})<br>   new_refresh_token = create_refresh_token({&quot;sub&quot;: username})<br>   return {<br>     &quot;access_token&quot;: new_access_token,<br>     &quot;refresh_token&quot;: new_refresh_token,<br>     }</pre><h4>Step 4: Protect Routes with JWT Authentication</h4><pre>from fastapi import Depends<br><br>async def get_current_user(token: str = Depends(oauth2_scheme)):<br> payload = decode_token(token)<br> if not payload:<br>   raise HTTPException(<br>   status_code=status.HTTP_401_UNAUTHORIZED,<br>   detail=&quot;Invalid or expired token&quot;,<br>   )<br> return payload[&quot;sub&quot;]<br><br>@app.get(&quot;/users/me&quot;)<br>async def read_users_me(current_user: str = Depends(get_current_user)):<br>  return {&quot;username&quot;: current_user}</pre><h3>Conclusion: Balancing Security and User Experience</h3><p>JWT authentication is powerful, but like any security mechanism, it requires careful consideration to implement effectively. Refresh token rotation is a crucial tool in the fight against token theft and replay attacks, allowing you to offer a seamless user experience while maintaining a high level of security. By applying the best practices we’ve discussed — such as rotating refresh tokens, shortening access token lifetimes, and using secure storage — you can build an authentication system that is robust, scalable, and secure. FastAPI provides an excellent platform for implementing these techniques, but these principles apply to any modern web framework. Whether you’re using Django, Flask, or Express, the strategies outlined here will help you build secure, user-friendly authentication systems. Happy coding, and stay secure!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63a9aa1a4b12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FastAPI Unveiled: Mastering the Magic of Lightning-Fast Python APIs]]></title>
            <link>https://choudharycodes.medium.com/fastapi-unveiled-mastering-the-magic-of-lightning-fast-python-apis-02d1b4cc22f7?source=rss-c7d4cad27ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/02d1b4cc22f7</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[asyncio]]></category>
            <dc:creator><![CDATA[Chetan Choudhary]]></dc:creator>
            <pubDate>Wed, 18 Sep 2024 11:05:59 GMT</pubDate>
            <atom:updated>2024-09-18T11:05:59.087Z</atom:updated>
            <content:encoded><![CDATA[<p>FastAPI is a modern, high-performance web framework for building APIs with Python. It’s designed to be easy to use, fast to code, and capable of handling production workloads. In this beginner-friendly guide, we’ll explore how FastAPI works behind the scenes, particularly in handling different types of requests.</p><h3>What is FastAPI?</h3><p>Before diving into the technicalities, let’s understand what FastAPI is and why it’s popular:</p><ul><li><strong>Fast to code</strong>: FastAPI allows you to write APIs quickly with minimal code.</li><li><strong>Based on standards</strong>: It uses Python type hints and modern Python features (3.6+).</li><li><strong>Automatic docs</strong>: FastAPI automatically generates interactive API documentation.</li><li><strong>High performance</strong>: It’s one of the fastest Python frameworks available.</li></ul><h3>The Basics: Synchronous vs. Asynchronous Operations</h3><p>To understand FastAPI’s magic, we need to grasp two key concepts:</p><ol><li><strong>Synchronous (Blocking) Operations</strong>:</li></ol><ul><li>Think of these as tasks that must finish before anything else can happen.</li><li>Example: Waiting for a kettle to boil — you can’t use the hot water until it’s done.</li><li>In Python: time.sleep(5) pauses everything for 5 seconds.</li></ul><p><strong>2. Asynchronous (Non-Blocking) Operations</strong>:</p><ul><li>These are tasks that can be paused, allowing other tasks to run in the meantime.</li><li>Example: Starting the dishwasher and then doing other chores while it runs.</li><li>In Python: await asyncio.sleep(5) allows other code to run during those 5 seconds.</li></ul><h3>How FastAPI Handles Requests</h3><p>Let’s look at three common scenarios in FastAPI:</p><h4>Scenario 1: The Patient Queue (Synchronous in Async Function)</h4><pre>async def patient_checkup():<br>    print(&quot;Patient enters&quot;)<br>    time.sleep(5)  # Representing a 5-minute checkup<br>    print(&quot;Patient leaves&quot;)</pre><p>In this scenario:</p><ul><li>Even though we use async def, the time.sleep() is blocking.</li><li>FastAPI processes these requests one at a time, like a patient queue where each checkup must finish before the next starts.</li></ul><h4>Scenario 2: The Efficient Multitasker (Asynchronous)</h4><pre>async def efficient_checkup():<br>    print(&quot;Patient enters&quot;)<br>    await asyncio.sleep(5)  # Representing a 5-minute checkup<br>    print(&quot;Patient leaves&quot;)</pre><p>Here:</p><ul><li>The await asyncio.sleep(5) is non-blocking.</li><li>FastAPI can handle multiple requests concurrently, like a doctor checking on one patient while tests are running for another.</li></ul><h4>Scenario 3: The Separate Examination Rooms (Regular Function)</h4><pre>def separate_room_checkup():<br>    print(&quot;Patient enters&quot;)<br>    time.sleep(5)  # Representing a 5-minute checkup<br>    print(&quot;Patient leaves&quot;)</pre><p>Interestingly:</p><ul><li>FastAPI runs these in separate threads, like having multiple examination rooms.</li><li>Requests can be processed in parallel, even with blocking operations.</li></ul><h3>FastAPI’s Secret Sauce: The Event Loop</h3><p>Imagine FastAPI as a super-efficient hospital:</p><ol><li><strong>Main Reception (Main Thread)</strong>: This is where all async functions are managed.</li><li><strong>Waiting Area (Event Loop)</strong>: Patients (requests) wait here and are handled efficiently.</li><li><strong>Examination Rooms (Separate Threads)</strong>: For regular functions, allowing parallel processing.</li></ol><h3>Best Practices for FastAPI Beginners</h3><ol><li><strong>Use </strong><strong>async def for:</strong></li></ol><ul><li>Database queries</li><li>API calls to external services</li><li>File I/O operations</li><li>Any operation that might take some time but doesn’t use the CPU much</li></ul><p><strong>2. Use regular </strong><strong>def for:</strong></p><ul><li>CPU-intensive tasks</li><li>Operations using libraries without async support</li></ul><p><strong>3. Avoid blocking operations in </strong><strong>async def functions</strong></p><h3>Why FastAPI is Great for Beginners</h3><ol><li><strong>Clear Syntax</strong>: FastAPI’s use of Python type hints makes code more readable and self-documenting.</li><li><strong>Automatic Documentation</strong>: You get interactive API docs for free, great for learning and testing.</li><li><strong>Performance</strong>: It’s fast out of the box, so you don’t need to worry about optimization early on.</li><li><strong>Modern Python</strong>: It encourages use of the latest Python features, keeping your skills up-to-date.</li></ol><h3>Conclusion</h3><p>FastAPI’s efficient request handling is like a well-oiled machine, capable of managing various types of operations smoothly. By understanding these basics, you’re well on your way to building efficient, high-performance APIs with FastAPI.</p><p>Remember, the key to mastering FastAPI is practice. Start with simple endpoints, experiment with both async and regular functions, and gradually build more complex applications. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02d1b4cc22f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Deploy a React Application with Docker and Secure it with Let’s Encrypt SSL]]></title>
            <link>https://choudharycodes.medium.com/how-to-deploy-a-react-application-with-docker-and-secure-it-with-lets-encrypt-ssl-2c57c200bba9?source=rss-c7d4cad27ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c57c200bba9</guid>
            <category><![CDATA[ssl]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[deployment]]></category>
            <dc:creator><![CDATA[Chetan Choudhary]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 16:28:42 GMT</pubDate>
            <atom:updated>2024-06-11T16:29:41.835Z</atom:updated>
            <content:encoded><![CDATA[<p>Deploying a React application using Docker provides a robust and portable way to manage your application. Combining this with Let’s Encrypt for SSL certificates ensures your application is secure. In this article, we will guide you through setting up a React project, containerizing it using Docker, and securing it with Let’s Encrypt SSL certificates.</p><h3>Prerequisites</h3><ul><li>A domain name pointed to your server.</li><li>Docker and Docker Compose are installed on your server.</li><li>Basic knowledge of Docker, Nginx, and SSL certificates.</li></ul><h3>Step 1: Create a Dockerfile for Your React Application</h3><p>First, let’s set up a Dockerfile to build and serve your React application using Nginx.</p><h3>Dockerfile</h3><pre># Stage 1: Build the React application<br>FROM node:14 AS build</pre><pre>WORKDIR /app</pre><pre>COPY package.json ./<br>COPY package-lock.json ./<br>COPY .env ./</pre><pre>RUN npm install</pre><pre>COPY . ./</pre><pre>RUN npm run build</pre><pre># Stage 2: Serve the React application using Nginx<br>FROM nginx:alpine</pre><pre>COPY --from=build /app/dist /usr/share/nginx/html</pre><pre># Copy custom Nginx configuration file<br>COPY nginx.conf /etc/nginx/conf.d/default.conf</pre><pre># Copy SSL certificates (initially empty, will be replaced with Let&#39;s Encrypt certificates)<br>COPY ssl /etc/nginx/ssl</pre><pre>EXPOSE 80 443<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h3>Step 2: Configure Nginx</h3><p>Create an nginx.conf file to configure Nginx to serve your application and redirect HTTP traffic to HTTPS.</p><h3>nginx.conf</h3><pre># Redirect HTTP to HTTPS<br>server {<br>    listen 80;<br>    server_name yourdomain.com <a href="http://www.yourdomain.com/">www.yourdomain.com</a>;<br>    return 301 <a href="https://$host$request_uri/">https://$host$request_uri</a>;<br>}</pre><pre># HTTPS server<br>server {<br>    listen 443 ssl;<br>    server_name yourdomain.com <a href="http://www.yourdomain.com/">www.yourdomain.com</a>;</pre><pre>ssl_certificate /etc/nginx/ssl/fullchain.pem;<br>    ssl_certificate_key /etc/nginx/ssl/privkey.pem;</pre><pre>location / {<br>        root /usr/share/nginx/html;<br>        index index.html index.htm;<br>        try_files $uri $uri/ /index.html;<br>    }<br>}</pre><p>Replace yourdomain.com with your actual domain name.</p><h3>Step 3: Generate SSL Certificates with Let’s Encrypt</h3><p>To generate SSL certificates using Let’s Encrypt, you’ll need to install Certbot.</p><h3>Install Certbot</h3><p>For Debian/Ubuntu-based systems:</p><pre>sudo apt update<br>sudo apt install certbot</pre><h3>Generate SSL Certificates</h3><p>Run the following command to obtain the certificates:</p><pre>sudo certbot certonly --standalone -d yourdomain.com -d www.yourdomain.com</pre><p>This command will place the certificates in /etc/letsencrypt/live/yourdomain.com/.</p><h3>Step 4: Update Dockerfile to Use SSL Certificates</h3><p>Modify your Dockerfile to copy the Let&#39;s Encrypt certificates from your host machine.</p><h3>Updated Dockerfile</h3><pre># Stage 1: Build the React application<br>FROM node:14 AS build</pre><pre>WORKDIR /app</pre><pre>COPY package.json ./<br>COPY package-lock.json ./<br>COPY .env ./</pre><pre>RUN npm install</pre><pre>COPY . ./</pre><pre>RUN npm run build</pre><pre># Stage 2: Serve the React application using Nginx<br>FROM nginx:alpine</pre><pre>COPY --from=build /app/dist /usr/share/nginx/html</pre><pre># Copy custom Nginx configuration file<br>COPY nginx.conf /etc/nginx/conf.d/default.conf</pre><pre># Copy SSL certificates from the host<br>COPY /etc/letsencrypt/live/yourdomain.com/fullchain.pem /etc/nginx/ssl/fullchain.pem<br>COPY /etc/letsencrypt/live/yourdomain.com/privkey.pem /etc/nginx/ssl/privkey.pem</pre><pre>EXPOSE 80 443<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><h3>Step 5: Build and Run Your Docker Container</h3><h3>Build the Docker Image</h3><p>Use the following command to build your Docker image:</p><pre>docker build -t react-nginx .</pre><h3>Run the Docker Container</h3><p>Run the container with the following command:</p><pre>docker run -d --name react-app -p 80:80 -p 443:443 react-nginx</pre><h3>Step 6: Set Up Automatic Renewal for SSL Certificates</h3><p>Let’s Encrypt certificates are valid for 90 days, so you must renew them periodically. You can automate this process using a cron job.</p><h3>Create a Renewal Script</h3><p>Create a script named renew_certificates.sh:</p><pre>#!/bin/bash<br><br>sudo certbot renew<br>docker exec -it react-app nginx -s reload</pre><p>Make the script executable:</p><pre>chmod +x renew_certificates.sh</pre><h3>Set Up a Cron Job</h3><p>Open the cron job editor:</p><pre>crontab -e</pre><p>Add the following line to run the renewal script twice a day:</p><pre>0 0,12 * * * /path/to/renew_certificates.sh &gt;&gt; /var/log/renew_certificates.log 2&gt;&amp;1</pre><h3>Conclusion</h3><p>By following these steps, you have successfully deployed your React application using Docker and secured it with SSL certificates from Let’s Encrypt. This setup ensures that your application is not only robust and portable but also secure. Regularly renewing your SSL certificates with a cron job keeps your application compliant with security best practices.</p><p>Remember to replace yourdomain.com with your actual domain name and ensure all paths in the Dockerfile and scripts are correctly set. With this configuration, you can confidently serve your React application over HTTPS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c57c200bba9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python Decorators made easy]]></title>
            <link>https://choudharycodes.medium.com/python-decorators-made-easy-9d9c6318d748?source=rss-c7d4cad27ae1------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9c6318d748</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Chetan Choudhary]]></dc:creator>
            <pubDate>Thu, 02 Feb 2023 11:04:10 GMT</pubDate>
            <atom:updated>2023-02-02T18:15:41.236Z</atom:updated>
            <content:encoded><![CDATA[<p>Python decorators are a powerful tool that allow you to modify the behavior of a function or class without changing its code. They’re especially useful for adding functionality to existing code, such as logging, timing, or validation. In this blog post, we’ll take a look at how to use decorators in Python, in a very easy way.</p><h4>1. What are Decorators?</h4><p>Decorators are essentially wrapper functions that modify the behavior of another function. They’re defined using the @ symbol, followed by the name of the decorator function. Here&#39;s a simple example:</p><pre>def my_decorator(func):<br>    def wrapper(*args, **kwargs):<br>        print(&quot;Something is happening before the function is called.&quot;)<br>        result = func(*args, **kwargs)<br>        print(&quot;Something is happening after the function is called.&quot;)<br>        return result<br>    return wrapper</pre><pre>@my_decorator<br>def say_hello():<br>    print(&quot;Hello!&quot;)<br>say_hello()</pre><h4>Output:</h4><pre>Something is happening before the function is called.<br>Hello!<br>Something is happening after the function is called.</pre><h4>2. Creating Decorators</h4><p>To create a decorator, you simply define a function that takes another function as an argument and returns a new function that wraps the original function. The wrapper function can then modify the behavior of the original function in any way you like. Here’s another example:</p><pre>def log_function_call(func):<br>    def wrapper(*args, **kwargs):<br>        print(f&quot;Calling {func.__name__} with arguments {args} and keyword arguments {kwargs}&quot;)<br>        result = func(*args, **kwargs)<br>        print(f&quot;{func.__name__} returned {result}&quot;)<br>        return result<br>    return wrapper</pre><pre>@log_function_call<br>def multiply(a, b):<br>    return a * b<br>multiply(2, 3)</pre><h4>Output:</h4><pre>Calling multiply with arguments (2, 3) and keyword arguments {}<br>multiply returned 6</pre><h4>3. Decorating Classes</h4><p>You can also decorate classes in Python using decorators. To do this, you simply create a decorator that takes a class as an argument and returns a modified version of the class. Here’s an example:</p><pre>def uppercase_class_name(cls):<br>    cls.__name__ = cls.__name__.upper()<br>    return cls</pre><pre>@uppercase_class_name<br>class MyClass:<br>    pass<br>print(MyClass.__name__)</pre><pre>Output: MYCLASS</pre><h4>4. Conclusion</h4><p>Decorators are a powerful tool for adding functionality to existing code in Python. Whether you’re adding logging, timing, or validation, decorators can help you keep your code clean and maintainable. With a little practice, you’ll be able to create decorators that solve all sorts of problems in your code. So start experimenting today and see what you can do!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9c6318d748" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>