0
0
FastAPIframework~10 mins

Connection pooling in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create a connection pool with asyncpg in FastAPI.

FastAPI
import asyncpg

async def connect_db():
    pool = await asyncpg.create_pool(dsn=[1])
    return pool
Drag options to blanks, or click blank then click option'
A12345
B"postgresql://user:pass@localhost/dbname"
CNone
DTrue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a number instead of a connection string
Passing None instead of a DSN string
2fill in blank
medium

Complete the code to acquire a connection from the pool in an async context.

FastAPI
async with pool.[1]() as connection:
    result = await connection.fetch('SELECT 1')
Drag options to blanks, or click blank then click option'
Aacquire
Bconnect
Cget
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' which creates a new connection
Using 'get' which is not a pool method
3fill in blank
hard

Fix the error in the code to properly release the connection back to the pool.

FastAPI
connection = await pool.[1]()
try:
    await connection.execute('SELECT 1')
finally:
    await connection.release()
Drag options to blanks, or click blank then click option'
Aconnect
Bget
Copen
Dacquire
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' which does not support release
Forgetting to release the connection
4fill in blank
hard

Fill both blanks to create a FastAPI dependency that provides a connection from the pool.

FastAPI
from fastapi import Depends

async def get_connection(pool=Depends([1])):
    async with pool.[2]() as conn:
        yield conn
Drag options to blanks, or click blank then click option'
Aconnect_db
Bacquire
Cconnect
Dget_pool
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'connect' instead of 'acquire'
Using a wrong dependency function name
5fill in blank
hard

Fill all three blanks to create a dictionary comprehension that maps table names to their row counts using a connection.

FastAPI
counts = { [1]: await conn.fetchval(f'SELECT COUNT(*) FROM [2]') for [1] in [3] }
Drag options to blanks, or click blank then click option'
Atable
Bconn
Ctables
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for loop variable and query placeholder
Using 'conn' as loop variable