PyActiveResource
PyActiveResource is a Python port of Ruby's ActiveResource project, providing an object-relational mapping (ORM) for RESTful web services. It aims to simplify interaction with REST APIs by mapping remote resources to local Python objects, following a 'convention over configuration' philosophy. The current version is 2.2.2, with its last release in February 2021, suggesting a stable but slow release cadence.
Warnings
- breaking The PyPI project classifiers officially list support only up to Python 3.4. While it uses `six` for Python 2/3 compatibility, using `pyactiveresource` with modern Python versions (3.5+) might encounter unexpected issues or require manual patching.
- gotcha PyActiveResource relies heavily on 'convention over configuration', similar to Ruby's ActiveResource. It expects RESTful conventions like pluralized resource names (e.g., 'Person' maps to '/people'), standard HTTP verbs (GET for find, POST for create, PUT for update), and a specific JSON request/response format. Deviating from these conventions without explicit configuration will likely lead to errors.
- gotcha The library's implicit URL construction can be a source of errors, especially with trailing slashes or complex API paths. Issues have been reported where incorrectly configured `_site` or resource paths lead to malformed URLs (e.g., double slashes) resulting in `ResourceNotFound` or `BadRequest` exceptions.
- gotcha Direct manipulation of internal methods, such as `_update`, with raw JSON dictionaries, can lead to `TypeError` (e.g., 'cannot use a string pattern on a bytes-like') or other serialization/deserialization issues if the input data doesn't precisely match the library's internal expectations for attribute assignment, especially with nested objects or different string encodings.
Install
-
pip install pyactiveresource
Imports
- ActiveResource
from pyactiveresource import activeresource as ar # Then use ar.ActiveResource
- ConnectionError
from pyactiveresource.connection import ConnectionError
Quickstart
import os
from pyactiveresource import activeresource as ar
# Configure your API base URL (e.g., from environment variables)
API_BASE_URL = os.environ.get('PYACTIVERESOURCE_API_URL', 'http://api.example.com/v1')
# Define a resource class that maps to your REST endpoint
class Person(ar.ActiveResource):
_site = API_BASE_URL
# Optionally set headers for authentication, e.g., Bearer token
# _headers = {'Authorization': f'Bearer {os.environ.get("API_TOKEN", "")}'}
# Example usage:
try:
# Find all people
all_people = Person.find()
print(f"Found {len(all_people)} people.")
for p in all_people:
print(f"ID: {p.id}, Name: {p.name if hasattr(p, 'name') else 'N/A'}")
# Find a specific person by ID
if all_people:
first_person_id = all_people[0].id
person = Person.find(first_person_id)
print(f"\nFound person: {person.name if hasattr(person, 'name') else 'N/A'} (ID: {person.id})")
# Create a new person
new_person = Person(name='Alice', age=30)
if new_person.save():
print(f"\nCreated new person: {new_person.name} (ID: {new_person.id})")
else:
print(f"Failed to create person. Errors: {new_person.errors}")
except ar.ResourceNotFound:
print(f"Resource not found at {API_BASE_URL}.")
except ar.ConnectionError as e:
print(f"Connection error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")