Skip to main content

Simple Pydantic AIOHTTP Client Sessions

Project description

SPACS: Simple Pydantic AIOHTTP Client Sessions

A package to assist in managing and using long-lived AIOHTTP client sessions with simplicity. Built to handle Pydantic objects.

Features

  • Handles request params and bodies as either Pydantic objects or native Python dictionaries, converting items to JSON-safe format.
  • Abstracts away internals of managing the request/response objects, instead either returning parsed response content on success, or raising a specialized error object.
  • Automatically manages persistent connections to be shared over extended lifespan across application, cleaning up all open connections on teardown.
  • Utilizes modern Python type hinting.

Installation

Using poetry (preferred):

poetry add spacs

Using pip:

pip install spacs

Basic Usage

SPACS currently supports the HTTP methods GET, POST, PUT, and DELETE. All methods take the same, singular SpacsRequest argument. The following are some common patterns to be utilized when working with SPACS.

Request With Params

import asyncio
from spacs import SpacsClient, SpacsRequest

async def example():
    client = SpacsClient(base_url="https://httpbin.org")
    request = SpacsRequest(path="/get", params={"foo": "bar"})
    result = await client.get(request)
    print(result)
    await client.close()


loop = asyncio.new_event_loop()
loop.run_until_complete(example())

Sending Pydantic objects via request body

import asyncio
from spacs import SpacsClient, SpacsRequest
from pydantic import BaseModel

class Person(BaseModel):
    name: str
    age: int

async def example():
    client = SpacsClient(base_url="https://httpbin.org")
    person = Person(name="James", age=25)
    request = SpacsRequest(path="/post", body=person)
    response = await client.post(request)
    print(response)
    await client.close()


loop = asyncio.new_event_loop()
loop.run_until_complete(example())

Tip: Response Model

For all examples here, if the API declares that response bodies will only contain json data representing a Pydantic object, the payload can be deserialized into an object by specifying a Pydantic class in the request. For example, using our above Person model:

request = SpacsRequest(path="/post", body=person, response_model=Person)
response = await client.post(request)
assert isinstance(response, Person)

Handling Errors

Manual Error Handling

import asyncio
from spacs import SpacsClient, SpacsRequest, SpacsRequestError

async def example():
    client = SpacsClient(base_url="https://httpbin.org")
    request = SpacsRequest(path="/status/404")
    try:
        await client.get(request)
    except SpacsRequestError as error:
        print({"code": error.status, "reason": error.reason})
    await client.close()


loop = asyncio.new_event_loop()
loop.run_until_complete(example())

Injecting Error Handler

import asyncio
from spacs import SpacsClient, SpacsRequest, SpacsRequestError

async def error_handler(error: SpacsRequestError) -> None:
    print(f"It blew up: {error.reason}")

async def example():
    client = SpacsClient(base_url="https://httpbin.org", error_handler=error_handler)
    request = SpacsRequest(path="/status/504")
    response = await client.get(request)
    await client.close()
    assert response is None


loop = asyncio.new_event_loop()
loop.run_until_complete(example())

Closing sessions

In the above examples, a client.close() call is made. This is to ensure that the underlying AIOHTTP session is properly cleaned up, and is a step that should always be performed on application teardown. Alternatively, the following can be used to close all open sessions without having to directly reference a client instance:

await SpacsClient.close_all()

SPACS is not affiliated with httpbin.org.

Building

poetry build

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

spacs-0.0.8.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

spacs-0.0.8-py3-none-any.whl (6.0 kB view details)

Uploaded Python 3

File details

Details for the file spacs-0.0.8.tar.gz.

File metadata

  • Download URL: spacs-0.0.8.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.11.1 Windows/10

File hashes

Hashes for spacs-0.0.8.tar.gz
Algorithm Hash digest
SHA256 743e8a6929ec4d0c28b32a31d39858d4337403425ccbe94a6a9a9eefe495bb2e
MD5 c03de83ae243e56c6d74b46d41013691
BLAKE2b-256 38d3b3142f037ab3c5ffc3fbad65aaf21db13f09f2dda0f88b22b8ef5cbf7295

See more details on using hashes here.

File details

Details for the file spacs-0.0.8-py3-none-any.whl.

File metadata

  • Download URL: spacs-0.0.8-py3-none-any.whl
  • Upload date:
  • Size: 6.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.3.1 CPython/3.11.1 Windows/10

File hashes

Hashes for spacs-0.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 ea221e4f549e5cbf2530d119f70b461af58609c8f14eb6450641de922653c308
MD5 467b7e06abbd84423090230381f29a82
BLAKE2b-256 929ce47c86ca42a4c799900b1c08fc65075091ad14796b1236272491f276062a

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page