<?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 Anurag Kumar on Medium]]></title>
        <description><![CDATA[Stories by Anurag Kumar on Medium]]></description>
        <link>https://medium.com/@akanuragkumar?source=rss-854db477af7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YyDiKhslAgCrd0sR3StXTg.jpeg</url>
            <title>Stories by Anurag Kumar on Medium</title>
            <link>https://medium.com/@akanuragkumar?source=rss-854db477af7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:09:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akanuragkumar/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[Streaming AI Agents Responses with Server-Sent Events (SSE): A Technical Case Study]]></title>
            <link>https://akanuragkumar.medium.com/streaming-ai-agents-responses-with-server-sent-events-sse-a-technical-case-study-f3ac855d0755?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3ac855d0755</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[langchain]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 10:31:58 GMT</pubDate>
            <atom:updated>2025-08-14T11:05:41.857Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AkfydtT3UOj20IM-" /></figure><p>At <a href="https://www.senseloaf.ai/"><strong>Senseloaf.ai</strong></a>, we’ve built an AI-powered Hiring Agent that helps recruiters by analysing job descriptions and candidate profiles using advanced language models. It’s smart and thorough, powered by a multi-step reasoning pipeline with tools like LangChain, which means it can take time to produce a final answer.</p><p>The problem? Users staring at a blank screen or a loading spinner for half a minute will grow anxious, thinking the system is unresponsive or broken. We needed to <strong>remove user anxiety during long-running AI tasks</strong>. Our solution was to <strong>stream live progress updates</strong> to the frontend, giving users real-time insight into what the AI is doing. This way, even if the total processing time remains the same, the experience <em>feels</em> faster and more interactive</p><p>In this technical blog, we’ll dive into how we implemented <strong>Server-Sent Events (SSE)</strong> in a FastAPI backend with Celery and Redis to stream an AI agent’s progress to a React frontend. We’ll walk through the architecture and the code that powers this solution, using our Hiring Agent use case as the running example.</p><h4><strong>The Problem: Long-Running “Agentic” AI Tasks</strong></h4><p>Our Hiring Assistant uses an <em>agentic</em> AI workflow -essentially a sequence of steps involving multiple reasoning or API calls orchestrated by an AI agent (using <strong>LangChain</strong> under the hood). For example, given a job description and a list of candidates, the agent might:</p><ol><li><strong>Analyze the Job Description -</strong>e.g., extract key requirements and role objectives.</li><li><strong>Evaluate Each Candidate</strong> -for each candidate, read their resume and compare with the job requirements.</li><li><strong>Generate a Recommendation -</strong>decide which candidate is the best fit and formulate an answer.</li></ol><p>Each of these steps might involve heavy computation or external API calls (like calling an LLM for each comparison). As a result, the total process could take, say, 30 seconds or more.</p><p>If we implemented this naively (synchronously), the user would send a request and just <strong>wait 30 seconds</strong> for a single response. That’s unacceptable for UX — users might think the application froze or crashed. Even if we show a simple spinner, 30 seconds of silence is agonisingly long.</p><h4><strong>Solution Overview: Async Processing with Real-Time Streaming Updates</strong></h4><p>To solve this, we designed an architecture that <strong>decouples the long-running task from the user-facing request</strong> and streams progress updates back to the client. The key components are:</p><ul><li>FastAPI Backend -Provides endpoints for initiating the task and for streaming updates.</li><li>Celery + Redis -Handles the heavy lifting in the background (Celery workers run the AI agent tasks). Redis serves as both the Celery broker/result backend and a real-time message channel for progress updates.</li><li>Server-Sent Events (SSE) -Used to push updates to the frontend over HTTP. SSE is a simple protocol that keeps an HTTP connection open, allowing the server to send data to the client whenever new information is available.</li><li>React Frontend -Initiates the process and listens to the SSE stream, updating the UI with incoming progress messages (structured insights from the AI).</li></ul><p>Why SSE and not WebSockets? For our use-case, we only needed one-way communication (server -&gt; client). SSE is ideal here — it’s simpler to implement than WebSockets, works over standard HTTP, and has built-in support in browsers via the EventSource API. This keeps our stack lightweight while fulfilling the real-time update requirement.</p><h3>Architecture Overview</h3><p>High-level architecture of the streaming backend. Clients send requests to FastAPI (which streams results back via SSE), and heavy tasks are offloaded to Celery worker processes via a message broker (Redis). The Celery workers execute jobs asynchronously and update progress/results in Redis (acting as both broker and result store). FastAPI pulls these updates and streams them to clients in real-time. This decoupled design allows API servers and workers to scale independently, dramatically improving throughput and latency under load.</p><p>At a high level, the flow is as follows:</p><p><strong>1. Client Request:</strong> A client (e.g. a frontend or another service) initiates a long-running operation by calling an API endpoint on the FastAPI server. Instead of waiting synchronously, this endpoint will immediately enqueue a background task and return a response stream.</p><p><strong>2. Task Queuing:</strong> The FastAPI app pushes the job to a Celery <strong>task queue</strong> (using Redis as the broker). Celery acts as a <strong>producer-consumer</strong> system: the API server is the producer (client) adding a message to the queue, and one of the Celery worker processes will consume that message and execute the task.</p><p><strong>3. Background Processing:</strong> Celery workers, running in separate processes or containers, constantly listen on the queue (Redis). We will configure <strong>two queues</strong>: for example, a high-priority queue for urgent tasks, and a default queue for normal tasks. This separation ensures critical tasks aren’t stuck behind less important work -a recommended approach to task prioritization. We can deploy dedicated workers for each queue (e.g. fewer, fast workers for the high-priority tasks, and more workers for the default queue). The worker picks up the task and processes it, which could involve CPU-intensive AI computations or calls to external services.</p><p><strong>4. Progress Updates:</strong> As the task runs, it can emit progress updates. There are a couple of strategies here:</p><ul><li><strong>Polling the Task State:</strong> The FastAPI server can poll the task’s state via Celery’s result backend. Celery supports task states (PENDING, STARTED, SUCCESS, etc.) and even custom metadata. For example, the task can periodically call update_state(meta=...) to record its progress percentage. The API server, in an async loop, checks the task state and retrieves these updates.</li><li><strong>Push via Pub/Sub:</strong> Alternatively, the Celery task can publish messages to a Redis <strong>pub/sub</strong> channel, and the FastAPI server can subscribe to that channel to receive updates in real-time. This is a more <em>push-based</em> model and can reduce latency further (no polling delay). For our example, we’ll illustrate the polling approach for simplicity, but note that using Redis pub/sub for instant updates is also a viable pattern (it’s essentially how a dedicated “Event Server” could work).</li></ul><p><strong>5. SSE Streaming to Client:</strong> The FastAPI endpoint returns a streaming HTTP response. Using SSE (content type text/event-stream), the server can keep the connection open and <strong>continuously send events</strong> to the client as new data becomes available. Each event might be a JSON chunk of progress info, logs, or partial results. The client (in a browser, this could be via the <strong>EventSource</strong> API) receives these events and can update the UI in real-time. SSE ensures the client doesn’t have to poll repeatedly; one connection delivers all updates.</p><p><strong>6. Task Completion:</strong> Once the Celery task finishes, the final result (e.g. the AI computation output) is stored in Redis (as the Celery result backend) and/or published as a last event. The FastAPI SSE handler will detect completion (either via the task state turning to SUCCESS or a final pub/sub message) and push a final event to the client before closing the stream. The client then knows the operation is done (it could, for example, display the result to the user and close the EventSource).</p><p>Throughout this flow, none of the heavy lifting blocks the main FastAPI server. The API process is free to handle new requests even while background tasks are running. This means we can scale each part independently: if the bottleneck is CPU-bound tasks, we add more Celery workers; if we need to handle more simultaneous client connections or initial request throughput, we scale out FastAPI instances. Redis in the middle handles the messaging at high speed (in-memory operations). It’s important to configure each component for performance -which we’ll cover after the core implementation.</p><h3>Implementing the Streaming API with FastAPI and SSE</h3><p>Let’s start by creating the FastAPI endpoint that will kick off a background task and stream updates to the client. FastAPI’s flexibility allows us to return a StreamingResponse for SSE. We’ll use this to send chunked responses in the format event: &lt;type&gt;\ndata: &lt;json_data&gt;\n\n. As a simple example, our AI agent might be doing a multi-step analysis. We’ll simulate that with a loop and send progress events.</p><p><strong>FastAPI SSE Endpoint (</strong><strong>main.py):</strong></p><pre>from fastapi import FastAPI<br>from fastapi.responses import StreamingResponse<br>import asyncio<br>from celery.result import AsyncResult<br>from .worker import celery_app, run_agent_task<br><br>app = FastAPI()<br><br>@app.get(&quot;/run-agent-stream&quot;)<br>async def run_agent_stream(query: str):<br>    &quot;&quot;&quot;Endpoint to start the agent task and stream back its progress/results.&quot;&quot;&quot;<br>    # 1. Enqueue the long-running task in Celery (e.g., high_priority queue)<br>    task = run_agent_task.apply_async(args=[query], queue=&quot;high_priority&quot;)<br>    task_id = task.id<br><br>    # 2. Define an async generator to yield Server-Sent Events<br>    async def event_stream():<br>        # Immediately notify the client that the task was accepted<br>        yield f&quot;event: start\ndata: Task {task_id} started\n\n&quot;<br>        # Continuously poll task state and yield progress<br>        while not task.ready():<br>            if task.state == &quot;PROGRESS&quot;:<br>                info = task.info or {}<br>                progress = info.get(&quot;progress&quot;, 0)<br>                # Stream a progress update event<br>                yield f&quot;event: progress\ndata: {progress}% complete\n\n&quot;<br>            await asyncio.sleep(1)  # small delay between polls<br>        # Task is done, get the result<br>        result = task.get()<br>        # Stream the final result event (could be large JSON)<br>        yield f&quot;event: result\ndata: {result}\n\n&quot;<br>        # The generator will naturally exit, closing the SSE stream<br><br>    # 3. Return a StreamingResponse that uses our generator<br>    return StreamingResponse(event_stream(), media_type=&quot;text/event-stream&quot;)</pre><p>In this <strong>/run-agent-stream</strong> endpoint, we do the following:</p><ul><li><strong>Enqueue the task:</strong> We call our Celery task (defined later as run_agent_task) via apply_async, passing the user’s query and specifying the high_priority queue. Celery returns immediately with an AsyncResult (containing the task_id). FastAPI doesn’t wait for the task to finish; it proceeds to streaming the response. We send an initial event to inform the client the task has started. This also ensures the SSE headers are sent promptly (establishing the event stream).</li><li><strong>Stream progress events:</strong> We enter an async loop, periodically checking task.ready() (which becomes True when the task is finished or failed). If the task state is PROGRESS, we pull the progress percentage from task.info (populated via Celery’s update_state). We yield an SSE event with that progress. Each yield sends a chunk of data down to the client. Note that SSE requires each message to end with a double newline (\n\n) and includes an event: name field for custom event types. Here we use event: progress for intermediate updates, and event: result for the final output.</li><li><strong>Finalize the stream:</strong> Once the task is done (task.ready() becomes true), we fetch the result (this will wait briefly if the task just finished). We then yield a final event containing the result data. After that, the function exits, and FastAPI will close out the HTTP response. On the client side, the EventSource would receive the &quot;result&quot; event and know the stream ended (the server can also send a special event: end or just close the connection).</li></ul><p>This SSE approach ensures <strong>low latency updates</strong> to the client. Instead of polling a status endpoint every few seconds (which introduces delay and load), the client gets pushed updates as soon as they’re available. And because it’s just an HTTP response under the hood, it scales well: SSE connections are lightweight (text streaming over HTTP) and don’t require special WebSocket infrastructure. The main consideration is keeping many connections open, which FastAPI/Uvicorn can handle with async workers, just be mindful to tune the Uvicorn workers or use Gunicorn with UVLoop for heavy loads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*Ks6mV_yaTRtF8l6E.jpeg" /></figure><p><strong>Note:</strong> In a real production setting, you might offload even the SSE handling to a separate process or thread to avoid any back-pressure on the FastAPI event loop. The approach above, however, works well for many cases and keeps things simple by using the Celery result backend for progress. If we needed truly instantaneous pushes, we could integrate a Redis pub/sub listener inside event_stream() (instead of polling), or use an async queue mechanism to push updates from the Celery worker to the FastAPI side.</p><h3>Offloading Work with Celery Tasks (and Prioritizing Queues)</h3><p>Now, let’s define the Celery app and the background task. We will create a Celery instance, configure it to use Redis, and define our run_agent_task that the FastAPI endpoint calls. This task will simulate a long-running process by sleeping and updating its progress. In a real AI agent scenario, this could be where the AI model runs inference, calls other APIs, or performs step-by-step reasoning.</p><p><strong>Celery Application &amp; Task (</strong><strong>worker.py):</strong></p><pre>from celery import Celery<br><br># Initialize Celery with Redis as broker and result backend<br>celery_app = Celery(&quot;agent_worker&quot;,<br>    broker=&quot;redis://redis:6379/0&quot;,<br>    backend=&quot;redis://redis:6379/0&quot;<br>)<br># Celery configuration for reliability and performance<br>celery_app.conf.update(<br>    result_expires=3600,               # Task results expire in 1 hour (cleanup)<br>    task_track_started=True,           # Enable tracking the STARTED state of tasks<br>    task_acks_late=True,               # Acknowledge tasks after execution, not before<br>    task_reject_on_worker_lost=True,   # Reschedule task if worker crashes:contentReference[oaicite:19]{index=19}<br>    worker_prefetch_multiplier=1,      # Each worker grabs only 1 task at a time:contentReference[oaicite:20]{index=20}<br>    task_routes={                     # Route certain tasks to specific queues<br>        &#39;app.worker.run_agent_task&#39;: {&#39;queue&#39;: &#39;high_priority&#39;}<br>    }<br>)<br><br>@celery_app.task(bind=True)<br>def run_agent_task(self, query: str) -&gt; str:<br>    &quot;&quot;&quot;Long-running AI task that processes the user query.&quot;&quot;&quot;<br>    # Simulate work in stages with progress updates<br>    total_steps = 5<br>    for step in range(total_steps):<br>        # ... perform part of the computation (e.g., call AI model) ...<br>        # Here we just sleep to simulate time-consuming work<br>        import time; time.sleep(1)<br>        # Update task progress (percentage)<br>        percent = int(((step+1) / total_steps) * 100)<br>        self.update_state(state=&quot;PROGRESS&quot;, meta={&quot;progress&quot;: percent})<br>    # (In a real scenario, assemble the final result from the computation)<br>    result = f&quot;Result for &#39;{query}&#39;&quot;<br>    return result</pre><p>A few things to note in this <strong>Celery setup and task</strong>:</p><ul><li>We configure <strong>Redis as both the broker and the result backend</strong>. This means Redis will handle the queue of tasks and also store task statuses/results so we can query them. Redis is a popular choice for Celery in part because of its speed, though for very large deployments you might use RabbitMQ as a broker for more robust queue semantics and keep Redis for results. For simplicity, one Redis is sufficient here.</li><li>The Celery.conf.update(...) section applies some <strong>important optimizations</strong>:</li><li><strong>result_expires=3600:</strong> We don’t want Redis to fill up with old task results. This setting ensures that after an hour, results are cleared. In a long-running AI agent scenario, you might not need to store results for too long once sent to the client, so this prevents memory bloat.</li><li><strong>task_track_started=True:</strong> By default, Celery tasks are either PENDING or SUCCESS/FAILURE; enabling this flag allows a <strong>STARTED</strong> state, which is useful if we want to know when a task actually began execution (it emits a “task started” event). We set this so we could, for instance, notify the client that processing has really commenced (though in our SSE we already send a &#39;started&#39; event).</li><li><strong>task_acks_late=True and </strong><strong>task_reject_on_worker_lost=True:</strong> These two combined improve reliability. By acknowledging tasks <em>after</em> completion, we ensure that if a worker dies mid-task (say, the container crashes), the task isn’t lost; task_reject_on_worker_lost will put the task back in the queue to be picked up by another worker. This assumes your tasks are <strong>idempotent</strong> (safe to run twice), but it’s a crucial setting for fault tolerance in production.</li><li><strong>worker_prefetch_multiplier=1:</strong> Celery workers by default fetch multiple tasks in advance (prefetch). For long-running tasks, this is not ideal – a worker might reserve tasks it won’t get to for a while, leading to idle tasks while other workers sit idle. Setting prefetch to 1 means a worker takes only one task at a time, preventing any single worker from holding a backlog. This maximizes parallelism across workers for CPU-bound jobs. (If tasks were very short, a higher prefetch could improve throughput by reducing broker round-trips, but that’s not our case.)</li><li><strong>task_routes:</strong> Here we route the run_agent_task to the high_priority queue. This is one way to send tasks to specific queues. We could also specify the queue at call time (as we did in apply_async(..., queue=&quot;high_priority&quot;)), but defining routes in config ensures <em>any</em> invocation of this task goes to the right queue by default. By segregating queues, we can run separate Celery workers listening on only the high-priority queue versus the default queue. This is the recommended strategy for task prioritization in Celery, it gives you fine-grained control. For example, you might run 2 workers for high-priority (so that at least two urgent tasks can run concurrently) and 5 workers for default tasks. If no high-priority tasks are queued, those specialized workers will simply be idle (which is often acceptable to guarantee capacity when needed).</li><li>The @celery_app.task(bind=True) decorator defines our task function. Using bind=True allows the task to access self, which is the Task instance – this is how we call self.update_state(). The task itself simply loops 5 times, sleeping 1 second each to simulate work, and updates progress (20%, 40%, ... 100%). In a real agent, each loop might represent a reasoning step or a chunk of data processed. Finally, we return a result (here just a string). This return value will be stored in Redis (for retrieval via AsyncResult.get() in the FastAPI code) and could also be sent in the SSE stream.</li></ul><p>With Celery in place, any FastAPI process (or any client for that matter) can enqueue work, and our workers will pull tasks off the queue. We’ve effectively decoupled the request/response lifecycle from the actual processing. The FastAPI thread handling the request quickly hands off to Celery and is free to handle another request — this is how we achieve high throughput. As Celery’s own docs put it: a task queue allows work to be distributed across threads or machines, with workers executing tasks asynchronously.</p><h3>Containerization with Docker Compose</h3><p>To run this system in production (or locally for testing), Docker Compose is an invaluable tool. We can define all the services — FastAPI app, Celery workers, Redis, and monitoring tools — and run them together. Below is a <strong>Docker Compose configuration</strong> that sets up our backend:</p><pre>version: &quot;3.8&quot;<br>services:<br>  api:<br>    build: .  # Dockerfile builds the FastAPI app image<br>    command: uvicorn app.main:app --host 0.0.0.0 --port 8000<br>    environment:<br>      - CELERY_BROKER_URL=redis://redis:6379/0<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0<br>    depends_on:<br>      - redis<br>    ports:<br>      - &quot;8000:8000&quot;<br>    # (Consider multiple replicas of api for scaling out, behind a load balancer)<br>  <br>  celery_worker_default:<br>    build: .  # reuse the same image that has Celery and our code<br>    command: celery -A app.worker.celery_app worker -Q default -c 4 --loglevel=info<br>    depends_on:<br>      - redis<br>    environment:<br>      - C_FORCE_ROOT=true        # (if running as root in container, allow Celery)<br>    # This worker will only process the &quot;default&quot; queue, concurrency=4<br>  <br>  celery_worker_priority:<br>    build: .<br>    command: celery -A app.worker.celery_app worker -Q high_priority -c 2 --loglevel=info<br>    depends_on:<br>      - redis<br>    # This worker processes only &quot;high_priority&quot; tasks, concurrency=2 (fewer, but dedicated)<br>  <br>  redis:<br>    image: redis:7-alpine<br>    container_name: redis<br>    ports:<br>      - &quot;6379:6379&quot;<br>    volumes:<br>      - redis_data:/data<br>    # Using a volume to persist data (so result backend isn&#39;t lost if Redis restarts)<br>    # In production, you&#39;d secure Redis with auth and possibly use Redis cluster for HA.<br>  <br>  flower:<br>    image: mher/flower:1.2.0<br>    command: celery -A app.worker.celery_app flower --port=5555 --address=0.0.0.0<br>    depends_on:<br>      - redis<br>      - celery_worker_default<br>    ports:<br>      - &quot;5555:5555&quot;<br>    environment:<br>      - FLOWER_BASIC_AUTH=user:pass  # protect the Flower dashboard with basic auth (optional)<br>      - CELERY_BROKER_URL=redis://redis:6379/0<br>      - CELERY_RESULT_BACKEND=redis://redis:6379/0</pre><p>A breakdown of this Compose file:</p><ul><li>We have an <strong>api service</strong> for our FastAPI application. It uses Uvicorn to run the app on port 8000. We pass environment variables to configure Celery (the app will read those in worker.py when initializing Celery). In a real deployment, you might run multiple instances of this API behind a load balancer for handling many SSE clients concurrently. (SSE connections are typically sticky to one server instance.)</li><li>Two Celery worker services are defined: one for the <strong>default queue</strong> and one for the <strong>high_priority queue</strong>. Each uses the same code image but runs a different command:</li><li>celery_worker_default runs celery ... -Q default -c 4, meaning it’ll listen on the “default” queue with a concurrency of 4 (four worker processes inside, by default Celery uses prefork model).</li><li>celery_worker_priority runs with -Q high_priority -c 2, so two processes focusing on the high_priority queue. We choose fewer processes here assuming high_priority tasks might be CPU-intensive and we want to avoid contention – adjust these numbers based on actual workload and CPU cores available. As a best practice, you’d typically set --concurrency close to the number of CPU cores available to that container (for CPU-heavy tasks, using more workers than cores can lead to context switching overhead with little gain). We explicitly separate the queues so that even if the default queue is backed up with slow tasks, a new high_priority task can start immediately on its own worker.</li><li>The <strong>Redis service</strong> uses an official image. We map the port for visibility (not strictly required if everything is in the same Docker network for internal communication). We also use a named volume redis_data to persist data. In production, if using Redis purely as a transient broker and cache, you might not need persistence (or you might run Redis in a managed service). But since we also store results, persistence can help during restarts. We could also fine-tune Redis: for example, if results are ephemeral, we might disable RDB/AOF persistence for performance, set a max memory policy, etc., depending on the reliability requirements. We’d also ensure the Redis instance has enough memory for the peak number of tasks and results stored.</li><li>The <strong>Flower service</strong> is included for observability of Celery. Flower is a web dashboard for Celery tasks and workers. We set it to run on port 5555 and provide the broker and backend URLs. Once up, you can open http://localhost:5555 to see the task monitoring UI (it will show active tasks, completed tasks, worker statuses etc). We also demonstrated how to secure Flower with a basic auth in the environment variables – in a real setup, you wouldn’t want an open dashboard. Flower is a very useful tool in production to keep an eye on the background jobs.</li></ul><blockquote><strong><em>Compose Scaling Tip:</em></strong><em> We could define our Compose in a way that allows scaling the workers easily (e.g., using Docker Compose profiles or replicas). For example, we might start with </em><em>celery_worker_default as 2 replicas and </em><em>celery_worker_priority as 1, and adjust via the command line or an orchestration tool based on load. The key is that by separating queues, we maintain control over resource allocation to different task types. “The workers can subscribe to specific queues… each worker group can share the load,” as one guide notes – this exactly describes our approach of splitting high-priority and default tasks.</em></blockquote><p>Additionally, though not shown to keep the snippet concise, you could include <strong>Prometheus and Grafana</strong> services in this Compose file (or deploy them separately). For instance, a Prometheus container could scrape metrics from the FastAPI app (if you expose /metrics using something like Prometheus FastAPI Instrumentation) and also scrape Celery metrics (Celery doesn’t expose Prometheus metrics out of the box, but you can capture stats like task durations via logs or use custom exporters). Grafana would then be used to visualize those metrics. Monitoring is crucial – you’d want to track the queue lengths, task execution times, worker CPU usage, memory, etc., to identify bottlenecks. <strong>Grafana + Prometheus</strong> provide the observability pillar for metrics, complementing Flower’s specialized Celery view. In production, you might also aggregate logs (ELK stack or Graylog) and set up alerting on metrics (e.g., if the queue backlog is growing, or if tasks are erroring out).</p><h3>Benchmarking Performance (Before vs. After Optimization)</h3><p>To ensure our architecture meets the goals, we should benchmark it. Let’s compare a baseline implementation (e.g., a naive approach without these optimizations) against our optimized setup:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Evf8D--er-KtVPMQlxda-Q.png" /></figure><h3>Key Takeaways and Best Practices</h3><p>Building a real-time streaming backend for long-running AI tasks requires carefully balancing concurrency, responsiveness, and throughput. Here are some key learnings and best practices from our journey:</p><ul><li><strong>Decouple Work from Request Cycle:</strong> Use background task queues (Celery) to handle long operations. FastAPI stays fast for incoming requests by instantly delegating heavy work to Celery. This decoupling is what allowed us to achieve massive throughput gains without “melting the server.”</li><li><strong>Stream, Don’t Poll:</strong> Server-Sent Events provide a simple yet powerful way to push progress and results to clients in real time. SSE is easier to scale than full duplex channels in many scenarios, since it’s essentially HTTP streaming. Always prefer pushing updates over forcing clients to poll — it improves user experience and reduces unnecessary load.</li><li><strong>Prioritise with Separate Queues:</strong> Avoid Celery’s built-in numeric priority within a single queue (which can be unreliable); instead, assign tasks to different named queues based on urgency or type. Run dedicated worker processes for each queue so you can scale and tune them independently. This guarantees high-priority tasks get worker attention quickly, while low-priority tasks don’t starve but also don’t clog critical paths.</li><li><strong>Tune Worker Concurrency and Prefetch:</strong> Match Celery worker concurrency to your CPU cores for CPU-bound tasks (or higher if I/O-bound). Disable prefetching (or set to 1) for long tasks to prevent uneven work distribution. These settings ensure efficient usage of resources and predictable latency — no task waits in a worker’s private queue while another core sits idle.</li><li><strong>Use Reliable Ack Settings:</strong> In production, always configure task_acks_late=True with caution and ensure idempotency. Combined with task_reject_on_worker_lost=True, this makes your system resilient to worker crashes or restarts – tasks will be retried on another worker instead of silently lost. Without this, a server failure could mean a task vanishes (at-most-once delivery), which is unacceptable for important jobs.</li><li><strong>Observe and Instrument:</strong> Employ tools like <strong>Flower</strong> for real-time Celery monitoring — it’s invaluable to see what tasks are doing and identify failures or bottlenecks. For system-wide observability, integrate <strong>Prometheus</strong> to gather metrics (request rates, task durations, queue lengths, memory usage) and <strong>Grafana</strong> to visualise them. This helps in capacity planning (e.g., do we need more workers?) and in catching issues early (e.g., tasks taking longer over time might indicate a regression or external slowdown).</li><li><strong>Production Hardening:</strong> Finally, treat this setup as a starting point. In a real deployment, you’d consider using a message broker like RabbitMQ if you require guaranteed at-least-once delivery (Redis broker is <em>fast</em> but has at-most-once semantics by design). You’d also secure your Redis (no open access), possibly separate the Redis instances for broker vs result backend if needed (to distribute load), and use a robust process manager for the FastAPI app (Gunicorn with multiple worker processes or Uvicorn workers). Deploy Celery workers on a platform that can auto-restart or auto-scale them (Kubernetes, AWS ECS, etc.), and use health checks. Celery can be scaled horizontally very easily -a Celery system can consist of multiple workers across machines, enabling high throughput and high availability. Embrace that flexibility.</li></ul><p>By implementing these techniques, we achieved a backend that can handle long-running AI tasks gracefully, giving users timely feedback and keeping the system scalable. In practice, this means your AI application can think deeply without keeping users in the dark, and your infrastructure can grow to support more users and more ambitious tasks. Happy coding, and may your agents be ever streaming!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3ac855d0755" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Smart Code Search: Building an AI-Powered Query System with Django & OpenAI]]></title>
            <link>https://akanuragkumar.medium.com/smart-code-search-building-an-ai-powered-query-system-with-django-openai-d1a8b9dc502c?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1a8b9dc502c</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[vector]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[openai]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 09:39:26 GMT</pubDate>
            <atom:updated>2025-02-04T12:34:06.723Z</atom:updated>
            <content:encoded><![CDATA[<h3>Smart Code Search: Building an AI-Powered Code Query System with Django &amp; OpenAI</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jqlPP49PXZdJIEF8m1MOIw.jpeg" /></figure><p><strong><em>Efficient Code Search and Retrieval with AI: A Developer’s Guide</em></strong></p><h3><strong>Introduction</strong></h3><p>As software projects scale, navigating a complex codebase can feel like searching for a needle in a haystack. Developers often spend hours hunting down functions, tracing dependencies, and finding similar snippets. But what if there was a smarter way?</p><p>Imagine asking a question in plain English and receiving an <strong>instant, AI-powered response</strong> tailored to your codebase — no more endless scrolling or sifting through files.</p><p>This project brings that vision to life. By integrating <strong>AI with a Django-based web application</strong>, it allows developers to interact with their code repositories using natural language queries. Instead of manually searching through thousands of lines of code, they can now ask:</p><p>“<em>Where is this function used?</em>”<br>“<em>Show me similar functions in this repository.</em>”</p><p>With this AI-powered code search, development becomes faster, smarter, and more intuitive.</p><h3>Problem with Traditional Code Search</h3><p>Most code search tools rely on <strong>basic keyword matching</strong>, requiring developers to know the exact function names or terms they’re searching for. This rigid approach has significant drawbacks:</p><p>🔍 <strong>Lack of Context Awareness</strong> — Traditional searches treat code as plain text, missing the meaning behind queries.</p><p>🔄 <strong>No Way to Find Similar Code</strong> — Identifying related functions or patterns across a large repository is tedious and error-prone.</p><p>🗣️ <strong>No Natural Language Support</strong> — Developers must structure queries in a rigid syntax instead of asking questions in plain English.</p><p>📂 <strong>Scattered Documentation</strong> — Important docstrings and inline comments often go unnoticed, leading to redundant searches.</p><p><strong>The result?</strong> Hours wasted searching, increased frustration, and a slower development workflow. But what if there was a way to search <strong>intelligently, contextually, and in natural language</strong>?</p><h3><strong>Solution: AI-Powered Code Search</strong></h3><p>The <strong>Smart Code Search </strong>is a <strong>Django-based web application </strong>that enhances code search and understanding using <strong>OpenAI’s GPT models</strong> and <strong>vector-based search techniques</strong>. It enables:</p><p><strong>Code Repository Upload</strong><br>Users can upload their code repositories to the system. The backend parses the code and indexes key components like function names, class structures, and docstrings.</p><p><strong>Natural Language Query Processing</strong><br>Instead of using rigid search queries, users can ask questions in plain English, such as:<br><em>Where is the function </em><strong><em>process_payment</em></strong><em> implemented?</em><br><em>Find all functions related to </em><strong><em>authentication</em></strong><em>.</em><br><em>Which methods are similar to `</em><strong><em>validate_user_input`</em></strong></p><p><strong>AI-Powered Responses</strong><br>Using <strong>OpenAI embeddings</strong> and <strong>semantic search techniques</strong>, the system retrieves relevant code snippets, documentation, and explanations. This hybrid approach combines <strong>vector search</strong> (to find semantically similar content) with <strong>keyword-based search</strong> (using TrigramSimilarity in PostgreSQL).</p><h3>System Architecture</h3><p>1. <strong>Django Backend</strong>: Manages user authentication, chat sessions, and database interactions.<br>2. <strong>PostgreSQL Database</strong>: Stores indexed code snippets, embeddings, and chat history.<br>3. <strong>OpenAI API</strong>: Generates embeddings and provides AI-powered responses.<br>4. <strong>Hybrid Search (Vector + Keyword)</strong>: Combines semantic search with trigram-based keyword matching.<br>5. <strong>Frontend (Django Templates + JavaScript)</strong>: Provides an interactive chat interface for users to ask queries.</p><h3>Technical Implementation</h3><p>The system is designed to ingest, index, search, and retrieve Python code snippets efficiently while providing a chatbot interface to assist users in understanding and exploring code. Let’s break it down into key components:</p><h4>1. Code Ingestion and Indexing</h4><p>To enable efficient code search, we extract functions and classes from Python files and store their metadata in a database.</p><h4>1.1 Extracting Function/Class Names, Code, and Docstrings</h4><p>We use Python’s built-in ast module to parse files and extract:</p><ul><li>Function/Class Names</li><li>Code Body</li><li>Docstrings (Documentation within functions/classes)</li></ul><h4>Example Extraction Logic</h4><pre>import ast<br>def extract_functions_from_file(file_path):<br>    with open(file_path, &quot;r&quot;, encoding=&quot;utf-8&quot;) as f:<br>        content = f.read()<br>    tree = ast.parse(content)<br>    functions = []<br>    for node in ast.walk(tree):<br>        if isinstance(node, (ast.FunctionDef, ast.ClassDef)):<br>            name = node.name<br>            start_line = node.lineno<br>            end_line = node.body[-1].lineno if node.body else start_line<br>            function_code = &quot;\n&quot;.join(content.splitlines()[start_line - 1:end_line])<br>            docstring = ast.get_docstring(node) or &quot;&quot;<br>            functions.append((name, function_code, docstring))<br>    return functions</pre><h4>Why store file path, docstring, chunk id?</h4><ul><li>file_path: Helps retrieve the original file where a function/class is defined.</li><li>docstring: Enables documentation-based search for better code understanding.</li><li>chunk_id: A unique identifier for each function (combines file name + function name).</li></ul><h4>1.2 Storing and Indexing Code with Embeddings</h4><p>Once we extract function details, we store them in a database and generate embeddings using OpenAI’s text-embedding-ada-002 model.</p><h4>Embedding Generation</h4><pre>embedding_response = client.embeddings.create(<br>    input=[code + &quot; &quot; + docstring], <br>    model=&quot;text-embedding-ada-002&quot;<br>)<br>embedding = embedding_response.data[0].embedding</pre><h4>Why embeddings?</h4><p>Traditional keyword-based search fails when looking for semantically similar code. By converting text into vector embeddings, we can perform similarity-based retrieval.</p><h4>Word2Vec for Code Understanding</h4><p>We train a Word2Vec model on function names, docstrings, and code tokens.</p><pre>w2v_model = Word2Vec(tokens, vector_size=100, window=5, min_count=1,<br>workers=4)</pre><h4>Why Word2Vec?</h4><ul><li>Helps in synonym expansion (e.g., search_function vs. lookup_method).</li><li>Enables suggestions for similar function names.</li></ul><h4>2. Query Processing</h4><p>To ensure efficient search and retrieval, we process user queries before searching.</p><h4>2.1 Query Preprocessing (preprocess_query)</h4><pre>import re<br>import spacy<br>nlp = spacy.load(&quot;en_core_web_md&quot;)<br>def preprocess_query(query):<br>    query = query.lower()<br>    query = re.sub(r&quot;[^a-z0-9\s]&quot;, &quot;&quot;, query)  # Remove special characters<br>    doc = nlp(query)<br>    words = {token.lemma_ for token in doc if token.pos_ in {&quot;NOUN&quot;, &quot;VERB&quot;, &quot;PROPN&quot;} and not token.is_stop}<br>    # Synonym Expansion<br>    words.update({syn for word in words if word in SYNONYM_DICT for syn in SYNONYM_DICT[word]})<br>    return &quot; &quot;.join(words)</pre><h4>Why NLP &amp; Lemmatization?</h4><ul><li>Removes stop words (the, is, a etc.).</li><li>Extracts meaningful words (find similar function → find function similar).</li><li>Expands synonyms for better recall.</li></ul><h4>3. Code Search Mechanism</h4><h4>3.1 Vector Similarity Search</h4><p>Once a query is processed, we generate query embeddings and retrieve similar documents.</p><h4>Query Embedding</h4><pre>query_embedding = client.embeddings.create(input=query,<br>model=&quot;text-embedding-ada-002&quot;).data[0].embedding</pre><h4>Vector Search (PostgreSQL with pgvector)</h4><pre>def search_similar_documents(query_embedding, top_k=3):<br>    embedding_array = f&quot;[{&#39;,&#39;.join(map(str, query_embedding))}]&quot;<br>    with connection.cursor() as cursor:<br>        cursor.execute(<br>            &quot;&quot;&quot;<br>            SELECT id, title, content, docstring, file_path, embedding &lt;=&gt; %s::vector AS distance<br>            FROM document<br>            ORDER BY distance ASC<br>            LIMIT %s;<br>            &quot;&quot;&quot;,<br>            [embedding_array, top_k]<br>        )<br>        results = cursor.fetchall()<br>    return results</pre><h4>Why pgvector?</h4><ul><li>Performs fast vector similarity searches.</li><li>Uses cosine similarity (&lt;=&gt;) to find the most relevant results.</li></ul><h4>3.2 Keyword-Based Search (Trigram Similarity)</h4><p>To complement vector search, we use PostgreSQL’s TrigramSimilarity for text matching.</p><pre>from django.contrib.postgres.search import TrigramSimilarity<br><br>keyword_results = Document.objects.annotate(<br>    similarity=TrigramSimilarity(&quot;title&quot;, query) + TrigramSimilarity(&quot;docstring&quot;, query)<br>).filter(similarity__gt=0.3).order_by(&quot;-similarity&quot;)[:3]</pre><h4>Why Trigram Similarity?</h4><ul><li>Helps when query is misspelled (serch function → search function).</li><li>Matches partial words (find meth → find_method).</li></ul><h4>4. Chat Session Management</h4><p>We store chat sessions so users can interact with the system over time.</p><h4>4.1 Rate Limiting and Session Handling</h4><pre>MAX_QUERIES_PER_HOUR = 100<br><br>one_hour_ago = now() - timedelta(hours=1)<br>user_message_count = Message.objects.filter(<br>    chat_session=chat_session, role=&quot;user&quot;, created_at__gte=one_hour_ago<br>).count()<br>if user_message_count &gt;= MAX_QUERIES_PER_HOUR:<br>    return Response({&quot;error&quot;: &quot;Query limit reached. Try again in an hour.&quot;}, status=429)</pre><h4>Why rate limiting?</h4><ul><li>Prevents abuse/spam.</li><li>Ensures API cost control (OpenAI API calls).</li></ul><h4>4.2 Summarizing Older Chats (Using tiktoken)</h4><p>To prevent exceeding OpenAI’s token limits, we summarize old chats.</p><pre>import tiktoken<br>TOKEN_LIMIT = 3000<br><br>encoding = tiktoken.encoding_for_model(&quot;gpt-4o-mini&quot;)<br>total_tokens = sum(len(encoding.encode(msg[&quot;content&quot;])) for msg in chat_history)<br>if total_tokens &gt; TOKEN_LIMIT:<br>    summary_prompt = f&quot;Summarize the chat:\n\n{chat_history}&quot;<br>    summary_response = client.chat.completions.create(<br>        model=&quot;gpt-4o-mini&quot;,<br>        messages=[{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: summary_prompt}],<br>        max_tokens=300<br>    )<br>    summary = summary_response.choices[0].message.content.strip()<br>    Message.objects.create(chat_session=chat_session, role=&quot;system&quot;, content=summary)</pre><h4>Why tiktoken?</h4><ul><li>Calculates exact token count before sending requests.</li><li>Prevents exceeding OpenAI limits (4096 tokens per request).</li></ul><h4>5. AI Chat Completion</h4><p>Finally, after retrieving relevant code snippets, we generate an AI response.</p><pre>completion_response = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    messages=chat_history,<br>    max_tokens=500<br>)<br>answer = completion_response.choices[0].message.content.strip()</pre><h4>Why GPT-based completion?</h4><ul><li>Generates contextual answers based on retrieved code.</li><li>Supports natural language explanations.</li></ul><h4>🚀 <strong>Check out the project on GitHub</strong>: [<a href="https://github.com/akanuragkumar/ai_qa_system">Smart Code Search</a>]</h4><h4>Installation &amp; Setup</h4><p>To set up the project locally:<br><strong>Prerequisites</strong><br>- Docker &amp; Docker Compose<br>- Python 3.9<br>- PostgreSQL with <em>pg_trgm</em> and <em>vector</em> extensions<br>- OpenAI API Key</p><h4>Quick Setup</h4><pre>git clone https://github.com/akanuragkumar/ai_qa_system.git<br>cd ai_qa_system<br>docker-compose up - build</pre><h4>Ingest Codebase for Searching</h4><pre>docker-compose run web python manage.py ingest_code</pre><h4>Run the Development Server</h4><pre>docker-compose run web python manage.py runserver</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*uhvh34fzr8YIHy-skSuQxg.png" /><figcaption>Chat window</figcaption></figure><h3>Future Roadmap 🚀</h3><p>The current version provides powerful AI-driven code search, but there’s always room for improvement. Here’s what’s planned next:</p><p><strong>Enhanced Code Understanding</strong><br>- Improve docstring extraction and indexing to provide richer explanations.<br>- Integrate static code analysis tools like <em>pyflakes</em> or <em>pylint</em> for deeper insights.</p><p><strong>Better Query Understanding</strong><br>- Expand synonym dictionaries with <strong>domain-specific terms</strong>.<br>- Implement <strong>multi-turn conversations</strong> for better follow-up queries.</p><p><strong>Improved Search &amp; Ranking</strong><br>- Use <strong>Reinforcement Learning (RLHF)</strong> to fine-tune search relevance.<br>- Optimize indexing for <strong>real-time code updates</strong>.</p><p><strong>Advanced Features</strong><br>- Implement <em>code generation and refactoring suggestions</em>.<br>- Add <em>multi-language support</em> for Java, JavaScript, and more.</p><h3>Conclusion</h3><p>The <strong>Smart Code Search </strong>bridges the gap between traditional code search and AI-powered understanding. By leveraging <em>natural language processing, embeddings, and hybrid search techniques</em>, it provides an intuitive way for developers to interact with their codebase. This project lays the foundation for smarter, AI-driven software development tools, reducing time spent searching for code and increasing productivity.</p><p>Let me know your thoughts! What features would you like to see next? 💡</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1a8b9dc502c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a scalable cron job with AWS EventBridge+StepFunction+Lambda function]]></title>
            <link>https://awstip.com/writing-a-scalable-cron-job-with-aws-eventbridge-stepfunction-lambda-function-61632ac39f25?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/61632ac39f25</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[aws-eventbridge]]></category>
            <category><![CDATA[aws-step-functions]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Mon, 27 Feb 2023 14:21:41 GMT</pubDate>
            <atom:updated>2023-03-02T19:01:38.546Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/410/1*UNpZvYz6IOP597PRB3dUDA.png" /><figcaption>EventBridge — StepFunction — Lambda Function</figcaption></figure><p>In this article, I would write steps in detail on how to deploy your script directly to lambda and invoke it by using EventBridge and StepFunction</p><p>I had to build a cron service which would be initiated periodically at a fixed interval of time and also during a few hours of the day it would lie dormant. Thus deploying this service in a serverless and on-demand made sense. One awesome thing about serverless is how we can glue services together in creative ways to solve the same problem differentlyFor this, we had chosen AWS Lambda. AWS Lambda is a serverless compute service that allows us to run code without provisioning or managing servers. The Lambda function had multiple functions nested inside and each task had a separate “KEY” for getting invoked which would be passed in Lambda events.</p><p>The next in this architecture was designing how to invoke the Lambda function. For cases where we had invocation greater than a minute we directly used AWS EventBridge. AWS EventBridge is a serverless event bus service that allows us to schedule events based on a cron expression. It also passes a constant JSON as events toLambda function so that it would know which nested function should be triggered now.</p><p>The last part of the step was going down for under-minute invocations. For this, we used AWS step function for second-level precision. AWS Step Functions is a fully managed workflow service that allows us to coordinate multiple AWS services as a series of steps in a state machine. For example, if I have to run a cron service every 15 seconds, then we would initiate the AWS step-function through AWS EventBridge every minute and then the step-function would actually have a state machine built to support every 15-second invocation. It would trigger the lambda function, go for a wait state for 15 seconds, and then again would trigger and continue this cycle for a minute till it ends.</p><p><strong>Amazon States Language (ASL) definition for the above example.</strong></p><pre>{<br>  &quot;Comment&quot;: &quot;A description of my state machine&quot;,<br>  &quot;StartAt&quot;: &quot;Pass State&quot;,<br>  &quot;States&quot;: {<br>    &quot;Pass State&quot;: {<br>      &quot;Type&quot;: &quot;Pass&quot;,<br>      &quot;Next&quot;: &quot;Map&quot;,<br>      &quot;Result&quot;: {<br>        &quot;value&quot;: 4<br>      }<br>    },<br>    &quot;Map&quot;: {<br>      &quot;Type&quot;: &quot;Map&quot;,<br>      &quot;ItemProcessor&quot;: {<br>        &quot;ProcessorConfig&quot;: {<br>          &quot;Mode&quot;: &quot;INLINE&quot;<br>        },<br>        &quot;StartAt&quot;: &quot;Wait&quot;,<br>        &quot;States&quot;: {<br>          &quot;Wait&quot;: {<br>            &quot;Type&quot;: &quot;Wait&quot;,<br>            &quot;Seconds&quot;: 15,<br>            &quot;Next&quot;: &quot;Lambda&quot;<br>          },<br>          &quot;Lambda&quot;: {<br>            &quot;Type&quot;: &quot;Task&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>            &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>            &quot;Parameters&quot;: {<br>              &quot;Payload.$&quot;: &quot;$&quot;,<br>              &quot;FunctionName&quot;: &quot;arn:aws:lambda:ap-south-1:861673107443:function:cwsyn-lead-api-6a0a642f-2ce8-4db6-a841-c7ae3b3a16a4:$LATEST&quot;<br>            },<br>            &quot;Retry&quot;: [<br>              {<br>                &quot;ErrorEquals&quot;: [<br>                  &quot;Lambda.ServiceException&quot;,<br>                  &quot;Lambda.AWSLambdaException&quot;,<br>                  &quot;Lambda.SdkClientException&quot;,<br>                  &quot;Lambda.TooManyRequestsException&quot;<br>                ],<br>                &quot;IntervalSeconds&quot;: 2,<br>                &quot;MaxAttempts&quot;: 6,<br>                &quot;BackoffRate&quot;: 2<br>              }<br>            ],<br>            &quot;End&quot;: true<br>          }<br>        }<br>      },<br>      &quot;End&quot;: true,<br>      &quot;InputPath&quot;: &quot;$.MyStateInput.value&quot;<br>    }<br>  }<br>}</pre><p>I’m using a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-pass-state.html">Pass</a> state to initialise an array containing 4 numbers. The numbers themselves aren’t actually important, I’m just using them to make the <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-map-state.html">Map</a> state loop 4times.</p><blockquote><strong><em>Importantly</em></strong><em>, I’ve set </em><em>MaxConcurrency to </em><em>1 on the Map state, otherwise, it would run multiple threads and invoke the Lambda function in parallel.</em></blockquote><p>The Map state iterator waits 15 seconds using a <a href="https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-wait-state.html">Wait</a> state, then invokes the interval Lambda function asynchronously (it <strong>doesn’t</strong> wait for it to complete before moving on to the next loop).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/146/1*e99odxz5QMiWe_CAjcvXZQ.png" /><figcaption>State Diagram for the above example</figcaption></figure><p>We can use AWS CloudWatch Logs and CloudWatch Metrics, to help us monitor, log and troubleshoot Lambda-function. AWS EventBridge, Step Functions, and Lambda are powerful AWS services that can be used together to build scalable and reliable cron jobs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61632ac39f25" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/writing-a-scalable-cron-job-with-aws-eventbridge-stepfunction-lambda-function-61632ac39f25">Writing a scalable cron job with AWS EventBridge+StepFunction+Lambda function</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Pagination in python with offset and limit]]></title>
            <link>https://akanuragkumar.medium.com/custom-pagination-in-python-with-offset-and-limit-b8dc6b13f13b?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8dc6b13f13b</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[django-rest-framework]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Sun, 13 Nov 2022 16:10:21 GMT</pubDate>
            <atom:updated>2022-11-13T18:05:18.164Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*D9K_aEWo9MDx7osLKT1Cxw.jpeg" /><figcaption>Offset Pagination</figcaption></figure><p>Recently I was stuck with optimising pagination which we use in our REST APIs. Before this, we used to use python’s Rest Framework — <em>PageNumberPagination. </em>This<em> </em>pagination takes page number and limit and then queries whole query set instead of just querying for that particular page. This drastically affects the performance of the API specially when the scale of data is very high.</p><p>The other alternative which I considered was — <a href="https://www.django-rest-framework.org/api-guide/pagination/#limitoffsetpagination">LimitOffsetPagination</a> of Rest Framework. This also worked fine for the use case but it lagged taking page number and limit and then setting the whole context for the function. Thus, I thought of making our own custom pagination which will not only fulfil my purpose but also would be generic enough so that it was be used project wide with other contexts as well. Also, while doing it I had few things in mind- things which we always do while returning a paginated response in an API —</p><ol><li>Getting data by page number rather than offset.</li><li>Having freedom of sorting data by any order.</li><li>Accepting any model object and query.</li><li>Accepting serializer and serializer context for returning serialized data directly.</li><li>If serializer is not passed then have an mechanism in place that would serialize the data for the given model object.</li></ol><p>Considering all the above points, I could come up with the below <strong>Implementation of pagination</strong></p><pre>class CustomPaginationOffset:<br>    &quot;&quot;&quot;<br>    Custom pagination class which can be used when we get page number<br>    and ideally don&#39;t want to query the whole data, here we get offset<br>    queryset and count of whole data.<br><br>    It expects current page number, model serializer, model in which<br>    query has to be made, query itself in form of dict and order_by<br>    which the result would be sorted.<br><br>    It returns the count of whole model data and serialized data.<br>    &quot;&quot;&quot;<br><br>    page_number = 1<br>    page_size = 20<br>    order_by = &#39;-created&#39;<br><br>    def get_offset(self):<br>        &quot;&quot;&quot;It returns limit when it gets page number according to page size.&quot;&quot;&quot;<br>        upper_limit = self.page_number * self.page_size<br>        lower_limit = upper_limit - self.page_size<br>        return lower_limit, upper_limit<br><br>    def get_serialized_data(self, model, queryset, serializer=None, context=None):  # noqa<br>        &quot;&quot;&quot;It returns serialized data if serializer is present, else creates a<br>         serializer from the model given.&quot;&quot;&quot;<br>        if serializer:<br>            serialized_data = serializer(queryset, context=context, many=True).data<br>        else:<br><br>            class Serializer(serializers.ModelSerializer):<br><br>                class Meta:<br>                    fields = &#39;__all__&#39;<br><br>            Serializer.Meta.model = model<br>            serialized_data = Serializer(queryset, many=True).data<br>        return serialized_data<br><br>    def __call__(self, model: object, query: dict, serializer=None, context=None):<br>        &quot;&quot;&quot;<br>        Returns paginated data.<br>        @param model:<br>        @param serializer:<br>        @param query:<br>        @param context:<br>        @return: {&quot;results&quot;: serialized data, &quot;count&quot;: total_objects_count,<br>                  &quot;total_pages&quot;: total_pages, &quot;is_next_page&quot;: True/False}<br>        &quot;&quot;&quot;<br>        lower_limit, upper_limit = self.get_offset()<br><br>        queryset = model.objects.filter(**query).order_by(<br>            self.order_by)[lower_limit: upper_limit]<br>        total_objects_count = model.objects.filter(**query).count()<br>        serialized_data = self.get_serialized_data(model, queryset, serializer, context)<br><br>        total_pages = math.ceil(float(total_objects_count/self.page_size))<br>        is_next_page = True if total_pages &gt; self.page_number else False<br><br>        return {&quot;results&quot;: serialized_data, &quot;count&quot;: total_objects_count,<br>                &quot;total_pages&quot;: total_pages, &quot;is_next_page&quot;: is_next_page}</pre><p>This returns list of serialized data, total count of objects according to the given query set, total pages and a boolean field — is_next_page.</p><p><strong>Usage</strong></p><pre>query = {&#39;created__date__range&#39;: [start_date, end_date]}<br>context = {&#39;user_profile_uuids&#39;: user_profile_uuids}<br><br>paginator = CustomPaginationOffset()<br>paginator.page_number = self.page<br># I am not setting paginator.page_size here and using the default<br>response = paginator(User, query,<br>                     UserSerializer, context)<br># And if we do not have a serializer in place then we can directly do -<br># response = paginator(User, query, None, context)</pre><p>This was a very naive approach to the pagination problem which I was facing. I tried making the code as modular as possible and include few useful and redundant things which might make my overall lines of code come down in my project. I would not be shy in updating this in future if I get suggestions about improvements and adding new functionalities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8dc6b13f13b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Database setup for Django-Test]]></title>
            <link>https://akanuragkumar.medium.com/multi-database-setup-for-django-test-54b125d18210?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/54b125d18210</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Fri, 23 Sep 2022 03:53:23 GMT</pubDate>
            <atom:updated>2022-09-23T03:53:23.139Z</atom:updated>
            <content:encoded><![CDATA[<p>Set up multi-database for the python-Django test without using any patch</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*CrkIi4bJY8aGRUEJs5GOlQ.png" /><figcaption>Multi-Database setup in Django test</figcaption></figure><p>I have been writing tests for the past 3 years, but I recently came across an interesting case. We have a micro-service written in Python-Django which uses multiple databases. The default database is for writing operations and is native to it, the other database which is a read replica of another micro-service native database.</p><p>The Django settings file is defined as follows:</p><pre>DATABASES = {<br>    &#39;default&#39;: {<br>        &#39;ENGINE&#39;: ENGINE,<br>        &#39;NAME&#39;: NAME,<br>        &#39;USER&#39;: USER,<br>        &#39;PASSWORD&#39;: PASSWORD,<br>        &#39;HOST&#39;: HOST,<br>        &#39;PORT&#39;: PORT,<br>    },<br>    &#39;other-database&#39;: {<br>        &#39;ENGINE&#39;: ENGINE,<br>        &#39;NAME&#39;: NAME,<br>        &#39;USER&#39;: USER,<br>        &#39;PASSWORD&#39;: PASSWORD,<br>        &#39;HOST&#39;: HOST,<br>        &#39;PORT&#39;: PORT,<br>    }<br><br>}</pre><p>The read-only models have been defined in this way:</p><pre># models.py<br><br>from django.db import models<br><br><br>class Notmanaged(models.Model):<br>    foo = models.TextField()<br><br>    class Meta:<br>        # This model is not managed by Django<br>        managed = False<br>        db_table = &#39;notmanaged_table&#39;</pre><p>For querying from a non-default database using Django ORM, I use the following where DB-name is the name defined in Django settings -</p><pre>Notmanaged.objects.using(other-database).filter(foo=bar)</pre><p>Now coming back to testing, the database scenario was as follows:</p><ol><li>Default DB would be used for writing and reading native data.</li><li>For validation and data points of another micro-service, another database would be used which is ready only and has <em>managed=False</em> while defining meta for the model class.</li></ol><p>Thus in Django set up I would have to create mock Database entries for both the databases, But inherently Django does not support it as when your test database would be created, tables would not be created for where you would have defined <em>managed=False</em> in model class meta as table schema has not been created.</p><p>We inherit the class <a href="https://docs.djangoproject.com/en/4.1/topics/testing/tools/#testcase">TestCase</a> for writing our test cases. For creating table <a href="https://docs.djangoproject.com/en/dev/ref/schema-editor/">schema</a>, applying it while test-DB creation and then destroying it after the test is over, we will have to override TestCase <a href="https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.TestCase"><em>setUp</em></a> and <em>tearDown.</em></p><pre># tests.py<br><br>from django.db import connection<br>from django.test import TestCase<br><br>from app.models import Notmanaged<br><br><br>class ModelsTestCase(TestCase):<br>    def setUp(self):<br>        super().setUp()<br><br>        with connection.schema_editor() as schema_editor:<br>            schema_editor.create_model(Notmanaged)<br><br>            if (<br>                Notmanaged._meta.db_table<br>                not in connection.introspection.table_names()<br>            ):<br>                raise ValueError(<br>                    &quot;Table `{table_name}` is missing in test database.&quot;.format(<br>                        table_name=Notmanaged._meta.db_table<br>                    )<br>                )<br><br>    def tearDown(self):<br>        super().tearDown()<br><br>        with connection.schema_editor() as schema_editor:<br>            schema_editor.delete_model(Notmanaged)<br><br>    def test_notmanaged_model(self):<br>        with self.assertNumQueries(num=3):<br>            self.assertEqual(0, Unmanaged.objects.all().count())<br>            Unmanaged.objects.create()<br>            self.assertEqual(1, Unmanaged.objects.all().count())</pre><p>Also, there can be a scenario where you have to create multiple schemas, there we can create a constant list and can define all table names in it. And in the loop, we can create schemas.</p><pre>TestCase.databases = {&#39;default&#39;, &#39;other-database&#39;}<br><br>def setUp(self) -&gt; None:<br>    # Create Config and Auth setup<br>    super().setUp()<br><br>    for table in view_tables:<br><br>        with connection.schema_editor() as schema_editor:<br>            schema_editor.create_model(table)<br><br>            if (<br>                    table._meta.db_table<br>                    not in connection.introspection.table_names()<br>            ):<br>                raise ValueError(<br>                    &quot;Table `{table_name}` is missing in test database.&quot;.format(<br>                        table_name=table._meta.db_table<br>                    )<br>                )</pre><pre>def tearDown(self):<br>    super().tearDown()<br><br>    for table in view_tables:<br>        with connection.schema_editor() as schema_editor:<br>            schema_editor.delete_model(table)</pre><blockquote>The process here is way cleaner than hacks with test runner, settings and migration files.</blockquote><h3>Conclusion</h3><p>This might not be the best or most elegant way to handle the scenario but still is a better way than mocking or using migration files. Also, there is another way to implement this which I came across while reading about the implementation, not convinced though that which is more elegant-<a href="https://www.caktusgroup.com/blog/2010/09/24/simplifying-the-testing-of-unmanaged-database-models-in-django/">https://www.caktusgroup.com/blog/2010/09/24/simplifying-the-testing-of-unmanaged-database-models-in-django/</a></p><p>Read the doc. This article for example can bring some clarifications and a summary so that you can better understand the issue, but it does not replace the doc and neither do other articles on the net. Here are the 2 links to the doc of <a href="https://docs.python.org/3.5/library/unittest.html">unittest</a> and <a href="https://docs.djangoproject.com/en/1.10/topics/testing/tools/">Django testing tools</a>.</p><p>I will end this article with a quote from one of the best engineers that I’ve had the chance to work with ;)</p><p>You can not spare yourself from understanding what you do.</p><p>References:</p><p>Schema- <a href="https://docs.djangoproject.com/en/dev/ref/schema-editor/">https://docs.djangoproject.com/en/dev/ref/schema-editor/</a></p><p>SetUp- <a href="https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.TestCase">https://docs.djangoproject.com/en/dev/topics/testing/tools/#django.test.TestCase</a></p><p>TestCase — <a href="https://docs.djangoproject.com/en/4.1/topics/testing/tools/#testcase">https://docs.djangoproject.com/en/4.1/topics/testing/tools/#testcase</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=54b125d18210" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quickstart Guide for Python Eve: Setting up]]></title>
            <link>https://akanuragkumar.medium.com/quickstart-guide-for-python-eve-setting-up-a205d47171ca?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a205d47171ca</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[eve]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 10:59:21 GMT</pubDate>
            <atom:updated>2021-06-16T10:59:21.350Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/345/0*SqcieMmkSEm62IXB.png" /><figcaption>Python REST API framework designed for human beings</figcaption></figure><p>Python REST API framework designed for human beings</p><h3>Problems I faced</h3><p>I have known about Python eve framework for quite some time now. But recently I thought of using it in my project because of its usefulness. And then I hit a roadblock of less documentation and took me a good amount of time to master it. So, this article is an empathetic effort, empathy for those who may have to travel the same boat for some time and do not have to suffer the same pain as I did.</p><h3>Setting-up</h3><p>To install the eve package, the command(assuming you have pip already installed) is</p><blockquote><em>pip install eve</em></blockquote><h3>A Minimal Application</h3><p>We will start with a top-to-bottom approach to show you the simplicity of Eve. In a file “run.py”, you have 3 lines of code that you need to run.</p><pre>from eve import Eveapp = Eve()if __name__ == &#39;__main__&#39;:<br>    app.run()</pre><p>Next we have to create a new text file at the same place where run.py exists and name it as settings.py. It contains the following:</p><pre>DOMAIN = <strong>{</strong>&#39;users&#39;<strong>:</strong> <strong>{}}</strong></pre><p>This is the Eve configuration file, a standard Python module, and it is telling Eve that your API is comprised of just one accessible resource, user.</p><p>Now we are ready to launch our API.</p><pre>$ python run.py<br> * Running on <a href="http://127.0.0.1:5000/">http://127.0.0.1:5000/</a></pre><p>Now, let us understand what has happened. So, we have created a Read-only API from Eve as this is by default and without any schema definition.</p><h3>Database Inclusion</h3><p>We add the database connection by adding the following lines to settings.py:</p><pre><em># Let&#39;s just use the local mongod instance. Edit as needed.# Please note that MONGO_HOST and MONGO_PORT could very well be left</em><br><em># out as they already default to a bare bones local &#39;mongod&#39; instance.</em><br>MONGO_HOST = &#39;localhost&#39;<br>MONGO_PORT = 27017<em># Skip this block if your db has no auth. But it really should.</em><br>MONGO_USERNAME = &#39;&lt;your username&gt;&#39;<br>MONGO_PASSWORD = &#39;&lt;your password&gt;&#39;<br><em># Name of the database on which the user can be authenticated,</em><br><em># needed if --auth mode is enabled.</em><br>MONGO_AUTH_SOURCE = &#39;&lt;dbname&gt;&#39;. MONGO_DBNAME = &#39;users_ms&#39;</pre><p>These things are enough to start using in Mongo due to mongo’s laziness as in POST request a new database and new collection will be created with entry if nothing exists but the performance issue will be persistent as it will be without optimization and indexes due to auto-managed databases.</p><h3>Real-life Application</h3><p>We create a new directory named schema and a text file as user_schema.py inside it and store the collection schema here. For multiple collections we can define different schema files and later import it to settings file of eve.</p><pre>users_schema = {<br>    &#39;user_name&#39;: {<br>        &#39;type&#39;: &#39;string&#39;,<br>        &#39;minlength&#39;: 1,<br>        &#39;maxlength&#39;: 50,<br>        &#39;required&#39;: True,<br>        # talk about hard constraints! For the purpose of the demo<br>        # &#39;lastname&#39; is an API entry-point, so we need it to be        unique.<br>        &#39;unique&#39;: True,<br>    },<br>    &#39;user_education&#39;: {<br>        &#39;type&#39;: &#39;integer&#39;,<br>        &#39;minlength&#39;: 1,<br>        &#39;maxlength&#39;: 4,<br>        &#39;required&#39;: True,<br>        # talk about hard constraints! For the purpose of the demo<br>    },<br>    # An embedded &#39;strongly-typed&#39; dictionary.<br>    &#39;question_json&#39;: {<br>        &#39;schema&#39;<strong>:</strong> <strong>{</strong><br>            &#39;question&#39;<strong>:</strong> <strong>{</strong>&#39;type&#39;<strong>:</strong> &#39;string&#39;<strong>},</strong><br>            &#39;answer&#39;<strong>:</strong> <strong>{</strong>&#39;type&#39;<strong>:</strong> &#39;string&#39;<strong>}</strong><br>        <strong>},</strong>&#39;required&#39;: True,<br>    },<em># &#39;role&#39; is a list, and can only contain values from &#39;allowed&#39;.</em><br>    &#39;role&#39;<strong>:</strong> <strong>{</strong><br>        &#39;type&#39;<strong>:</strong> &#39;list&#39;<strong>,</strong><br>        &#39;allowed&#39;<strong>:</strong> <strong>[</strong>&quot;author&quot;<strong>,</strong> &quot;contributor&quot;<strong>,</strong> &quot;copy&quot;<strong>],</strong><br>    <strong>}</strong><br>}</pre><p>Now, we come back to settings.py file and make further customization there for the above changes.</p><pre>users = {<br>    &#39;item_title&#39;: &#39;users&#39;,<br><em># Enable GET, POST, DELETE for resources/collections.              </em><br><em># (if we omit this line, the API will default to [&#39;GET&#39;] and provide</em><br><em># read-only access to the endpoint).</em><br>    &#39;resource_methods&#39;: [&#39;GET&#39;, &#39;POST&#39;],<br><em># Enable GET, PATCH, PUT and deletes #of individual items</em>&#39;item_methods&#39;: [&#39;GET&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;],    &#39;schema&#39;: users_schema<br>}<br>DOMAIN = {<br>    &#39;users&#39;: users,<br>}</pre><p>Finally, our settings.py file will look like this:</p><pre><em>from schema import users_schema<br># Let&#39;s just use the local mongod instance. Edit as needed.# Please note that MONGO_HOST and MONGO_PORT could very well be left</em><br><em># out as they already default to a bare bones local &#39;mongod&#39; instance.</em><br>MONGO_HOST = &#39;localhost&#39;<br>MONGO_PORT = 27017<em># Skip this block if your db has no auth. But it really should.</em><br>MONGO_USERNAME = &#39;&lt;your username&gt;&#39;<br>MONGO_PASSWORD = &#39;&lt;your password&gt;&#39;<br><em># Name of the database on which the user can be authenticated,</em><br><em># needed if --auth mode is enabled.</em><br>MONGO_AUTH_SOURCE = &#39;&lt;dbname&gt;&#39;. MONGO_DBNAME = &#39;users_ms&#39;users = {<br>    &#39;item_title&#39;: &#39;users&#39;,<br><em># Enable GET, POST, DELETE for resources/collections.              </em><br><em># (if we omit this line, the API will default to [&#39;GET&#39;] and provide</em><br><em># read-only access to the endpoint).</em><br>    &#39;resource_methods&#39;: [&#39;GET&#39;, &#39;POST&#39;],<br><em># Enable GET, PATCH, PUT and deletes #of individual items</em>&#39;item_methods&#39;: [&#39;GET&#39;, &#39;PATCH&#39;, &#39;DELETE&#39;],    &#39;schema&#39;: users_schema<br>}<br>DOMAIN = {<br>    &#39;users&#39;: users,<br>}</pre><p>Save settings.py and launch run.py. We can now insert documents at the users endpoint:</p><pre>$ curl -d &#39;[{&quot;user_name&quot;:&quot;Sagar Malik&quot;,&quot;user_education&quot;:12,&quot;question_json&quot;:{&quot;Question&quot;:&quot;What is photosynthesis&quot;,&quot;answer&quot;:&quot;It is the process by which plants make food&quot;},&quot;role&quot;:&quot;author&quot;},{&quot;user_name&quot;:&quot;Vartul Mittal&quot;,&quot;user_education&quot;:12,&quot;question_json&quot;:{&quot;Question&quot;:&quot;What is photosynthesis&quot;,&quot;answer&quot;:&quot;It is the process by which plants make food&quot;},&quot;role&quot;:&quot;author&quot;}]&#39; -H &#39;Content-Type: application/json&#39;  <a href="http://127.0.0.1:5000/users">http://127.0.0.1:5000/users</a><br>HTTP/1.0 201 OK</pre><p>We will get a similar response in the form of a list as we had sent POST request also in form of a list:</p><pre>{<br>    &quot;_status&quot;: &quot;OK&quot;,<br>    &quot;_items&quot;: [<br>        {<br>            &quot;_updated&quot;: &quot;Fri, 05 Jun 2020 02:30:56 GMT&quot;,<br>            &quot;_created&quot;: &quot;Fri, 05 Jun 2020 02:30:56 GMT&quot;,<br>            &quot;_etag&quot;: &quot;fbd77aca5e59b9a0751c6f549f890692aa0d10c3&quot;,<br>            &quot;_id&quot;: &quot;5ed9ae60dbdf8c083f0ca30f&quot;,<br>            &quot;_links&quot;: {<br>                &quot;self&quot;: {<br>                    &quot;title&quot;: &quot;users&quot;,<br>                    &quot;href&quot;: &quot;users/5ed9ae60dbdf8c083f0ca30f&quot;<br>                }<br>            },<br>            &quot;_status&quot;: &quot;OK&quot;<br>        },<br>        {<br>            &quot;_updated&quot;: &quot;Fri, 05 Jun 2020 02:30:56 GMT&quot;,<br>            &quot;_created&quot;: &quot;Fri, 05 Jun 2020 02:30:56 GMT&quot;,<br>            &quot;_etag&quot;: &quot;364e0a5574f29e7fab9a84b293c0ffc1d02c2587&quot;,<br>            &quot;_id&quot;: &quot;5ed9ae60dbdf8c083f0ca310&quot;,<br>            &quot;_links&quot;: {<br>                &quot;self&quot;: {<br>                    &quot;title&quot;: &quot;users&quot;,<br>                    &quot;href&quot;: &quot;users/5ed9ae60dbdf8c083f0ca310&quot;<br>                }<br>            },<br>            &quot;_status&quot;: &quot;OK&quot;<br>        }<br>    ]<br>}</pre><blockquote><em>Now, we can have read (GET) from the href that is created inside _links. Also, pagination of results are automated in eve and we can directly access it by /collection_name?max_results=(_)&amp;page=(_) and 25 results per page is generated by default if left empty.</em></blockquote><p>Thus now we set up a simple RESTFUL API(but fairly complex if Eve would not have been there). Eve comes in with default support for MongoDB but we can use other SQL and NoSQL databases. To read more about the superpowers and what can be achieved by Eve <a href="http://docs.python-eve.org/en/latest/features.html">here</a>.</p><p>Thanks for reading the article and I hope it would have solved your doubts and aversions about Python Eve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a205d47171ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Flask REST App with Flask-Restful+Auth+MongoDB]]></title>
            <link>https://akanuragkumar.medium.com/building-flask-rest-app-with-flask-restful-auth-mongodb-d7ffb67ea470?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7ffb67ea470</guid>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flask]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 10:57:57 GMT</pubDate>
            <atom:updated>2021-06-16T10:57:57.464Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*inrDS48NQbZE9xR_.jpeg" /></figure><p>Create a complete web API with Python, Flask, JWT, and MongoDB using sustainable coding practices.</p><p>Before we start: This guide is aimed towards beginners / intermediate level. So, a bit of python knowledge and object-oriented programming fundamentals are required. Creating an API with a database backend is a great programming project, but it can be tough to get started since there are so many concepts to work with. This guide is meant to help you build your first API using Python Flask-Restful, Auth, and MongoDB, from start to finish. Hopefully, this guide will help take the edge off.</p><h3>What Is This App about?</h3><p>Here is a small <strong>product</strong> requirements document for the app- Doubt-Bag:</p><h3>Doubt-Bag</h3><p>This app provides a platform for users to ask doubts, tag those questions to multiple topics and in turn, other users can comment on that question for further clarification and if they think they know the solution, they can answer the question. Further, if someone has doubts regarding the solution, people can post a comment for that solution. Lastly, if people are satisfied or dissatisfied with the solution, They can upvote or downvote the solution. The author of the question if he/she finds the answer satisfactory they can accept the answer.</p><p><strong>API Requirements:</strong></p><ul><li>Signup for new users, Login for current users.</li><li>Forgot password and reset password implementation.</li><li>In all the features, for editing/deleting content, We must check if the author is the one who posted or not.</li><li>View all questions- Public view.</li><li>Post question with tagged topics and question heading- Login required.</li><li>View specific questions that will contain the question heading, question body, Tagged topics, comments on those questions, and solutions with votes- Login required.</li><li>The question can be only deleted which has <strong>no solution.</strong></li><li>Post comment to any question- Login required.</li><li>If the question is deleted then comment must also be <strong>deleted</strong>.</li><li>Post answers to any question- Login required</li><li>Delete answer- Login required</li><li>Users can upvote or downvote an answer- Login required</li><li>If the author of the question finds the answer satisfactory, <strong>they only can accept</strong> the answer.</li><li>Post comment to any answer- Login required.</li><li>If any answer is deleted then comment must also be <strong>deleted</strong>.</li></ul><p>Ok, let’s get started!</p><p>Grab the GitHub Doubt-Bag code:</p><pre>git clone <a href="https://github.com/akanuragkumar/Doubt-Bag">https://github.com/akanuragkumar/Doubt-Bag.git</a></pre><p><strong>Project Structure:</strong></p><pre>Doubt-Bag/                        <br>├── databases<br>│   ├── db.py<br>│   └── models.py<br>├── resources<br>│   ├── answer.py<br>│   ├── auth.py<br>│   ├── comment.py<br>│   ├── comment_answer.py<br>│   ├── errors.py<br>│   ├── question.py<br>│   ├── reset_password.py<br>│   ├── routes.py<br>│   └── votes.py<br>├── tests<br>│   ├── __init__.py<br>│   ├── Basecase.py<br>│   ├── test_create_question.py<br>│   ├── test_get_questions.py<br>│   ├── test_login.py<br>│   └── test_signup.py<br>├── templates/email<br>│   ├── reset_password.html<br>│   └── reset+password.txt<br>│   <br>├── services<br>│   └── mail_service.py<br>├── .env<br>├── .env.test<br>├── app.py<br>├── requirements.txt<br>└── run.py</pre><h3>Quickstart</h3><p>To work in a sandboxed Python environment it is recommended to install the app in a Python <a href="https://pypi.python.org/pypi/virtualenv">virtualenv</a>.</p><ol><li>Install dependencies</li></ol><pre>$ cd /path/to/Doubt-Bag<br>$ pip install -r requirements.txt</pre><p>2. .env FILE contains environment variable for MongoDB, JWT, and mail- server. Export this file to use this an environment variable for our app.</p><pre>$ export ENV_FILE_LOCATION=./.env</pre><h3>3. Run the app</h3><p>Start SMTP server in the terminal with:</p><pre>$ python -m smtpd -n -c DebuggingServer localhost:1025</pre><p>This will create an SMTP server for testing our email feature.</p><p>Then open another terminal and run:</p><pre>$ python run.py</pre><p>View app at http://127.0.0.1:5000/&lt;endpoints&gt;</p><h3>4. Run the Test-cases</h3><h3>Test Isolation</h3><p>Test isolation is one of the most important concepts in testing. Usually, when we are writing tests, we test one business logic. The idea of test isolation is that one of your tests should not in any way affect another test.</p><p>Suppose that you have created a user in one test and you are testing login on another test. To follow test isolation you cannot depend on the user-created in a user creation test, but should create the user right in the test where you are going to test login. Why? Because your login test might run before your user creation test this makes your test fail.</p><p>Also, if we do not delete our user which we created on the previous test run, and we try to run the test again, our test fails because the user is already there.<br>So, we should always test a feature from an empty state and for that easiest way is to delete all the collections in our database.</p><p>Before running our first test make sure to export the environment variable ENV_FILE_LOCATION with the location to the test env file.</p><pre>$ export ENV_FILE_LOCATION=./.env.test# for running single unit test case<br>$ python -m unittest tests/test_signup.py<br># running all unit test cases together<br>$ python -m unittest --buffer</pre><h3>Tech-stack used for Doubt bag:</h3><ul><li><a href="https://palletsprojects.com/p/flask/">Flask</a> — For our web server.</li><li><a href="https://flask-restful.readthedocs.io/en/latest/installation.html">flask-restful</a> — For building cool Rest-APIs.</li><li><a href="https://pypi.python.org/pypi/virtualenv">virtualenv</a> For managing python virtual environments.</li><li><a href="http://docs.mongoengine.org/projects/flask-mongoengine/en/latest/">mongoengine</a> — For managing our database.</li><li><a href="https://flask-marshmallow.readthedocs.io/en/latest/">flask-marshmallow</a> — For serializing user requests.</li><li><a href="https://www.getpostman.com/downloads/">Postman</a> — For testing our APIs</li><li><a href="https://flask-bcrypt.readthedocs.io/en/latest/">Flask-Bcrypt</a> For hashing user password.</li><li><a href="https://flask-jwt-extended.readthedocs.io/en/stable/">Flask-JWT-Extended</a> For creating tokens for authorization and authentication.</li></ul><h3>Exception Handling to make flask application more resilient to errors</h3><ul><li>Handle exceptions in our flask application using exception chaining.</li><li>Send the error message and status code based on the exception that occurred.</li></ul><h3>Reset Password</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*myOCrH91blGJvYqg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/0*DQiTNfEBmrH4aqqE.png" /></figure><p>Password reset flow diagram</p><ol><li>/forget: This endpoint takes the email of the user whose account needs to be changed. This endpoint then sends the email to the user with the link which contains reset token to reset the password.</li></ol><p>In the ForgotPassword resource, we first get the user based on the email provided by the client. We are then using create_access_token() to create a token-based on user.id and this token expires in 24 hours. We are then sending the email to the client. The email contains both HTML and text format information.</p><p>2. /reset: This endpoint takes reset_token sent in the email and the new password.</p><p>In ResetPassword resource, we first get the user based on user id from the reset_token and then reset the password of the user based on the password provided by the user. Finally, a reset success email is sent to the user.</p><h3>Need for run.py</h3><p>If we initialize run in app.py and run our app we will encounter:</p><pre>ImportError: cannot import name &#39;initialize_routes&#39; from &#39;resources.routes&#39;</pre><p>This is because of the circular dependency problem in python. In our reset_password.py, we import send_mail which is importing app from app.py whereas app is not yet defined on our app.py.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/60/0*Oo4DlYyiQvWsj17-" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/0*fBr5I_DP1oY_vjXE.png" /></figure><p>Circular dependency</p><p>To solve this issue we create another file run.py in our root directory, which will be responsible for running our app. Also, we need to initialize our routes/view functions after we have initialized our app.</p><h3>Database Schema:</h3><pre>class Question(db.Document):<br>    heading = db.StringField(required=True, unique=True)<br>    topics = db.ListField(db.StringField(), required=True)<br>    question_body = db.StringField(required=True)<br>    added_by = db.ReferenceField(&#39;User&#39;)<br></pre><pre>class Comments(db.Document):<br>    comment = db.StringField(required=True)<br>    question = db.ReferenceField(&#39;Question&#39;, reverse_delete_rule=CASCADE)<br>    added_by = db.ReferenceField(&#39;User&#39;)<br></pre><pre>class Answers(db.Document):<br>    answer = db.StringField(required=True)<br>    vote = db.IntField()<br>    is_accepted = db.BooleanField(default=False)<br>    question = db.ReferenceField(&#39;Question&#39;)<br>    added_by = db.ReferenceField(&#39;User&#39;)<br></pre><pre>class AnswerComments(db.Document):<br>    comment = db.StringField(required=True)<br>    answer = db.ReferenceField(&#39;Answers&#39;, reverse_delete_rule=CASCADE)<br>    added_by = db.ReferenceField(&#39;User&#39;)<br></pre><pre>class User(db.Document):<br>    email = db.EmailField(required=True, unique=True)<br>    password = db.StringField(required=True, min_length=6)<br>    questions = db.ListField(db.ReferenceField(&#39;Question&#39;, reverse_delete_rule=db.PULL))<br>    comments = db.ListField(db.ReferenceField(&#39;Comments&#39;, reverse_delete_rule=db.PULL))<br>    answers = db.ListField(db.ReferenceField(&#39;Answers&#39;, reverse_delete_rule=db.PULL))<br>    answers_comment = db.ListField(db.ReferenceField(&#39;AnswerComments&#39;, reverse_delete_rule=db.PULL))</pre><pre>    def hash_password(self):<br>        self.password = generate_password_hash(self.password).decode(&#39;utf8&#39;)</pre><pre>    def check_password(self, password):<br>        return check_password_hash(self.password, password)<br></pre><pre>User.register_delete_rule(Question, &#39;added_by&#39;, db.CASCADE)<br>User.register_delete_rule(Comments, &#39;added_by&#39;, db.CASCADE)<br>User.register_delete_rule(Answers, &#39;added_by&#39;, db.CASCADE)<br>User.register_delete_rule(AnswerComments, &#39;added_by&#39;, db.CASCADE)</pre><p>We have created a one-many relationship between <em>user</em> and <em>question, comments, answers, answer_comment</em>. That means a user can have one or more <em>questions</em> and a <em>question</em> can only be created by one user. Here reverse_delete_rule in the question field of User represents that a question should be pulled from the user document if the question is deleted.<br>Similarly, User.register_delete_rule(Question, &#39;added_by&#39;, db.CASCADE) creates another delete rule which means if a user is deleted then the question created by the user is also deleted.</p><p>Also, I have made <strong>reverse delete rule — cascade </strong>for references from parent to child table like if the question is deleted then comments associated with it would also be deleted.</p><h3>API end-points:</h3><h3>Auth</h3><ol><li>POST /api/auth/signup</li></ol><pre>application/json - [{&quot;email&quot;: &quot;akanuragkumar712@gmail.com&quot;,&quot;password&quot;: &quot;itssocool&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;You successfully signed up!&quot;,&quot;id&quot;: &lt;object_id&gt;}</pre><p>2. POST /api/auth/login</p><pre>application/json - [{&quot;email&quot;: &quot;akanuragkumar712@gmail.com&quot;,&quot;password&quot;: &quot;itssocool&quot;}]</pre><p>response</p><pre>{&quot;token&quot;: &lt;token&gt;}</pre><p>3. POST /api/auth/forget</p><pre>application/json - [{&quot;email&quot;: &quot;akanuragkumar712@gmail.com&quot;]</pre><p>response</p><pre>a mail will be send with reset password token</pre><p>4. POST /api/auth/reset</p><pre>application/json - [{&quot;reset_token&quot;: &lt;reset_token&gt;,&quot;password&quot;: &quot;thisisalsocool&quot;]</pre><p>response</p><pre>new password is set for the account and now the user has to login again.</pre><p>To use authorization header in Postman follow the steps:<br>1) Go to the Authorization tab.<br>2) Select the Bearer Token form TYPE dropdown.<br>3) Paste the token you got earlier from /login<br>4) Finally, send the request.</p><h3>Question</h3><ol><li>POST /api/question</li></ol><pre>application/json - [{&quot;topics&quot;: [&quot;general&quot;,&quot;metal ability&quot;,&quot;awareness&quot;],&quot;question_body&quot;: &quot;what is Doubt-bag 3?&quot;,&quot;heading&quot;: &quot;what is Doubt-bag 3?&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your question has been posted&quot;,&quot;id&quot;: &lt;object_id&gt;}</pre><p>2. GET /api/question/&lt;id&gt;</p><p>response</p><pre>{&quot;question&quot;: [{&quot;_id&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;heading&quot;: &quot;what is Doubt-bag?&quot;, &quot;topics&quot;: [&quot;general&quot;, &quot;metal ability&quot;, &quot;awareness&quot;], &quot;question_body&quot;: &quot;what is Doubt-bag?&quot;, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}}], &quot;comments&quot;: [{&quot;_id&quot;: {&quot;$oid&quot;: &lt;object_id&gt;&quot;}, &quot;comment&quot;: &quot;This is a very good question&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}}, {&quot;_id&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;comment&quot;: &quot;This is a very good question-1(duplicate)&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}}], &quot;answers&quot;: [{&quot;_id&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;answer&quot;: &quot;This is a store house of all doubts people can have ranging to different topic.&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}}, {&quot;_id&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;answer&quot;: &quot;This is a store house of all doubts people can have ranging to different topic.(duplicate)&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}}]}</pre><p>3. PUT /api/question/&lt;id&gt;</p><pre>application/json - [{&quot;topics&quot;: [&quot;science&quot;,&quot;metal ability&quot;,&quot;awareness&quot;],&quot;question_body&quot;: &quot;what is Doubt-bag 3?&quot;,&quot;heading&quot;: &quot;what is Doubt-bag 3?&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your question has been updated&quot;}</pre><p>4. DELETE /api/question/&lt;id&gt;</p><p>response</p><pre>{&quot;Success&quot;: &quot;Your question has been deleted&quot;}</pre><h3>Comments</h3><ol><li>POST /api/comments?question_id=&lt;id&gt;</li></ol><pre>application/json - [{&quot;comment&quot; : &quot;This is a very good question-1(duplicate)&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been posted&quot;,&quot;id&quot;: &lt;object_id&gt;}</pre><p>2. GET /api/comment/&lt;id&gt;</p><p>response</p><pre>[{&quot;comment&quot; : &quot;This is a very good question-1(duplicate)&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}]</pre><p>3. PUT /api/comments/&lt;id&gt;</p><pre>application/json - [{&quot;comment&quot; : &quot;This is a very good question-1&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been updated&quot;}</pre><p>4. DELETE /api/comments/&lt;id&gt;</p><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been deleted&quot;}</pre><h3>Answers</h3><ol><li>POST /api/answers?question_id=&lt;id&gt;</li></ol><pre>application/json - [{&quot;answer&quot; : &quot;This is a very good question-1(duplicate)&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your answer has been posted&quot;,&quot;id&quot;: &lt;object_id&gt;}</pre><p>2. GET /api/answers/&lt;id&gt;</p><p>response</p><pre>[{&quot;answer&quot; : &quot;This is a very good question-1(duplicate)&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;},{&quot;answer_comment&quot; : &quot;This is a very good question-1&quot;,&quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}]</pre><p>3. PUT /api/answers/&lt;id&gt;</p><pre>application/json - [{&quot;answer&quot; : &quot;This is a very good question-1&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your answer has been updated&quot;}</pre><p>4. DELETE /api/answer/&lt;id&gt;</p><p>response</p><pre>{&quot;Success&quot;: &quot;Your answer has been deleted&quot;}</pre><h3>Answer_comment</h3><ol><li>POST /api/answer_comment?answer_id=&lt;id&gt;</li></ol><pre>application/json - [{&quot;answer_comment&quot; : &quot;This is a very good question-1(duplicate)&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been posted&quot;,&quot;id&quot;: &lt;object_id&gt;}</pre><p>2. GET /api/answer_comment/&lt;id&gt;</p><p>response</p><pre>[{&quot;comment&quot; : &quot;This is a very good question-1(duplicate)&quot;, &quot;question&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}, &quot;added_by&quot;: {&quot;$oid&quot;: &lt;object_id&gt;}]</pre><p>3. PUT /api/answer_comment/&lt;id&gt;</p><pre>application/json - [{&quot;answer_comment&quot; : &quot;This is a very good question-1&quot;}]</pre><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been updated&quot;}</pre><p>4. DELETE /api/answer_comment/&lt;id&gt;</p><p>response</p><pre>{&quot;Success&quot;: &quot;Your comment has been deleted&quot;}</pre><h3>Vote and Accept of Answer</h3><ol><li>PUT /api/upvote?answer_id=&lt;id&gt;</li></ol><p>response</p><pre>{&#39;Success&#39;: &#39;Answer is upvoted&#39;}</pre><p>2. PUT /api/downvote?answer_id=&lt;id&gt;</p><p>response</p><pre>{&#39;Success&#39;: &#39;Answer is downvoted&#39;}</pre><p>3. PUT /api/accepted?answer_id=&lt;id&gt;</p><p>response</p><pre>{&#39;Success&#39;: &#39;Answer is accepted&#39;}</pre><h3>Improvements:</h3><p>There are lots of scopes where you can try to improve/add the features. Here are a few of them.</p><ul><li>Only 1 upvote/downvote is allowed per user. Here you will have to store users in Answer collection who have voted the answer and while voting this validation should be there.</li><li>Store all topics in a separate collection and validate the topics during post request of questions. Also, get requests on topics should be enabled.</li><li>The search for questions via question body or tagged topics.</li><li>Store versions of questions and answers.</li><li>Handling exceptions and all edge cases for failure points in API.</li><li>Adding unit test cases for both happy as well as unhappy path.</li></ul><h3>Conclusion:</h3><p>In this project, we built what was asked from us in the product requirements document. The topics which we have covered are:</p><ul><li>How to create Document schema using Mongoengine.</li><li>How to perform CRUD operation using Mongoengine.</li><li>How to create REST APIs using Flask-restful</li><li>Python spread operator, which spreads the dictionary. i.e: Question(**body)</li><li>How to hash user password using flask-bcrypt</li><li>How to create JSON token using flask-jwt-extended</li><li>How to protect API endpoints from unauthorized access.</li><li>How to implement authorization so that only the user who added the content can delete/update the content.</li><li>How to handle exceptions in our flask application using exception chaining and send the error message and status code based on the exception occurred.</li><li>How to create a token for resetting user password</li><li>How to send email to the user using Flask-mail</li><li>How to reset the user password</li><li>How to avoid circular dependency in Flask.</li><li>What test isolation is and why we should isolate our tests cases</li><li>How to test Flask REST APIs with unittest</li></ul><p>Hopefully, you can now set up your own custom REST APIs using Flask-Restful, Auth, and MongoDB. Thanks for going through this article, don’t forget to leave a few claps if you like it 😉.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7ffb67ea470" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching result of a method in Python]]></title>
            <link>https://akanuragkumar.medium.com/caching-result-of-a-method-in-python-c8ead9cd48de?source=rss-854db477af7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8ead9cd48de</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[flask]]></category>
            <category><![CDATA[python3]]></category>
            <dc:creator><![CDATA[Anurag Kumar]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 10:24:47 GMT</pubDate>
            <atom:updated>2021-06-16T10:24:47.309Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*dG-YMg7MozPdfV-z.jpeg" /></figure><p>Recently I was working on adding a new feature to an existing legacy code. But then while working on it, I found a sweet problem which was quite new for me.</p><pre>def get_obj():<br>        model_obj = model()         # Some large database query<br>        return model_obj</pre><pre>    def get_obj_value(self):<br>        obj = self.get_obj()<br>        return obj</pre><pre>    def get_obj_value_dup(self):<br>        obj = self.get_obj()<br>        return obj</pre><p>As we can see I have a method get_obj() which does some database query and returns that. This method was already there and I just had to use it in my separate methods, but soon I realized that this method get_obj() was being used in multiple places and it was always making database query which is computationally very costly. Thus the idea of caching the return value of the method came to my mind.</p><p>Currently, in the above code snippet, we can see that the return value of the method is computed always. To reduce that I used a <em>custom memoize decorator</em> which would cache the result of a method with a single <strong>self</strong> argument as property and its result will persist as long as the instance does.</p><pre>def memoize(function):<br>    memo = {}</pre><pre>    def wrapper(*args):<br>        if args in memo:<br>            return memo[args]<br>        else:<br>            rv = function(*args)<br>            memo[args] = rv<br>            return rv</pre><pre>    return wrapper</pre><pre>@memoize<br>def get_obj():<br>    model_obj = model()<br>    return model_obj</pre><pre>def get_obj_value(self):<br>    obj = self.get_obj()<br>    return objdef get_obj_value_dup(self):<br>    obj = self.get_obj()<br>    return obj</pre><p>Here we can see that memorize stores its cached result in the memo dictionary. Now if we go inside the wrapper function, <em>if args in memo</em>-&gt; here is checks that if the cached results already exist then return that without going inside the main function, <em>else</em>-&gt; go inside the function, compute and then store the result and return the existing result.</p><p>Alternatively, another <a href="https://code.activestate.com/recipes/496879/">memoization decorator</a> with a limit on the cache size can be implemented when you do not want your memory to be full if a single instance is caching quite big enough.</p><p>Also, we can use the python Funtool library’s cached_property .</p><pre>from functools import cached_property</pre><pre>@cached_property<br>def get_obj():<br>    model_obj = model()<br>    return model_obj</pre><p>Thus, we could see how the caching result of a method helped me in this case. But this power should be used wisely and not followed blindly everywhere.</p><blockquote><em>There are only two hard things in Computer Science: cache invalidation and naming things. — Phil Karlton</em></blockquote><p>Sometimes we need to work a little with a model instance and where we need to change the object and send it to the response. Django provides the <a href="https://docs.djangoproject.com/en/1.8/ref/models/instances/#refreshing-objects-from-database">refresh_from_db()</a> method to reload an object from the database. Refreshing the object from the database all model fields and relationships are cleaned out and non-deferred fields are reloaded, but the cached method is not a model field and the value is still stored in self.__dict__.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8ead9cd48de" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>