<?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 Sreelekshmi Jayaprakash on Medium]]></title>
        <description><![CDATA[Stories by Sreelekshmi Jayaprakash on Medium]]></description>
        <link>https://medium.com/@at.sreelekshmi?source=rss-ee4574915f67------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rFXxq1ZfvTg6Fa8LwyesKg.png</url>
            <title>Stories by Sreelekshmi Jayaprakash on Medium</title>
            <link>https://medium.com/@at.sreelekshmi?source=rss-ee4574915f67------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 08:16:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@at.sreelekshmi/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[ The Day My E-commerce App Broke — And How Kafka Fixed It]]></title>
            <link>https://medium.com/@at.sreelekshmi/the-day-my-e-commerce-app-broke-and-how-kafka-fixed-it-64f378acb094?source=rss-ee4574915f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/64f378acb094</guid>
            <dc:creator><![CDATA[Sreelekshmi Jayaprakash]]></dc:creator>
            <pubDate>Mon, 04 May 2026 08:23:15 GMT</pubDate>
            <atom:updated>2026-05-04T08:23:15.382Z</atom:updated>
            <content:encoded><![CDATA[<p>I still remember the day everything <em>looked</em> perfect.</p><p>Orders were flowing in. Payments were working. Notifications were being sent.<br>My e-commerce system felt solid.</p><p>Until it wasn’t.</p><h3>💥 The Breaking Point</h3><p>We launched a flash sale.</p><p>Within minutes:</p><ul><li>Thousands of users clicked <strong>“Buy Now”</strong></li><li>Orders started failing randomly</li><li>Payments were duplicated</li><li>Inventory went negative</li></ul><p>It wasn’t just a bug.<br>It was a <strong>design problem</strong>.</p><h3>😓 The Hidden Issue: Tight Coupling</h3><p>Our system looked something like this:</p><pre>Order Service → Payment Service → Inventory Service → Notification Service</pre><p>Each service directly depended on the next.</p><p>At first, it felt simple and clean. But under load, cracks appeared:</p><ul><li>If Payment Service slowed down → Orders slowed down</li><li>If Inventory failed → Entire flow broke</li><li>If Notification crashed → Order pipeline got stuck</li></ul><p>Everything was <strong>connected too tightly</strong>.</p><p>That’s when I realized:<br>👉 We needed a way to <strong><em>decouple</em></strong> everything.</p><h3>🚀 Enter Kafka</h3><p>Instead of services talking directly to each other, we introduced a middle layer:</p><p><strong>Kafka — a distributed event streaming platform</strong></p><p>Think of it like a <strong>post office</strong>:</p><ul><li>Producers send messages 📤</li><li>Kafka stores and organizes them 📬</li><li>Consumers read them when ready 📥</li></ul><p>This one shift changed everything.</p><h3>🧠 Understanding Kafka Through Our E-commerce Story</h3><p>Let’s rebuild the system using Kafka.</p><h3>1. Producer — Who Sends Data?</h3><p>When a user places an order, the <strong>Order Service</strong> becomes a <em>producer</em>.</p><p>Instead of calling Payment Service directly, it sends an event:</p><pre>{<br>  &quot;order_id&quot;: 101,<br>  &quot;user&quot;: &quot;test&quot;,<br>  &quot;items&quot;: [&quot;Shoes&quot;]<br>}</pre><p>It doesn’t care what happens next.</p><p>It simply says:</p><p>👉 “Here’s the event. Someone else can handle it.”</p><h3>2. Topic — Where Messages Go</h3><p>Kafka organizes messages into <strong>topics</strong>.</p><p>Think of topics as categories:</p><ul><li>orders</li><li>payments</li><li>inventory</li></ul><p>So our Order Service sends data to:</p><p>👉 orders topic</p><h3>3. Consumer — Who Reads Data?</h3><p>Now multiple services independently listen to the same topic:</p><ul><li>Payment Service → processes payments</li><li>Inventory Service → updates stock</li><li>Notification Service → sends alerts</li></ul><p>Each service reacts <strong>on its own time</strong>, without blocking others.</p><h3>4. Broker — The Backbone</h3><p>Kafka runs on servers called <strong>brokers</strong>.</p><p>They:</p><ul><li>Store messages</li><li>Handle reads/writes</li><li>Ensure durability</li></ul><p>Even if a service goes down, messages stay safe.</p><h3>5. Partition — Scaling Like a Pro</h3><p>Here’s where Kafka gets powerful.</p><p>A topic is divided into <strong>partitions</strong>:</p><pre>orders topic:<br>  Partition 0<br>  Partition 1<br>  Partition 2</pre><p>Why?</p><p>👉 To process messages in parallel.</p><p>Instead of one slow pipeline, you now have multiple lanes running simultaneously.</p><h3>6. Ordering — The Subtle Detail</h3><p>Kafka guarantees:</p><p>👉 <strong>Order is maintained only within a partition</strong></p><p>This is critical.</p><p>If you want all events for a user to stay in order:</p><p>👉 Use a <strong>key</strong></p><p>Example:</p><pre>key = user_id</pre><p>Kafka ensures:</p><ul><li>Same key → same partition</li><li>Same partition → correct order</li></ul><h3>🛍️ The New Flow (With Kafka)</h3><p>Let’s replay our system after adopting Kafka:</p><h3>Step 1: Order Created</h3><p>Order Service → publishes event to orders topic</p><h3>Step 2: Payment Processing</h3><p>Payment Service consumes from orders, processes payment, and publishes to payments</p><h3>Step 3: Inventory Update</h3><p>Inventory Service consumes from orders, updates stock</p><h3>Step 4: Notification</h3><p>Notification Service listens and sends confirmation messages</p><p>Now, each service works <strong>independently</strong>.</p><p>No blocking. No cascading failures.</p><h3>⚡ Why Kafka Changed Everything</h3><h3>✅ Loose Coupling</h3><p>Services don’t depend on each other anymore.</p><h3>✅ Fault Tolerance</h3><p>If one service fails, others keep running.</p><h3>✅ Scalability</h3><p>Add more consumers → handle more traffic.</p><h3>✅ Durability</h3><p>Messages are stored safely and can be replayed.</p><h3>🧑‍💻 Using Kafka with FastAPI</h3><p>In Python, a popular async Kafka client is aiokafka.</p><h3>Producer Example (Order Service)</h3><pre>from aiokafka import AIOKafkaProducer<br>import asyncio<br>import json</pre><pre>async def send_order():<br>    producer = AIOKafkaProducer(<br>        bootstrap_servers=&#39;localhost:9092&#39;<br>    )<br>    await producer.start()</pre><pre>    try:<br>        order = {&quot;order_id&quot;: 101, &quot;user&quot;: &quot;test&quot;}<br>        await producer.send_and_wait(<br>            &quot;orders&quot;,<br>            json.dumps(order).encode(&quot;utf-8&quot;),<br>            key=b&quot;user_1&quot;<br>        )<br>    finally:<br>        await producer.stop()</pre><pre>asyncio.run(send_order())</pre><h3>Consumer Example (Payment Service)</h3><pre>from aiokafka import AIOKafkaConsumer<br>import asyncio</pre><pre>async def consume_orders():<br>    consumer = AIOKafkaConsumer(<br>        &quot;orders&quot;,<br>        bootstrap_servers=&#39;localhost:9092&#39;,<br>        group_id=&quot;payment-group&quot;<br>    )<br>    await consumer.start()</pre><pre>    try:<br>        async for msg in consumer:<br>            print(&quot;Processing order:&quot;, msg.value)<br>    finally:<br>        await consumer.stop()</pre><pre>asyncio.run(consume_orders())</pre><h3>🧩 Consumer Groups — The Scaling Trick</h3><p>Let’s say you run multiple instances of Payment Service:</p><pre>Payment Service (3 instances)</pre><p>Kafka distributes partitions among them.</p><p>👉 Each message is processed <strong>once per group</strong>, not duplicated.</p><h3>🔥 When Should You Use Kafka?</h3><p>Kafka is a great fit when:</p><ul><li>You have high traffic systems</li><li>You’re building microservices</li><li>You need asynchronous processing</li><li>Reliability and retry are important</li><li>Real-time data processing is required</li></ul><h3>⚠️ When NOT to Use Kafka</h3><p>Kafka isn’t always the answer.</p><p>Avoid it if:</p><ul><li>Your app is simple CRUD</li><li>Traffic is low</li><li>You don’t need async processing</li></ul><p>Kafka adds complexity — use it when it truly adds value.</p><h3>🎯 Final Thought</h3><p>That day our system broke was frustrating — but necessary.</p><p>It forced us to rethink architecture.</p><p>Kafka didn’t just fix our problem.</p><p>👉 It changed how we design systems.</p><p>Because in the end:</p><p><strong>Kafka isn’t just about moving data — <br>it’s about turning tightly coupled chaos into scalable, resilient systems.</strong></p><p>Happy Coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64f378acb094" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Time and Space Complexity in Python: A Beginner’s Guide]]></title>
            <link>https://medium.com/@at.sreelekshmi/understanding-time-and-space-complexity-in-python-a-beginners-guide-caebb7f4ea09?source=rss-ee4574915f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/caebb7f4ea09</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-basics]]></category>
            <category><![CDATA[time-complexity]]></category>
            <dc:creator><![CDATA[Sreelekshmi Jayaprakash]]></dc:creator>
            <pubDate>Sun, 16 Mar 2025 09:21:00 GMT</pubDate>
            <atom:updated>2025-03-16T09:26:29.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oncJ3XSy1TE71xKgnoMxSQ.png" /></figure><p>Have you ever wondered why some code runs lightning-fast while others make you wait? Or why some programs hog all your memory and crash unexpectedly? Welcome to the fascinating world of time and space complexity — concepts that help us gauge the efficiency of our code.</p><p>In this beginner-friendly guide, we’ll break down these key ideas with simple Python examples. By the end, you’ll have a solid grasp of how to write faster, more memory-efficient programs. Ready? Let’s dive in!</p><h3>🚀 What is Time Complexity?</h3><p>Time complexity measures how the execution time of an algorithm grows as the input size increases. We use <strong>Big O notation</strong> (written as O(something)) to describe this behavior.</p><p>Let’s break it down with real examples.</p><h3>⚡ O(1) — Constant Time</h3><p>An algorithm with O(1) time complexity runs in <strong>constant time</strong>, meaning it doesn’t matter how big your input is — it always takes the same amount of time.</p><pre>def get_first_element(my_list):<br>    return my_list[0]  # Always just one operation, regardless of list size</pre><p>Even if my_list has a million elements, accessing the first item is just one operation—super fast! ⚡</p><h3>📈 O(n) — Linear Time</h3><p>O(n) means the execution time grows <strong>proportionally</strong> with the input size. If your input doubles, the time roughly doubles.</p><pre>def find_max(my_list):<br>    max_value = my_list[0]<br>    for number in my_list:  # This loop runs n times<br>        if number &gt; max_value:<br>            max_value = number<br>    return max_value</pre><p>If my_list has 100 elements, the loop runs <strong>100 times</strong>. If it has 1,000, it runs <strong>1,000 times</strong>. Simple, right? 😊</p><h3>🚨 O(n²) — Quadratic Time</h3><p>O(n²) happens when you have <strong>nested loops</strong> — each input element interacts with every other element.</p><pre>def find_duplicates(my_list):<br>    duplicates = []<br>    for i in range(len(my_list)):  # Outer loop (n)<br>        for j in range(i + 1, len(my_list)):  # Inner loop (n)<br>            if my_list[i] == my_list[j]:<br>                duplicates.append(my_list[i])<br>    return duplicates</pre><p>With 100 elements, this could result in <strong>10,000</strong> comparisons! 😱 Avoid nested loops whenever possible!</p><h3>🏎️ O(log n) — Logarithmic Time</h3><p>O(log n) algorithms <strong>halve the problem size</strong> with each step — very efficient for large inputs.</p><pre>def binary_search(sorted_list, target):<br>    left, right = 0, len(sorted_list) - 1<br>    while left &lt;= right:<br>        mid = (left + right) // 2<br>        if sorted_list[mid] == target:<br>            return mid<br>        elif sorted_list[mid] &lt; target:<br>            left = mid + 1  # Look in the right half<br>        else:<br>            right = mid - 1  # Look in the left half<br>    return -1  # Target not found</pre><p>Even with <strong>1,000,000 elements</strong>, this search takes only about <strong>20 steps</strong>. Impressive, right? 🔥</p><h3>🧠 Common Python Operations &amp; Their Complexities</h3><p>Here’s a handy cheat sheet! 📝</p><pre># O(1) operations<br>my_list = [1, 2, 3, 4, 5]<br>first_item = my_list[0]  # Indexing is O(1)<br>length = len(my_list)  # Getting length is O(1)<br>my_dict = {&quot;name&quot;: &quot;Alice&quot;, &quot;age&quot;: 25}<br>age = my_dict[&quot;age&quot;]  # Dictionary lookup is O(1)</pre><pre># O(n) operations<br>sum_of_items = sum(my_list)  # Must look at each element once: O(n)<br>found = 3 in my_list  # Searching without an index is O(n)</pre><pre># O(n log n) operations<br>sorted_list = sorted(my_list)  # Sorting is typically O(n log n)</pre><h3>🏗️ What is Space Complexity?</h3><p>Space complexity measures how much <strong>extra memory</strong> an algorithm needs. Like time complexity, we use <strong>Big O notation</strong>.</p><h3>O(1) — Constant Space</h3><pre>def sum_list(my_list):<br>    total = 0  # Just one variable<br>    for number in my_list:<br>        total += number<br>    return total</pre><p>No matter how big my_list gets, the function only needs <strong>one variable (</strong><strong>total)</strong>—that’s O(1) space! 🎉</p><h3>O(n) — Linear Space</h3><pre>def double_values(my_list):<br>    doubled = []  # This grows with input size<br>    for number in my_list:<br>        doubled.append(number * 2)<br>    return doubled</pre><p>If my_list has 1,000 elements, doubled will also have <strong>1,000 elements</strong>. That’s <strong>O(n) space</strong>.</p><h3>O(n²) — Quadratic Space</h3><pre>def multiplication_table(n):<br>    table = []<br>    for i in range(n):<br>        row = []<br>        for j in range(n):<br>            row.append(i * j)<br>        table.append(row)<br>    return table</pre><p>A table of size <strong>10 needs 100 cells</strong>, and a table of <strong>100 needs 10,000 cells</strong>. That’s O(n²) space! 🤯</p><h3>🏆 Pro Tips for Writing Efficient Code</h3><h3>✅ Use Built-in Functions</h3><p>Python’s built-in functions are optimized. Use them whenever possible!</p><pre># Better: O(n)<br>maximum = max(my_list)<br># Worse: O(n) but less efficient in practice<br>maximum = my_list[0]<br>for item in my_list:<br>    if item &gt; maximum:<br>        maximum = item</pre><h3>✅ Choose the Right Data Structures</h3><pre># Using a set for fast lookups: O(1) per operation<br>unique_items = set(my_list)<br>is_present = item in unique_items  # O(1)<br># Using a list for lookups: O(n) per operation<br>is_present = item in my_list  # O(n)</pre><h3>✅ Avoid Nested Loops When Possible</h3><pre># O(n²) approach<br>matches = []<br>for x in list1:<br>    for y in list2:<br>        if x == y:<br>            matches.append(x)<br># O(n) approach using sets<br>set2 = set(list2)  # O(n)<br>matches = [x for x in list1 if x in set2]  # O(n)</pre><h3>🎯 Conclusion</h3><p>Understanding time and space complexity isn’t just for computer science textbooks — it’s <strong>essential for writing better Python code</strong>! 🚀</p><p>By recognizing common patterns and optimizing your logic, you’ll build programs that run faster and use less memory. Keep practicing, and soon, you’ll be writing code that’s not just correct but also <strong>efficient</strong>! 💡💻</p><p>Happy coding! 😃</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caebb7f4ea09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing Test Cases in Python for Beginners]]></title>
            <link>https://medium.com/@at.sreelekshmi/writing-test-cases-in-python-for-beginners-d8d08937d392?source=rss-ee4574915f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d08937d392</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[python-unittest]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[test-case]]></category>
            <dc:creator><![CDATA[Sreelekshmi Jayaprakash]]></dc:creator>
            <pubDate>Mon, 03 Mar 2025 11:01:47 GMT</pubDate>
            <atom:updated>2025-03-03T11:21:25.885Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing your code is important to make sure it works as expected. Python provides a built-in module called unittest to help you write tests. In this blog, we’ll learn how to write simple test cases and use mock to test functions that rely on external services.</p><h3>Why Write Test Cases?</h3><ul><li>Helps catch errors early</li><li>Makes debugging easier</li><li>Ensures code works correctly</li><li>Helps when updating or improving code</li></ul><h3>Getting Started with unittest</h3><p>First, create a new Python file (e.g., test_example.py). Import unittest in this file.</p><h3>Writing a Simple Test Case</h3><p>Let’s say we have a function that adds two numbers:</p><pre># math_operations.py<br>def add_numbers(a, b):<br>    return a + b</pre><p>To test this function, we write a test case like this:</p><pre># test_math_operations.py<br>import unittest<br>from math_operations import add_numbers<br><br>class TestMathOperations(unittest.TestCase):<br>    def test_add_numbers(self):<br>        self.assertEqual(add_numbers(2, 3), 5)  # Check if 2 + 3 = 5<br>        self.assertEqual(add_numbers(-1, 1), 0) # Check if -1 + 1 =0<br>if __name__ == &quot;__main__&quot;:<br>    unittest.main()</pre><h3>Running the Test</h3><p>Save the file and run the test using the command:</p><pre>python -m unittest test_math_operations.py</pre><p>If the function works correctly, the test will pass. If not, it will show an error.</p><h3>Using Mock to Test Functions with External Calls</h3><p>Sometimes, functions use external APIs or databases. In tests, we don’t want to call real APIs. Instead, we use unittest.mock to create a fake response.</p><h3>Example: Mocking an API Call</h3><p>Imagine we have a function that gets user data from a website:</p><pre># user_service.py<br>import requests<br><br>def fetch_user(user_id):<br>    response = requests.get(f&quot;https://example.com/users/{user_id}&quot;)<br>    return response.json()</pre><p>We can test this function without calling the real API using mock:</p><pre># test_user_service.py<br>import unittest<br>from unittest.mock import patch<br>from user_service import fetch_user<br><br>class TestUserService(unittest.TestCase):<br>    @patch(&quot;user_service.requests.get&quot;)<br>    def test_fetch_user(self, mock_get):<br>        # Create a fake response<br>        mock_get.return_value.json.return_value = {&quot;id&quot;: 1, &quot;name&quot;: &quot;Alice&quot;}<br>        result = fetch_user(1)<br>        self.assertEqual(result[&quot;name&quot;], &quot;Alice&quot;)<br>        mock_get.assert_called_once_with(&quot;https://example.com/users/1&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    unittest.main()</pre><h3>Mocking a Class Method</h3><p>You can also use mock to replace a method in a class:</p><pre># user.py<br>class User:<br>    def get_full_name(self):<br>        return &quot;John Doe&quot;</pre><p>Test with mock:</p><pre>import unittest<br>from unittest.mock import MagicMock<br>from user import User<br><br>class TestUser(unittest.TestCase):<br>    def test_mock_method(self):<br>        user = User()<br>        user.get_full_name = MagicMock(return_value=&quot;Mocked Name&quot;)<br>        self.assertEqual(user.get_full_name(), &quot;Mocked Name&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    unittest.main()</pre><h3>Conclusion</h3><p>Writing tests helps keep your code error-free and reliable. Using unittest and mock makes testing easy, even when working with external dependencies. Try writing some tests for your own code today!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d08937d392" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Using adduser in Docker]]></title>
            <link>https://medium.com/@at.sreelekshmi/the-importance-of-using-adduser-in-docker-2acd66a9858b?source=rss-ee4574915f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/2acd66a9858b</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[useradd]]></category>
            <dc:creator><![CDATA[Sreelekshmi Jayaprakash]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 07:41:16 GMT</pubDate>
            <atom:updated>2025-02-22T07:41:16.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NlQhvLqMuJ7Y4Be1JO7Q6g.png" /></figure><h3>Introduction</h3><p>Welcome, fellow developers! Have you ever wondered why security experts always emphasize <strong>not running Docker containers as root</strong>? Well, let’s dive into the reasons behind this best practice and explore how using adduser can <strong>supercharge your container security</strong>! 🔐</p><h3>Why Running as Root in Docker is Dangerous ⚠️</h3><p>Think about this: <strong>Would you leave your front door wide open?</strong> Probably not! Running a container as root is like giving an attacker full access to your system. Here’s why it’s risky:</p><p>The container has <strong>full system privileges</strong>, making it a prime target. If an attacker gets in, they can <strong>modify system files or even escape the container</strong>. Some cloud providers <strong>block root containers</strong> due to security concerns. <strong>Privilege escalation</strong> attacks can lead to a compromised host machine.</p><p>💡 <strong>Solution? Create a non-root user using </strong><strong>adduser!</strong></p><h3>Why Should You Use adduser? 🤔</h3><p><strong>Reduces Security Risks</strong> — Even if an attacker gains access, they’ll have limited control. <strong>Prevents Accidental System Modifications</strong> — Avoid unintentional deletions or changes. <strong>Ensures Compatibility</strong> — Many cloud services and Kubernetes environments require non-root execution.</p><h3>How to Add a Non-Root User in Docker 🛠️</h3><p>Let’s look at an example:</p><h3>❌ The Risky Way — Running as Root</h3><pre>FROM python:3.11-slim<br><br>WORKDIR /app<br><br>COPY . .<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>😱 <strong>Yikes! The container runs as root. Let’s fix it!</strong></p><h3>✅ The Secure Way — Using adduser</h3><pre>FROM python:3.11-slim<br><br># Create a non-root user &#39;appuser&#39;<br><br>RUN adduser --disabled-password --gecos &#39;&#39; --no-create-home appuser<br><br>WORKDIR /app<br><br>COPY . .<br><br>RUN chown -R appuser:appuser /app<br><br># Switch to the non-root user<br>USER appuser<br><br>RUN pip install --no-cache-dir -r requirements.txt<br><br>CMD [&quot;python&quot;, &quot;app.py&quot;]</pre><p>🔐 <strong>Boom! Now the container runs as </strong><strong>appuser, making it much safer.</strong></p><h3>Understanding adduser Flags 🔍</h3><p>When using adduser in Docker, we often see these flags:</p><p>🔹 <strong>--disabled-password</strong>: Prevents password authentication. This means the user <strong>cannot log in interactively</strong> using a password, reducing security risks. 🔹 <strong>--no-create-home</strong>: Skips creating a home directory (/home/appuser). This keeps the container lightweight and prevents unnecessary writable directories. 🔹 <strong>--gecos &#39;&#39;</strong>: Skips interactive prompts while creating the user. 🔹 <strong>chown </strong>: Because when you copy files into the container, they <strong>default to being owned by root</strong>. If a non-root user (like appuser) tries to access them, it <strong>might not have the necessary permissions</strong>. By using chown(<strong>change the ownership)</strong>, we ensure appuser has full control over the /app directory.</p><p>By disabling passwords and skipping home directory creation, we ensure: ✅ The user exists <strong>only to run the application</strong> and <strong>cannot be used for interactive access</strong>. ✅ The container stays <strong>minimal</strong> and <strong>secure</strong>. ✅ The user <strong>cannot elevate privileges</strong> inside the container.</p><h3>Conclusion 🎯</h3><p>Using adduser in your Dockerfile is a <strong>simple yet powerful way</strong> to enhance security and prevent attacks. Think of it as adding an extra lock to your digital home! 🏠🔒</p><p>So, what are you waiting for? Go ahead and <strong>implement these changes today</strong> to secure your Docker applications! 🚀</p><p>💬 <strong>What are your thoughts? Have you encountered security issues in Docker? Let’s discuss in the comments below!</strong> 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2acd66a9858b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[# Django REST Framework Error Handling: A Practical Guide]]></title>
            <link>https://medium.com/@at.sreelekshmi/django-rest-framework-error-handling-a-practical-guide-7c57bf8cedff?source=rss-ee4574915f67------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c57bf8cedff</guid>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[error-handling-in-python]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[third-party]]></category>
            <dc:creator><![CDATA[Sreelekshmi Jayaprakash]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 09:40:15 GMT</pubDate>
            <atom:updated>2025-02-16T01:04:40.792Z</atom:updated>
            <content:encoded><![CDATA[<h3>Django REST Framework Error Handling: A Practical Guide</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W47teZBgdEvY71mMzYp9Kw.jpeg" /></figure><p><strong>Introduction</strong></p><p><em>Picture this</em>: You&#39;ve built a Django API that&#39;s working perfectly in your development environment. Then one day, a third-party service it depends on goes down, and suddenly your logs are flooded with unhandled exceptions. Sound familiar? In this guide, we&#39;ll explore how to implement robust error handling in Django REST Framework (DRF) that will make your APIs more reliable and maintainable.</p><p><strong>The Challenge</strong></p><p>Modern APIs often involve complex operations with multiple layers:<br>- External API calls that can fail<br>- Business logic that needs validation<br>- Database operations that might timeout<br>- Input validation at various levels</p><p>Without proper error handling, these complexities can lead to:<br>- Cryptic error messages exposed to end-users<br>- Difficult-to-debug issues in production<br>- Inconsistent API responses<br>- Security vulnerabilities</p><p>Let&#39;s solve these problems step by step.</p><p>First, let&#39;s create custom exceptions that make our error handling more expressive and maintainable:</p><pre>from rest_framework.exceptions import APIException<br>from rest_framework import status</pre><pre>class ThirdPartyAPIException(APIException):<br>   status_code = status.HTTP_503_SERVICE_UNAVAILABLE<br>   default_detail = &#39;Third party service error&#39;<br>   default_code = &#39;third_party_error&#39;</pre><pre>class BusinessLogicException(APIException):<br>   status_code = status.HTTP_400_BAD_REQUEST<br>   default_detail = &#39;Business logic error&#39;<br>   default_code = &#39;business_logic_error&#39;<br></pre><p>These custom exceptions help us:<br>- Define specific HTTP status codes for different error types<br>- Provide clear, consistent error messages<br>- Distinguish between different error categories</p><p><strong>Implementing Layered Error Handling</strong></p><p>Let&#39;s look at a real-world example of how to implement error handling in a Django API view:</p><pre>class UserDataAPIView(APIView):<br>   def get(self, request):<br>     try:<br>       user_id = request.query_params.get(&#39;user_id&#39;)<br>       result = self._process_user_data(user_id)<br>       return Response(result, status=status.HTTP_200_OK)<br>     except ThirdPartyAPIException as e:<br>       logger.error(f&quot;Third party API error: {str(e)}&quot;, exc_info=True)<br>       return Response(<br>           {&#39;error&#39;: &#39;External service temporarily unavailable&#39;},<br>           status=status.HTTP_503_SERVICE_UNAVAILABLE<br>           )<br>     except BusinessLogicException as e:<br>       return Response(<br>           {&#39;error&#39;: str(e)},<br>           status=status.HTTP_400_BAD_REQUEST<br>           )</pre><ol><li><strong>Top Level (View Layer)<br></strong>- Catch all expected exceptions<br>- Log errors appropriately<br>- Return user-friendly responses<br>- Use correct HTTP status codes</li></ol><p><strong>2. Middle Layer (Business Logic)</strong></p><pre>def _process_user_data(self, user_id):<br>   if not user_id:<br>     raise BusinessLogicException(&#39;User ID is required&#39;)<br>   <br>   try:<br>     external_data = self._fetch_external_data(user_id)<br>     return self._transform_data(external_data)<br>   except requests.RequestException as e:<br>     raise ThirdPartyAPIException(f&#39;Failed to fetch external data: {str(e)}&#39;)</pre><p>Key points:<br>- Convert low-level exceptions to custom ones<br>- Validate input parameters<br>- Handle business logic errors explicitly</p><p><strong>3. Bottom Layer (External Services)</strong></p><pre><br>def _fetch_external_data(self, user_id):<br>   try:<br>     response = requests.get(f&#39;https://api.thirdparty.com/users/{user_id}&#39;,timeout=5)<br>     response.raise_for_status()<br>     return response.json()<br>   except requests.RequestException:<br>     raise # Let parent handle it</pre><p>Key points:<br>- Set appropriate timeouts<br>- Use specific exception types<br>- Let exceptions bubble up when appropriate</p><p><strong>Logging Strategies</strong></p><p>Proper logging is crucial for debugging production issues:</p><pre>import logging<br>logger = logging.getLogger(__name__)</pre><pre># In your error handling:<br>logger.error(<br>   &quot;Failed to process user data&quot;,<br>   extra={<br>   &#39;user_id&#39;: user_id,<br>   &#39;error_details&#39;: str(e)<br>   },<br>   exc_info=True<br>  )</pre><p>Tips for effective logging:<br>- Include relevant context<br>- Use appropriate log levels<br>- Don&#39;t log sensitive information<br>- Include stack traces for unexpected errors</p><p><strong>Security Considerations</strong></p><p>When handling errors, always remember:<br>- Never expose internal error details to users<br>- Sanitize error messages<br>- Log sensitive information securely<br>- Use appropriate HTTP status codes</p><p><strong>Testing Error Handling</strong></p><p>Don&#39;t forget to test your error handling:</p><pre>def test_third_party_api_error(self):<br>   with patch(&#39;requests.get&#39;) as mock_get:<br>     mock_get.side_effect = requests.ConnectionError()<br>     response = self.client.get(&#39;/api/user-data/?user_id=123&#39;)<br>     self.assertEqual(response.status_code, 503)<br>     self.assertIn(&#39;error&#39;, response.json())</pre><p><strong>Conclusion</strong></p><p>Proper error handling is not just about catching exceptions – it&#39;s about creating a robust system that:<br> - Provides clear feedback to users<br> - Makes debugging easier<br> - Maintains security<br> - Ensures reliability</p><p><em>Remember: The time you spend implementing proper error handling will save you countless hours of debugging and maintenance in the future.</em></p><p><strong>Additional Resources</strong></p><p>- [Django REST Framework Exceptions Documentation](https://www.django-rest-framework.org/api-guide/exceptions/)<br>- [Python Logging Best Practices](https://docs.python.org/3/howto/logging.html)<br>- [HTTP Status Codes](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c57bf8cedff" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>