Registry / http-networking / pyactiveresource

pyactiveresource

JSON →
library2.2.2pypypi✓ verified 24d ago

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.

pip install pyactiveresource
INSTALL
IMPORT
SIG · PYACTIVERESOURCE
P
pyactiveresource
http-networkingpythonv2.2.2
Install
2.4s avg
Import
175ms
Disk
17MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v2.2.2 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.95 runs
installs and imports cleanly · install 0.0s · import 0.182s · 19.5MB
glibc
py 3.103.95 runs
installs and imports cleanly · install 2.4s · import 0.168s · 20MB
17MB installed
● package 17MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

ActiveResource
from pyactiveresource import activeresource as ar # Then use ar.ActiveResource
from pyactiveresource.activeresource import ActiveResource
The common convention shown in documentation is to import the module as 'ar'.
ConnectionError
from pyactiveresource.connection import ConnectionError
Base exception for connection issues, and its subclasses like `UnauthorizedAccess`.

This quickstart demonstrates how to define a resource class by inheriting from `pyactiveresource.activeresource.ActiveResource` and setting its `_site` attribute to your REST API's base URL. It then shows how to use class methods like `find()` to retrieve resources and instance methods like `save()` to create new ones, encapsulating typical REST interactions. It also includes basic error handling for common `pyactiveresource` exceptions.

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}")
Debug
Known issues
breakingThe 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.
fix
Thoroughly test with your target Python version. Consider evaluating alternatives if facing compatibility issues, as the library may not be actively maintained for newer Python versions.
affects: <=2.2.2 (all versions)
gotchaPyActiveResource 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.
fix
Ensure your API endpoints and data structures adhere to RESTful conventions expected by ActiveResource. Consult Ruby's ActiveResource documentation for the underlying philosophy, or explicitly configure `_site`, `_headers`, and custom methods when conventions cannot be followed.
affects: All versions
gotchaThe 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.
fix
Carefully manage the `_site` URL and ensure consistent path construction. Double-check that `_site` ends without a slash if your resource names are expected to provide the initial path component, or vice versa, to avoid malformed URLs. Always inspect the actual HTTP requests being sent.
affects: All versions
gotchaDirect 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.
fix
Prefer using the `ActiveResource` object's public interface (`resource.attribute = value`, `resource.save()`) for data manipulation. If direct JSON loading is necessary, ensure that the data is thoroughly pre-processed to match the expected object structure, and use `resource.load(data)` if available, rather than internal `_update` methods.
affects: All versions
Errors
Common errors & fixes
pyactiveresource.connection.ResourceNotFound: Response(code=404, ...)
This error occurs when the constructed URL for a resource does not match an existing endpoint on the REST API, often due to incorrect _site configuration or resource path definitions, resulting in an HTTP 404 Not Found response.
fix
Carefully review the `_site` URL in your `ActiveResource` class definition, paying attention to trailing slashes, and ensure that your resource names and methods correctly build the expected API endpoint path. Debug by inspecting the actual HTTP requests being sent.
pyactiveresource.connection.UnauthorizedAccess: Response(code=401, ...)
This error indicates that the client attempted to access a protected resource without valid authentication credentials, resulting in an HTTP 401 Unauthorized response from the API.
fix
Verify that your API keys, tokens, or other authentication credentials are correctly configured and passed with the `_site` URL or custom headers for your `ActiveResource` class.
pyactiveresource.connection.ServerError: Internal Server Error
This exception is raised when the remote REST service encounters an internal error (HTTP 5xx status code), indicating a problem on the server side rather than a client-side issue.
fix
While this error originates from the server, implement robust error handling in your client code, potentially with retry mechanisms and exponential backoff, and consider logging details to assist with reporting the issue to the API provider.
AttributeError: 'unicode' object has no attribute 'iteritems'
This error typically occurs in Python 2.x environments when `pyactiveresource` attempts to parse an error response body, and the `errors` field returned by the API is a simple string instead of a dictionary-like structure, leading to an incorrect call to `six.iteritems`.
fix
Ensure that the API consistently returns a dictionary or object structure for error responses. If not possible, you may need to manually parse `err.response.body` to handle string-based error messages before `pyactiveresource` attempts to process them as structured errors.
ModuleNotFoundError: No module named 'pyactiveresource.activeresource'
This common import error occurs when `ActiveResource` is incorrectly imported directly from the top-level `pyactiveresource` package, instead of its specific submodule `activeresource`.
fix
The correct way to import the `ActiveResource` class is `from pyactiveresource.activeresource import ActiveResource` or, following the common convention, `from pyactiveresource import activeresource as ar` and then use `ar.ActiveResource`.
Upgrade
Version history
2.2.2latest on PyPI · released Feb 4, 2021
Audit
Dependencies
sixrequiredUsed for Python 2/3 compatibility, explicitly required by the library's setup.py.
Agent activity
12 hits · last 30 days
node
10
Resources
pyactiveresource — pip install pyactiveresource · libregistry