<?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 No Place Like Localhost on Medium]]></title>
        <description><![CDATA[Stories by No Place Like Localhost on Medium]]></description>
        <link>https://medium.com/@noplacelikelocalhost?source=rss-910edd5892a1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by No Place Like Localhost on Medium</title>
            <link>https://medium.com/@noplacelikelocalhost?source=rss-910edd5892a1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:31:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@noplacelikelocalhost/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[Optimizing Your Application for High Traffic: A Guide to Stress Testing Sending Millions of…]]></title>
            <link>https://noplacelikelocalhost.medium.com/optimizing-your-application-for-high-traffic-a-guide-to-stress-testing-sending-millions-of-f08fc0dbb89e?source=rss-910edd5892a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f08fc0dbb89e</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[No Place Like Localhost]]></dc:creator>
            <pubDate>Mon, 04 Mar 2024 21:35:49 GMT</pubDate>
            <atom:updated>2024-03-04T21:35:49.661Z</atom:updated>
            <content:encoded><![CDATA[<h3>Optimizing Your Application for High Traffic: A Guide to Stress Testing and Sending Millions of Requests</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4BpdI7ghuas3slz0ygdIw.jpeg" /></figure><h3>TLDR;</h3><blockquote><strong>Purpose</strong>: Stress testing is essential to determine how your application performs under extreme conditions, ensuring it remains reliable and scalable during high traffic periods.</blockquote><blockquote><strong>Tools</strong>: Utilize Python’s asyncio and aiohttp libraries to simulate real-world stress on your application by sending a massive number of asynchronous POST requests. Use of semaphores prevents system overload, ensuring the stress test is rigorous yet safe</blockquote><blockquote><strong>Execution</strong>: The stress test is conducted by varying the number of requests to simulate different stress levels, providing insights into the application’s performance and resilience under pressure.</blockquote><blockquote><strong>Outcome</strong>: By methodically increasing the load and analyzing the application’s response, you can identify performance bottlenecks and areas for optimization, ensuring your application can handle real-world demands efficiently.</blockquote><blockquote>This guide equips you with a structured approach to push your application to its limits, revealing its true capacity and helping you enhance its performance and reliability.</blockquote><h3><strong>Introduction</strong></h3><p>In today’s fast-paced digital environment, it’s crucial to understand how your application performs under pressure. Can it handle hundreds, thousands, or even millions of requests without breaking a sweat? This knowledge is key to ensuring your application is reliable, scalable, and keeps users happy.</p><p>We’ll explore how to set up a service that simulates intense demand on your system using Python’s asyncio and aiohttp libraries. Our aim is to push your application to its limits, identify potential weak points, and ensure it can handle real-world pressures without a hitch.</p><h3>Sending requests</h3><p>This function is designed with the modern web’s asynchronous nature in mind. By leveraging Python’s async and await keywords, fetch allows our testing framework to wait for a response without blocking the execution of other tasks. This is particularly beneficial when sending out thousands, if not millions, of requests, as it ensures that our system remains responsive, efficiently managing resources without overwhelming the network or the server.</p><pre>async def fetch(url, session, data):<br>   async with session.post(url, json=data) as response:<br>       if response.status != 200:<br>           raise ClientResponseError(<br>               request_info=response.request_info,<br>               history=response.history,<br>               status=response.status,<br>               message=f&quot;API returned status code: {response.status}&quot;,<br>           )<br>       return await response.text()</pre><p>Upon invoking fetch, it initiates an asynchronous POST request to the specified url, carrying the data payload. This payload is crucial, as it can be tailored to test various aspects of your application, from how it handles typical user-generated content to more edge-case scenarios that might trigger unexpected behavior.</p><p>The response handling within fetch is equally important. Should the response indicate a successful interaction (a 200 status code), the function captures and returns the response text, potentially containing data or confirmation crucial for further analysis. However, if the encounter is less than ideal, signified by any status code other than 200, fetch raises a ClientResponseError. This error not only signals a hiccup in the request but also encapsulates detailed information about the request and its journey, offering insights into what went awry.</p><h3><strong>Regulating Request Flow with Semaphores</strong></h3><p>A critical aspect of conducting effective stress tests is ensuring that while we aim to push our systems to their limits, we don’t cross the line into causing actual damage or crashes. This is where the concept of semaphores comes into play, serving as a gatekeeper to regulate the flow of concurrent requests our system attempts to handle at any given moment. The bound_fetch function embodies this principle, meticulously orchestrating the execution of our asynchronous requests with the assistance of a semaphore.</p><pre>async def bound_fetch(sem, url, session, data):<br>   async with sem:<br>       try:<br>           await fetch(url, session, data)<br>       except ClientResponseError as e:<br>           print(f&quot;Error making request: {e}&quot;)</pre><p>At its core, bound_fetch is designed to work in tandem with the previously discussed fetch function, acting as a wrapper that adds an extra layer of control. The semaphore (sem) passed to bound_fetch is a sophisticated synchronization tool provided by the asyncio library, which limits the number of coroutines that can access a particular resource or execute a certain operation concurrently.</p><p>Here’s how it works in the context of our stress testing:</p><ul><li><strong>Concurrency Control</strong>: Upon invoking bound_fetch, it first awaits its turn to proceed, as dictated by the semaphore. The semaphore ensures that only a fixed number of bound_fetch instances can execute fetch concurrently. This limit is crucial to prevent overwhelming both the client (the machine running the stress test) and the server (the application being tested).</li><li><strong>Error Handling</strong>: Inside the semaphore’s context, bound_fetch attempts to perform the actual POST request using the fetch function. If fetch encounters an issue, such as receiving a non-200 status code from the server, it raises a ClientResponseError. bound_fetch catches this exception and logs the error, providing visibility into the issues encountered during the testing process without halting the execution of other requests.</li></ul><p>By incorporating bound_fetch into our stress testing framework, we gain a dual advantage. First, it allows us to simulate high traffic realistically and responsibly, adhering to our system’s and the application’s capacity constraints. Second, it offers a structured approach to error management, enabling us to collect and analyze error data systematically, which is invaluable for identifying and addressing potential weaknesses in our application.</p><p>In essence, bound_fetch acts not just as a mechanism for sending requests but as a guardian, ensuring that our quest to test the limits of our application respects the boundaries of safety and stability. This careful balance between aggression and restraint is what ultimately enables us to conduct thorough, effective stress tests that yield actionable insights, empowering us to enhance the resilience and performance of our applications.</p><h3><strong>Orchestrating the Stress Test</strong></h3><p>With the foundational blocks in place, courtesy of our fetch and bound_fetch functions, we arrive at the crux of our stress testing operation — the main function. This function is the conductor of our testing symphony, harmonizing the asynchronous execution of requests to stress test our application. Let’s dissect how it accomplishes this monumental task:</p><pre>async def main(num_queries, semaphore_nb, url, data):<br>   tasks = []<br>   async with aiohttp.ClientSession() as session:<br>       sem = asyncio.Semaphore(semaphore_nb)<br>       for _ in range(num_queries):<br>           task = asyncio.create_task(bound_fetch(sem, url, session, data))<br>           tasks.append(task)<br>       await asyncio.gather(*tasks)</pre><p>The main function is straightforward in its structure but profound in its impact. Here’s a step-by-step breakdown of its workflow:</p><ul><li><strong>Setting the Stage</strong>: Upon invocation, main receives several crucial parameters:</li><li>num_queries: The total number of requests to send during the stress test. This figure can range from a modest few to several millions, depending on the test’s scope and the system’s capacity.</li><li>semaphore_nb: The maximum number of concurrent requests allowed. This number is pivotal in preventing system overload and ensuring a controlled test environment.</li><li>url: The endpoint URL to which the stress test requests will be directed.</li><li>data: The payload to accompany each POST request, which can be tailored to probe different aspects of the application’s functionality.</li><li><strong>Session Initiation</strong>: A ClientSession from aiohttp is instantiated, serving as the gateway for all outgoing requests. This session is context-managed to ensure proper resource management, automatically handling connection establishment and closure.</li><li><strong>Semaphore Employment</strong>: A semaphore is created with the specified concurrency limit (semaphore_nb). This semaphore will play a crucial role in regulating the flow of request execution, maintaining a balance that prevents overburdening the system.</li><li><strong>Task Creation</strong>: For each query in num_queries, a bound_fetch coroutine is scheduled as a task. These tasks are designed to execute bound_fetch asynchronously, adhering to the semaphore’s concurrency rules. Each task represents an individual stress test request, collectively contributing to the overall load imposed on the application.</li><li><strong>Concurrent Execution</strong>: With all tasks scheduled, asyncio.gather is employed to execute them concurrently. This function awaits the completion of all tasks, effectively marshaling the collective force of our stress test requests. It’s this simultaneous execution that truly simulates the high-traffic conditions we aim to test against.</li></ul><p>The beauty of the main function lies in its orchestration of complex asynchronous operations in a concise and readable manner. By leveraging Python’s asynchronous programming features, it enables us to simulate real-world loads on our application, providing insights into performance under stress, capacity limits, and potential points of failure.</p><p>In conclusion, the main function isn’t just the culmination of our stress testing script — it’s the engine that drives our exploration into the resilience and scalability of our applications. Through this function, we unlock the ability to subject our applications to the rigorous demands of the real world, ensuring they are not only functional but formidable in the face of adversity.</p><h3><strong>Initiating the Test Run</strong></h3><p>The final step is to bring our preparation into action. By varying the number of requests, we can simulate different levels of stress, providing a comprehensive view of how the application performs under varying degrees of pressure.</p><pre>if __name__ == &quot;__main__&quot;:<br>   # Load configuration from file or environment variables (replace with your implementation)<br>   url = &quot;https://your-api-endpoint.com&quot;<br>   data = {&quot;key&quot;: &quot;value&quot;}  # Replace with your sample data<br>   semaphore_nb = 1000<br>   list_nb_queries = [1000, 10000, 10**5, 10**6]<br><br><br>   for nb_queries in list_nb_queries:<br>       print(<br>           f&quot;Testing for {nb_queries} queries from {datetime.utcnow()} with semaphore {semaphore_nb}&quot;<br>       )<br>       start_time = time.time()<br>       loop = asyncio.get_event_loop()<br>       loop.run_until_complete(main(nb_queries, semaphore_nb, url, data))<br>       end_time = time.time()<br>       print(f&quot;{nb_queries} queries time: {round(end_time - start_time, 3)}&quot;)</pre><p>In this critical section of our stress testing script, we kickstart the process by defining key parameters, including the endpoint URL, sample data for the payload, the semaphore number to control concurrency, and a list of different quantities of requests to simulate various levels of load on the application.</p><p>For each level of load defined in list_nb_queries, we initiate a test run, marking its commencement with a timestamp and a print statement that logs the start time and the conditions of the test. The heart of this operation lies in the loop.run_until_complete(main(…)) call, where the event loop executes the main function, passing in the number of queries to send, the semaphore number, the endpoint URL, and the data payload.</p><p>This approach allows us to methodically ramp up the pressure on our application, from a modest 1000 requests to a more substantial million requests in this example. By timing each run with time.time(), we gain valuable insights into how the response time of our application scales with the number of requests, providing a clear picture of its performance under varying loads.</p><p>The use of the event loop here is pivotal, as it ensures that our asynchronous tasks are executed in a non-blocking manner, keeping our system responsive and efficient throughout the testing process. It’s this careful orchestration of tasks, coupled with the measured increase in load, that allows us to conduct thorough and effective stress tests, ensuring that our application can withstand the demands of real-world usage without faltering.</p><h3><strong>Conclusion: Unleashing Your Application’s Potential</strong></h3><p>Stress testing is vital for ensuring your application can handle intense demand. By leveraging Python’s asynchronous features and gradually increasing load, you can discover its limitations, pinpoint inefficiencies, and enhance overall performance. It’s about preparing your application to not only meet but surpass user expectations in even the most challenging situations.</p><p>However, generating high loads is only part of the equation. Analyzing the results to make informed optimizations is equally crucial. In an upcoming blog post, I’ll delve into key performance metrics and analysis techniques:</p><ul><li><strong>Response Time</strong>: This metric reveals the time your application takes to respond to requests. Tracking how response times evolve with increased load can highlight when performance starts to falter.</li><li><strong>Throughput</strong>: Understanding the volume of requests your application can manage per time unit is essential. Identifying the peak throughput before performance declines is critical for capacity planning.</li><li><strong>Error Rate</strong>: Monitoring the rate of requests that fail under heavy load is crucial. A rising error rate may signal underlying bottlenecks or stability issues needing attention.</li><li><strong>Resource Utilization</strong>: Keep an eye on CPU, memory, disk I/O, and network usage. Excessive use of these resources can indicate performance constraints and direct optimization efforts.</li><li><strong>Concurrency and Latency</strong>: Analyzing how your application handles simultaneous requests and the latency of these processes can shed light on its scalability and efficiency.</li></ul><p>Stay tuned for a deep dive into these metrics, providing you with the tools to refine and ready your application for high-stress scenarios.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f08fc0dbb89e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Streaming with FastAPI’s StreamingResponse — Part  1]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://noplacelikelocalhost.medium.com/implementing-streaming-with-fastapis-streamingresponse-part-1-edf4c55a4132?source=rss-910edd5892a1------2"><img src="https://cdn-images-1.medium.com/max/2600/1*G4BpdI7ghuas3slz0ygdIw.jpeg" width="3088"></a></p><p class="medium-feed-snippet">Mastering Efficient Data Transfers: Dive into FastAPI&#x2019;s StreamingResponse and Prep for an AI-Integrated Future with ChatGPT!</p><p class="medium-feed-link"><a href="https://noplacelikelocalhost.medium.com/implementing-streaming-with-fastapis-streamingresponse-part-1-edf4c55a4132?source=rss-910edd5892a1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://noplacelikelocalhost.medium.com/implementing-streaming-with-fastapis-streamingresponse-part-1-edf4c55a4132?source=rss-910edd5892a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/edf4c55a4132</guid>
            <category><![CDATA[prgramming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[streaming]]></category>
            <dc:creator><![CDATA[No Place Like Localhost]]></dc:creator>
            <pubDate>Mon, 11 Sep 2023 16:54:51 GMT</pubDate>
            <atom:updated>2023-09-15T13:19:34.318Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Speed Up Python Applications with Essential Caching Techniques]]></title>
            <link>https://noplacelikelocalhost.medium.com/speed-up-python-applications-with-essential-caching-techniques-bf3120e8ad5c?source=rss-910edd5892a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf3120e8ad5c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[No Place Like Localhost]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 20:10:05 GMT</pubDate>
            <atom:updated>2023-08-17T20:10:05.838Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4BpdI7ghuas3slz0ygdIw.jpeg" /></figure><p>Enhancing the speed of your Python applications can drastically improve user experience and efficiency. One pivotal technique to achieve this is caching. In this guide, we will delve deep into Python caching techniques that not only bolster performance but also stand strong in real-world scenarios.</p><h3><strong>Understanding Caching in Python</strong></h3><p>Before diving into the coding part, let’s get a grip on what caching is. Caching is akin to keeping a small notepad at hand for quick notes, instead of referring to a big book each time. It allows the system to store and reuse previously fetched data, avoiding the need to re-fetch or recompute it, thus speeding up processes.</p><p><strong>Implementing Basic Caching in Python</strong></p><p>Let’s start by coding a simple caching mechanism to grasp how it works under the hood.</p><pre>from functools import wraps<br><br>def my_cache(func):<br>   cache = {}<br>   @wraps(func)<br>   def wrapper(*args, **kwargs):<br>         key = (tuple(args), tuple(kwargs.items()))<br><br>       if key not in cache:<br>           cache[key] = func(*args, **kwargs)<br>       return cache[key]<br>   return wrapper<br><br>@my_cache<br>def fibo(n):<br>  ...</pre><p>This my_cache decorator caches the results of functions. However, it lacks a size limit, potentially leading to memory overflow issues. One solution is using an OrderedDict and ensuring the cache doesn&#39;t surpass a certain size.</p><h3><strong>Using Built-in Caching with LRU_cache</strong></h3><p>For a more sophisticated approach without much heavy lifting, Python offers the lru_cache from the functools library.</p><pre>from functools import lru_cache<br><br>@lru_cache(maxsize=128)</pre><p>Always prioritize built-in functions when available — they are optimized and well-tested.</p><p><strong>Potential Downsides of Caching</strong></p><p>Caching, though immensely beneficial in enhancing performance, is not without its set of challenges. Here are some of the common pitfalls and concerns associated with caching:</p><ol><li><strong>Stale Data</strong>: At its core, caching is about storing and reusing previous results. But what if the original data changes after it’s been cached? This can lead to the system using outdated or ‘stale’ data, which might produce incorrect outcomes.</li><li><strong>Consistency in Concurrent Environments</strong>: Ensuring data consistency becomes crucial in multi-threaded or multi-process systems. When multiple processes access and possibly update the cache simultaneously, it can lead to data inconsistencies.</li><li><strong>Memory Overhead</strong>: While caching saves computational power, it consumes memory. If not managed correctly, caches can grow large, consuming a significant portion of available memory, and potentially leading to system slowdowns or crashes.</li></ol><p><strong>Conclusion</strong></p><p>Caching is a potent tool in a developer’s arsenal, especially when working with Python. Whether you’re building a small application or a distributed system, understanding and implementing effective caching can make a significant difference in performance. Keep exploring, and always look for ways to optimize and improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf3120e8ad5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing CRUD Operations with SQLite: A Time-Saving Guide for Developers]]></title>
            <link>https://noplacelikelocalhost.medium.com/testing-crud-operations-with-sqlite-a-time-saving-guide-for-developers-7c74405d63d5?source=rss-910edd5892a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/7c74405d63d5</guid>
            <category><![CDATA[sqlalchemy]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[sqlite]]></category>
            <category><![CDATA[crud]]></category>
            <dc:creator><![CDATA[No Place Like Localhost]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 18:50:07 GMT</pubDate>
            <atom:updated>2023-08-07T18:50:07.354Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G4BpdI7ghuas3slz0ygdIw.jpeg" /></figure><h3>TLDR;</h3><p>If you’re short on time or resources and don’t want to set up a dedicated database instance for testing, there’s an alternative that still allows you to follow best practices. By utilizing SQLite’s in-memory functionality, you can ensure that your application is robust and won’t crash upon its first encounter with a database. In this article, you’ll learn how to harness the power of SQLite to stay agile without sacrificing safety in your development process.</p><h3>Introduction</h3><p>Most applications require a connection to a database to store and manage data. There’s a plethora of options on the market, including well-known SQL family members like PostgreSQL, Oracle, and MySQL. But what if you want to test your solution without the overhead of setting up a specific test environment? The task of maintaining a test database can indeed be tedious and time-consuming.</p><p>Enter SQLite, an in-memory database that can serve as an efficient substitute for testing. As long as you don’t rely on complex database operations unique to your production database (such as PostgreSQL’s arrays), you can test your basic database-handling functions with SQLite. However, bear in mind that this approach may only be suitable for non-critical, simple applications. To achieve complete confidence in your code, there may be no substitute for setting up a test instance using the same database type as your production environment.</p><h3><strong>Creating a Connection to the Database</strong></h3><p>The first step in our journey is to establish a connection to the database using the SQLAlchemy framework. This connection serves as the entry point from which our application will interact with the database. We’ll be using the SQLALCHEMY_DATABASE_URL variable to store the URL to your database.</p><p>Below, we’ll walk through the code needed to set up this connection. This is just the beginning of an application, and you can follow it up by building a FastAPI app, complete with corresponding POST and GET endpoints.</p><pre>from sqlalchemy import create_engine<br>from sqlalchemy.ext.declarative import declarative_base<br>from sqlalchemy.orm import sessionmaker<br><br>SQLALCHEMY_DATABASE_URL = &quot;&quot;  # can be any database<br>engine = create_engine(<br>   SQLALCHEMY_DATABASE_URL, connect_args={&quot;check_same_thread&quot;: False}<br>)<br>SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br><br>Base = declarative_base()</pre><p><strong>Explanation:</strong></p><ul><li><strong>SQLALCHEMY_DATABASE_URL</strong>: This variable holds the URL for your chosen database. Replace &quot;your-database-url-here&quot; with the actual URL.</li><li><strong>create_engine</strong>: This function creates a new SQLAlchemy engine, which provides a source of connectivity to our database.</li><li><strong>SessionLocal</strong>: We&#39;re defining a custom session class, configured with autocommit and autoflush settings, to manage the persistence operations for our objects.</li><li><strong>declarative_base</strong>: This creates a base class for declarative models, providing the foundation for our database schema.</li></ul><h3>Creating Data Models</h3><p>In our application, we need to store user data in the database. To do this, we’ll create a declarative model named User. This class will inherit from Base, which we defined earlier in the main body of our application. The User class will include the following columns:</p><ul><li>id: An integer column serving as the primary key.</li><li>email: A string column to store the user’s email, ensuring that each email in the database is unique.</li><li>is_active: A boolean column to represent whether the user is active, defaulting to True.</li></ul><p>Here’s the code to define our User model:</p><pre>from app import Base<br>from sqlalchemy import Boolean, Column, Integer, String<br><br>class User(Base):<br>   __tablename__ = &quot;user&quot;<br><br>   id = Column(Integer, primary_key=True, index=True)<br>   email = Column(String, unique=True, index=True)<br>   is_active = Column(Boolean, default=True)</pre><p>By defining this model, we have set up a clear structure for storing user data in our database. The declarative style of SQLAlchemy simplifies the process, allowing us to focus on what the data should look like rather than how it’s stored.</p><h3><strong>Schemas</strong></h3><p>Schemas, in the context of our application, are used to define the structure and validation rules for the data we’re working with. They act as a contract between different parts of our application, ensuring that the data adheres to the expected format.</p><p>Here’s how we can define a basic user schema using Pydantic’s BaseModel:</p><pre>from pydantic import BaseModel<br><br>class UserBase(BaseModel):<br>   email: str</pre><p><strong>Why Do We Use Schemas?</strong></p><ol><li><strong>Validation</strong>: Schemas provide automatic validation of incoming and outgoing data. In our example, the UserBase schema ensures that the email field must be of type str. If any data doesn’t meet this requirement, an error will be raised.</li><li><strong>Serialization and Deserialization</strong>: Schemas enable easy conversion between complex data types, like objects, and common data formats, like JSON. This helps in transforming the data when sending or receiving from a client, or when storing in a database.</li><li><strong>Maintaining Consistency</strong>: Utilizing schemas throughout your application ensures that data consistency is maintained across different parts, from the database layer to the user interface.</li></ol><h3><strong>CRUD Operations</strong></h3><p>CRUD operations, standing for Create, Read, Update, and Delete, form the core functions that allow interactions with a database from a higher level of abstraction. These operations are essential in managing data within an application, ensuring smooth interactions with the underlying database.</p><p>In our example, we’ll focus on two specific CRUD functions: inserting new users into the database (Create) and retrieving users from the database based on their ID (Read). Let’s take a closer look at the code for these functions:</p><pre>from models import User<br>from schemas import UserCreate<br>from sqlalchemy.orm import Session<br><br>def get_user(db: Session, user_id: int):<br>   return db.query(User).filter(User.id == user_id).first()<br><br>def create_user(db: Session, user: UserCreate):<br>   db_user = User(email=user.email)<br>   db.add(db_user)<br>   db.commit()<br>   db.refresh(db_user)<br>   return db_user</pre><p><strong>Explanation:</strong></p><ul><li><strong>get_user</strong>: This function retrieves a user from the database by their ID. It takes the database session and user ID as parameters and returns the corresponding user object, or None if the user is not found.</li><li><strong>create_user</strong>: This function inserts a new user into the database. It takes the database session and a UserCreate schema object, which contains the user&#39;s email. The function then creates a new User object, adds it to the database, commits the transaction, and refreshes the object to ensure it reflects any database-triggered changes, like auto-generated IDs.</li></ul><p>These CRUD functions provide a clean and abstract way to interact with the underlying database, allowing the rest of the application to work with data without getting bogged down in the details of database access.</p><h3>Using the In-Memory Database for Testing CRUD Operations</h3><p>We finally arrive at the main subject of this blog post: testing CRUD operations with SQLite. By utilizing SQLite’s in-memory database functionality, we can create a lightweight, flexible testing environment that doesn’t require a separate database setup.</p><p>The approach we’re going to take involves creating a TestSession with an engine in SQLite&#39;s in-memory mode. We&#39;ll use this session as a fixture in our tests, with a scope set to &quot;function&quot;, meaning a new session will be created for each test function. This ensures isolation between tests, preventing potential interference from one test to another.</p><p>Here’s the code snippet to set up the testing database fixture using Pytest:</p><pre>@pytest.fixture<br>def db():<br>   engine = create_engine(<br>       &quot;sqlite:///:memory:&quot;, connect_args={&quot;check_same_thread&quot;: False}<br>   )<br>   TestSession = sessionmaker(autocommit=False, autoflush=False, bind=engine)<br>   Base.metadata.create_all(bind=engine)<br>   return TestSession()</pre><p>With our in-memory SQLite database fixture in place, we can now write tests that operate on this temporary database, allowing us to validate our CRUD operations without touching the production environment.</p><p>Notice how we pass the db argument to every test function. This argument refers to the fixture we created earlier, ensuring that each test receives a fresh database session.</p><p>Here are two examples of test functions that utilize this fixture to test user creation and retrieval:</p><pre>@pytest.mark.parametrize(<br>   &quot;email,password&quot;,<br>   [<br>       (&quot;test@example.com&quot;, &quot;password&quot;),<br>       (&quot;another@example.com&quot;, &quot;12345&quot;),<br>   ],<br>)<br>def test_create_user(db, email, password):<br>   user_create = UserCreate(email=email, password=password)<br>   user = create_user(db, user_create)<br>   assert user.email == email<br>   assert user.hashed_password == f&quot;{password}notreallyhashed&quot;<br><br>@pytest.mark.parametrize(<br>   &quot;email,password&quot;,<br>   [<br>       (&quot;test2@example.com&quot;, &quot;password&quot;),<br>       (&quot;another2@example.com&quot;, &quot;12345&quot;),<br>   ],<br>)<br>def test_get_user(db, email, password):<br>   user_create = UserCreate(email=email, password=password)<br>   created_user = create_user(db, user_create)<br>   retrieved_user = get_user(db, created_user.id)<br>   assert retrieved_user.id == created_user.id</pre><p>These examples illustrate the power and flexibility of using an in-memory SQLite database for testing. By avoiding dependencies on an external database, these tests are more portable and can be executed quickly, enhancing the development workflow.</p><h3>Conclusion</h3><p>If you have the time and resources, setting up a dedicated database for testing or including it in your CI/CD pipeline is a viable approach. However, for those looking to avoid these tasks while still testing their application, the method I’ve shown offers a practical alternative. I often employ this “hack” to test the proof-of-concepts (POCs) of my applications, or in scenarios where I’m confident the app will remain simple for the foreseeable future.</p><p>Should your application’s SQL functions grow in complexity, you can always integrate a database instance into your CI/CD pipeline later. This flexibility allows you to choose the best approach based on your current needs and future expectations.</p><p><strong>Use responsibly.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7c74405d63d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Background Tasks in FastAPI: Enhancing Performance and Responsiveness]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://noplacelikelocalhost.medium.com/leveraging-background-tasks-in-fastapi-enhancing-performance-and-responsiveness-6e4ad64c7d16?source=rss-910edd5892a1------2"><img src="https://cdn-images-1.medium.com/max/2600/1*G4BpdI7ghuas3slz0ygdIw.jpeg" width="3088"></a></p><p class="medium-feed-snippet">Unlocking Performance in FastAPI: A Deep Dive into Managing Long-Running Operations through Background Tasks to Ensure Responsiveness</p><p class="medium-feed-link"><a href="https://noplacelikelocalhost.medium.com/leveraging-background-tasks-in-fastapi-enhancing-performance-and-responsiveness-6e4ad64c7d16?source=rss-910edd5892a1------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://noplacelikelocalhost.medium.com/leveraging-background-tasks-in-fastapi-enhancing-performance-and-responsiveness-6e4ad64c7d16?source=rss-910edd5892a1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e4ad64c7d16</guid>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[No Place Like Localhost]]></dc:creator>
            <pubDate>Sun, 06 Aug 2023 17:56:54 GMT</pubDate>
            <atom:updated>2023-09-08T10:18:22.340Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
        </item>
    </channel>
</rss>