<?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 Ben on Medium]]></title>
        <description><![CDATA[Stories by Ben on Medium]]></description>
        <link>https://medium.com/@bendev1?source=rss-6391218be80c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Ben on Medium</title>
            <link>https://medium.com/@bendev1?source=rss-6391218be80c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 00:44:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bendev1/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[Asynchronously stream response data to disc using Python]]></title>
            <link>https://medium.com/@bendev1/asynchronously-stream-response-data-to-disc-using-python-6f8d5974f355?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f8d5974f355</guid>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[streaming]]></category>
            <category><![CDATA[httpx]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 19:53:10 GMT</pubDate>
            <atom:updated>2023-09-13T19:53:10.403Z</atom:updated>
            <content:encoded><![CDATA[<p>Using the <a href="https://www.python-httpx.org/"><strong>HTTPX</strong></a> and <a href="https://github.com/Tinche/aiofiles"><strong>aiofiles</strong></a> libraries, a request can be made, and the response can be streamed asynchronously to disk using the following snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d63RfZei1zZEJcV6w6RHwg.jpeg" /></figure><p>Install the necessary requirements:</p><pre>pip install aiofiles httpx</pre><p>Then use the following snippet:</p><pre>import aiofiles<br>from httpx import AsyncClient<br><br>async with AsyncClient() as http_client:<br>    async with aiofiles.open(&quot;file.json&quot;, mode=&#39;wb&#39;) as tmp_file:<br>        async with http_client.stream(&#39;GET&#39;, &quot;http://sample_url.com/path&quot;) as response:<br>            response.raise_for_status()<br>            async for chunk in response.aiter_bytes(chunk_size=4096):<br>                await tmp_file.write(chunk)</pre><p>Firstly, create an async client instance. Next, we open a file to write to. Next, use the <em>stream</em> method, and iterate over the response chunks using <em>aiter_bytes</em> method. Finally, write each chunk to a file.</p><p>This solution is memory efficient and can scale well, for example, multiple files could be streamed concurrently like this.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f8d5974f355" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best way to make Async Requests with FastAPI… the HTTPX Request Client & Tenacity!]]></title>
            <link>https://medium.com/@bendev1/how-to-use-httpx-request-client-with-fastapi-16255a9984a4?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/16255a9984a4</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[http-request]]></category>
            <category><![CDATA[httpx]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Fri, 28 Jul 2023 09:54:33 GMT</pubDate>
            <atom:updated>2026-01-17T14:56:12.081Z</atom:updated>
            <content:encoded><![CDATA[<p>It&#39;s very common to need to make requests from your API to other APIs. For years, Python developers heavily favored the <a href="https://requests.readthedocs.io/en/latest/">Requests HTTP library</a>, however, this does not support Asynchronous HTTP requests, therefore potentially leaving out a large performance gain for your API. Enter <a href="https://www.python-httpx.org/">HTTPX</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X20dQzsnk9h_cLG2PdRmIg.png" /></figure><p>HTTPX syntax is super similar to requests, so porting over to HTTPX should be easy. HTTPX is the preferred request library for FastAPI also and is installed when FastAPI is installed.</p><p>HTTPX docs recommend using a Client object to make requests. We will use the AsyncClient, configure it upon app boot using lifespan events, and refer to it during the execution of an endpoint, as follows:</p><pre>import httpx<br>from fastapi import FastAPI, Request<br>from contextlib import asynccontextmanager<br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    app.requests_client = httpx.AsyncClient()<br>    yield<br>    await app.requests_client.aclose()<br><br>app = FastAPI(lifespan=lifespan)<br><br>@app.get(&quot;/dogs&quot;)<br>async def get_red_dogs(request: Request):<br>    requests_client = request.app.requests_client<br>    response = await requests_client.post(&quot;http://localhost:5000&quot;, data={&quot;hello&quot;: &quot;world&quot;})<br>    return response.json()</pre><p>Upon app start, initialize an AsyncClient and assign it to an attribute named <em>requests_client </em>on the app object. <a href="https://fastapi.tiangolo.com/advanced/events/">lifespan events</a> are the current recommended way to execute code once the server starts in FastAPI. We close the client after the yield keyword (on shutdown).</p><p>The requests client can then be found on the request object and async requests can be made using the async/await syntax.</p><p>If the API or resource you are making a query to is flaky, using a retry library such as <a href="https://github.com/jd/tenacity"><em>Tenacity</em></a> is a good idea. See the snippet below…</p><pre>pip install tenacity</pre><pre>from httpx import ConnectTimeout<br>from tenacity import retry, stop_after_attempt, retry_if_exception_type<br><br>@retry(retry=retry_if_exception_type(ConnectTimeout), stop=stop_after_attempt(3))<br>async def send_address_match_request(requests_client, payload):<br>    response = await requests_client.post(<br>        url=f&quot;{os.getenv(&#39;ADDRESS_MATCHING_HOST&#39;)}/v4_0/match&quot;,<br>        data=payload,<br>    )<br>    response.raise_for_status()<br>    resp_data = response.json()<br>    return resp_data </pre><p>The <em>retry </em>decorator will retry the function if an exception is raised. It is highly configurable also, the ability to specify the number and timings of retries is possible, among other options.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16255a9984a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Load testing REST APIs with Python using Locust]]></title>
            <link>https://medium.com/@bendev1/load-testing-rest-apis-with-python-using-locust-b67c6b1a706f?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b67c6b1a706f</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[locust]]></category>
            <category><![CDATA[load-testing]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Mon, 17 Jul 2023 21:16:09 GMT</pubDate>
            <atom:updated>2023-07-17T21:16:09.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOcMpxQKmNGwJfw9piBXiw.png" /></figure><p><a href="https://locust.io/">Locust</a> An open-source load testing tool. It essentially allows you to send x amount of requests to your endpoints and will report back on the performance of your application.</p><p>A Python file (which by convention should be named locustfile.py)can be constructed which allows a range of configuration options for your load tests, such as defining a delay between requests, which endpoints to call, start-up functions, and so on.</p><pre>pip install locust</pre><pre>import os<br><br>from dotenv import load_dotenv<br>from locust import HttpUser, task, between, constant<br><br>load_dotenv()<br>token_string = os.getenv(&#39;TOKEN&#39;)<br><br><br>class QuickstartUser(HttpUser):<br>    wait_time = between(1, 3)<br><br>    def on_start(self):<br>        self.client.post(&quot;/api/v0/Users/login&quot;, json={&quot;email&quot;: &quot;user@testuser.com&quot;, &quot;password&quot;: &quot;password&quot;})<br><br>    @task<br>    def test_find_one(self):<br>        self.client.get(&quot;/api/v0/Properties/findOne&quot;, headers={&quot;authorization&quot;: &quot;Bearer &quot; + token_string})<br><br>    @task<br>    def test_find(self):<br>        params = {<br>            &quot;filter&quot;: &#39;{&quot;limit&quot;: 100}&#39;<br>        }<br>        self.client.get(&quot;/api/v0/Properties&quot;, headers={&quot;authorization&quot;: &quot;Bearer &quot; + token_string}, params=params)</pre><p>You can then launch the program through the command line by simply executing <em>locust</em> in the shell while in the same directory as the locust.py file, which will give you a UI running on localhost, which allows you to define the number of simulated users and the ramp rate, and optionally how long to test for.</p><pre>locust</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CHxQmTlb9BbUKPP_sO2yvA.png" /></figure><p>There are then a range of ways to view results, firstly tabular data like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b6o9kp7BYyyi_qeBvwHQYQ.png" /></figure><p>And Chart data like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9Xzr3E7pigteeucAe7UUw.png" /></figure><p>This data may aid a developer in identifying the capabilities of an application, and allow to developer to identify if more compute resources are needed, or changes to the application code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b67c6b1a706f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Sentry Application Performance Monitor into FastAPI Python Web Framework]]></title>
            <link>https://medium.com/@bendev1/integrating-sentry-application-performance-monitor-into-fastapi-python-web-framework-5f7a463fdf03?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f7a463fdf03</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[sentry]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[api-development]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Wed, 12 Jul 2023 23:10:15 GMT</pubDate>
            <atom:updated>2023-07-12T23:11:08.976Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://sentry.io/">Sentry</a> is an excellent third-party service to track errors and monitor performance. Sentry also includes a free tier, which I find provides enough features for my use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GkR-GZKkJDR3s51fsDEU-w.png" /></figure><p>It’s extremely easy to get up and running. You essentially import the SDK, and initialize sentry using the <em>init </em>function, passing in the DSN (a web address supplied by sentry), and this will offload telemetry data to the cloud, for viewing in the web UI.</p><pre>pip install &#39;sentry-sdk[fastapi]&#39;</pre><pre>from fastapi import FastAPI<br><br>import sentry_sdk<br><br><br>sentry_sdk.init(<br>    dsn=&quot;https://examplePublicKey@o0.ingest.sentry.io/0&quot;,<br>    traces_sample_rate=1.0,<br>)<br><br>app = FastAPI()</pre><p>I integrate sentry into all new APIs I build to make, primarily to make use of use of the following features:</p><p><strong>Error Tracking</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*skRvG0gJdsJdWtFGmKhGZA.png" /><figcaption>Issue Reporting in Sentry</figcaption></figure><p>Exceptions are automatically identified by Sentry, and a ticket is created in the Web UI, which details exactly what went wrong and will have a printout of the code where the exception occurred, along with a stack trace, and a bunch of other supporting info. Notifications and alerts can also be configured upon an exception occurring. You can also filter and sort different issues, for example, I like to filter just for 5xx status code errors.</p><p><strong>Performance stats</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2V5_tEKwNmMKI39JNtYdzQ.png" /><figcaption>Performance Stats in Sentry</figcaption></figure><p>Sentry is able to provide data on how often each and every endpoint is being invocated, as well as the response durations.</p><p><strong>Profiling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d9gsg_z0tGGRGCPi4aeZMA.png" /><figcaption>Profiling in Sentry</figcaption></figure><p>If profiling is enabled, the sentry will create flame charts for profiled requests which allow you to identify how much time is spent in each function or method in your application, allowing you to eliminate bottlenecks and improve application performance.</p><p>Note: Running FastAPI on AWS Lambda (such as with <a href="https://mangum.io/">Mangum</a>) requires a slight adjustment to installation and initialization, as seen below:</p><pre>pip install &#39;sentry-sdk&#39;</pre><pre>from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration<br>from sentry_sdk.integrations.fastapi import FastApiIntegration<br><br>sentry_sdk.init(<br>    dsn=&quot;enter_dsn_here&quot;,<br>    integrations=[AwsLambdaIntegration(), FastApiIntegration()],<br>    traces_sample_rate=1.0,<br>)</pre><p>Also, profiling your code will slow response times down, consider reducing sample rates in production environments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f7a463fdf03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Software Development Setup as a Python Engineer]]></title>
            <link>https://medium.com/@bendev1/my-preferred-software-development-setup-as-a-python-software-engineer-e158d3b48596?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/e158d3b48596</guid>
            <category><![CDATA[ide]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computers]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[tools]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Tue, 11 Jul 2023 21:49:41 GMT</pubDate>
            <atom:updated>2023-07-26T13:07:21.982Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve used a range of different computers and software over the years, here is my shortlist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hc0sx3dfb46wY0FQ8jt7JA.jpeg" /></figure><p><strong>Hardware &amp; OS</strong></p><p>Regarding a development machine, I prefer<strong> laptops over desktops</strong> due to a couple of reasons. Portability<strong>. </strong>As a software engineer, there&#39;s a good chance you’ll work from more than one location, so being to bring your own development machine is a huge bonus. Battery — having a battery is great in case the power goes down… you’ll be protected!</p><p><strong>RAM. </strong>16GB minimum is essential. By the time you’ve got a few browser tabs open, an IDE, Microsoft Teams, and whatever else you’ll, without doubt, be over 8GB at minimum, just don’t risk it!</p><p><strong>Processor. </strong>It’s no secret Apple’s new M1 &amp; M2 chips are blazing-fast and would be my recommendation of choice.</p><p>With this all said, for the vast majority of software engineering tasks (except perhaps if you’re working a great deal with computationally expensive fields such as ML) I’d recommend either a<strong> M1 Macbook Pro base model (budget choice) or a 2022 M2 Macbook Pro base model.</strong> If you’ve got a larger budget, upgrades could be added, but for general web development, I would consider it unnecessary.</p><p>For a mouse, I love the <strong>Logitech MX Master 2</strong> mouse for its ergonomic design and just feels good in the palm! These are very popular for good reason. I also like to use an ergonomic keyboard, specifically, I use the <strong>Microsoft Sculpt</strong> wireless keyboard, though due to its shape, it isn’t for everyone!</p><p><strong>Software</strong></p><p>I love using an IDE for software development. Purists may try and tell you the shell is all you need, but hey it&#39;s 2023! Without any doubt, for software development with Python, I’d absolutely suggest <a href="https://www.jetbrains.com/pycharm/"><strong>PyCharm Pro</strong></a>. A perfectly viable alternative is Visual Studio, but I started out on PyCharm and never moved on as it&#39;s excellent. I make daily use of so many features such as the database window, git integration, diff tool, integrated test runner, and so on.</p><p><strong>Chrome</strong> is my go-to web browser, it&#39;s fast, has an easy-to-use network tab, I can have different profiles for work and personal, and syncs across multiple devices.</p><p>As a backend engineer, there&#39;s a high chance you’ll be working with APIs. <a href="https://www.postman.com/"><strong>Postman</strong></a> is an incredible tool to aid with API development, or just using an API. At its core, it allows you to send requests, though, is bundled with a lot of tooling such as being able to configure different environments and variables, run tests and monitors, export request invocation code in different languages, import requests as cURL from your logs on your APIs and so on. It&#39;s my go-to tool when building and debugging an API to invoke it during development.</p><p><a href="https://sentry.io/welcome/?utm_source=google&amp;utm_medium=cpc&amp;utm_id=%7B19648478148%7D_Google_Search_Brand_EMEA_Alpha&amp;utm_content=g&amp;utm_term=sentry&amp;gad=1"><strong>Sentry</strong></a> is an excellent error reporting, monitoring, and profiling tool I now integrate into all my APIs. All you need to do is add a couple of lines of code to your app, and telemetry data is exported from your app and is viewable in a browser. Any errors are reported in sentry in a ticketed style, alerts can be sent out, the number of invocations can be measured, response times, and much more. The profiling section allows you to identify bottlenecks in your code by telling you which functions are taking the longest time to run.</p><p>A <strong>clipboard manager</strong> is absolutely essential for me! Being able to easily access more than the last item I copied is a game-changer. I use <a href="https://hluk.github.io/CopyQ/">CopyQ</a>.</p><p>As with above, a password manager is also essential. I use <strong>LastPass.</strong></p><p><strong>Docker Desktop </strong>Is an easy-to-use application that allows you to manage containers locally, especially for beginners to Docker as you won’t need to learn shell commands and have a nice easy-to-use GUI instead.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e158d3b48596" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a Mock SQL DB in Python from CSV for unit testing]]></title>
            <link>https://medium.com/@bendev1/create-a-mock-sql-db-in-python-from-csv-for-unit-testing-6668a09dd360?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6668a09dd360</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[mock-data]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 14:37:22 GMT</pubDate>
            <atom:updated>2023-07-01T14:37:22.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dUvHMBHgV9x25VpEqVTgww.png" /></figure><p>Sometimes having a mock database for unit testing can be very useful, especially in database-driven applications. A simple relational database can be configured in under 10 lines of code using a CSV file and some supporting Python libraries.</p><pre>pip install pandas<br>pip install sqlglot<br>pip install sqlalchemy</pre><pre>from sqlalchemy import create_engine, text<br>import sqlglot<br>import pandas as pd<br><br><br>def execute_sql_query(sql):<br>    query_as_sqlite = sqlglot.transpile(sql, read=&quot;postgres&quot;, write=&quot;sqlite&quot;)[0]<br>    mocked_db = create_engine(&#39;sqlite://&#39;)<br>    pd.read_csv(&#39;data.csv&#39;).to_sql(&#39;table_name&#39;, con=mocked_db)<br>    with mocked_db.connect() as connection:<br>        result = connection.execute(text(query_as_sqlite))<br>    return result</pre><p><em>create_engine </em>will return a db instance.</p><p><em>pd.read_csv </em>takes a file path to a CSV file, and will use the CSV file headers as column names, and will insert the rest of the rows into the table.</p><p><em>sqlglot.transpile </em>can be optionally used to transpile the SQL command from a different dialect to sqlite.</p><p>SQL commands can then be called using <em>connection().execute().</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6668a09dd360" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Asynchronous Postgres with Python, FastAPI, and Psycopg 3]]></title>
            <link>https://medium.com/@bendev1/asynchronous-postgres-with-python-fastapi-and-psycopg-3-fafa5faa2c08?source=rss-6391218be80c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fafa5faa2c08</guid>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[psycopg3]]></category>
            <dc:creator><![CDATA[Ben]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 14:17:04 GMT</pubDate>
            <atom:updated>2023-07-10T16:41:26.766Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lJ2n1DEQrq3hBfUysSIgOA.png" /></figure><p>Use advanced features of the Psycopg 3 library such as asynchronous operations and connection pooling to achieve high availability and fast response times.</p><p>At the time of writing this article, with <a href="https://www.psycopg.org/psycopg3/docs/basic/index.html">Psycopg 3</a> being a fairly new release, there isn’t a great deal of example usage so I thought I would demo a few things.</p><pre>pip install fastapi[all]<br>pip install psycopg[binary,pool]</pre><pre>import os<br>from contextlib import asynccontextmanager<br><br>from fastapi import FastAPI, Request<br>from psycopg_pool import AsyncConnectionPool<br><br><br>def get_conn_str():<br>    return f&quot;&quot;&quot;<br>    dbname={os.getenv(&#39;POSTGRES_DB&#39;)}<br>    user={os.getenv(&#39;POSTGRES_USER&#39;)}<br>    password={os.getenv(&#39;POSTGRES_PASSWORD&#39;)}<br>    host={os.getenv(&#39;POSTGRES_HOST&#39;)}<br>    port={os.getenv(&#39;POSTGRES_PORT&#39;)}<br>    &quot;&quot;&quot;<br><br><br>@asynccontextmanager<br>async def lifespan(app: FastAPI):<br>    app.async_pool = AsyncConnectionPool(conninfo=get_conn_str())<br>    yield<br>    await app.async_pool.close()<br><br><br>app = FastAPI(lifespan=lifespan)<br><br><br>@app.get(&quot;/dogs&quot;)<br>async def get_red_dogs(request: Request):<br>    async with request.app.async_pool.connection() as conn:<br>        async with conn.cursor() as cur:<br>            await cur.execute(&quot;&quot;&quot;<br>                SELECT * <br>                FROM dogs<br>            &quot;&quot;&quot;)<br>            results = await cur.fetchall()<br>            return results<br><br><br>@app.post(&quot;/dogs&quot;)<br>async def insert_dog(request: Request):<br>    try:<br>        async with request.app.async_pool.connection() as conn:<br>            async with conn.cursor() as cur:<br>                await cur.execute(&quot;&quot;&quot;<br>                        INSERT INTO dogs (name,age,colour)<br>                        VALUES (%s, %s, %s); <br>                    &quot;&quot;&quot;, (&quot;bonzo&quot;, 10, &quot;red&quot;,))<br>                await conn.commit()<br>    except Exception:<br>        await conn.rollback()</pre><p>Upon app start, initialize a connection pool and assign it to an attribute named <em>async_pool </em>on the app object. <a href="https://fastapi.tiangolo.com/advanced/events/">lifespan events</a> are the current recommended way to execute code once the server starts in FastAPI.</p><p>A connection then can be fetched from the pool during a request instead of initializing a new connection, which can sometimes take a long time.</p><p>Use the above syntax to perform asynchronous operations on the DB.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fafa5faa2c08" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>