Skip to content

Python Cheatsheet

db connection pool

from collections.abc import Generator

import psycopg
from psycopg_pool import ConnectionPool
from psycopg.rows import dict_row

from api.config import DB_DSN

pool = ConnectionPool(
    conninfo=DB_DSN,
    min_size=10,
    max_size=30,
    kwargs={"autocommit": False,  "row_factory": dict_row,},
)

def get_session() -> Generator[psycopg.Connection, None, None]:
    with pool.connection() as conn:
        yield conn

http client

from typing import Dict, Optional, Tuple
import httpx


async def make_request(
    host: str,
    endpoint: str,
    method: str,
    headers: Optional[Dict[str, str]] = None
) -> Tuple[int, str]:
    if headers is None:
        headers = {}

    url = f"{host}{endpoint}"
    async with httpx.AsyncClient() as client:
        if method.lower() == "post":
            response = await client.post(url, headers=headers)
        elif method.lower() == "get":
            response = await client.get(url, headers=headers)
        else:
            raise ValueError(f"Unsupported HTTP method: {method}")

        print(f"status : {response.status_code}")
        if response.status_code == 200:
            print("API CALL SUCCESSFUL")
        else:
            print("API CALL FAILED")

        return response.status_code, response.text