base.py
Overview
The base.py file defines a foundational class named Base that serves as a generic container and interface for interacting with RESTful API endpoints via an underlying request abstraction (rag). This class allows hierarchical data structures—potentially nested dictionaries—to be wrapped into Base instances, providing convenient recursive access and serialization to JSON-compatible dictionaries.
The Base class also encapsulates standard HTTP methods (GET, POST, PUT, DELETE) by delegating these requests to the rag object provided upon initialization. This design suggests that Base acts as a lightweight client-side model, mapping API resources to Python objects with easy data manipulation and API interaction capabilities.
Detailed Description
Class: Base
Purpose
Base is designed to:
Represent and encapsulate data returned from or sent to an API.
Recursively convert nested dictionaries into nested
Baseinstances for attribute-style access.Provide serialization to JSON-compatible dictionaries.
Provide a simple interface for HTTP methods (
GET,POST,PUT,DELETE) using an underlying requester (rag).
Constructor
def __init__(self, rag, res_dict):
Parameters:
rag: An object responsible for making HTTP requests. It must provide methods.get(),.post(),.put(), and.delete()compatible with the calls inBase.res_dict: A dictionary representing data, potentially nested, which will be converted into attributes of theBaseinstance.
Functionality:
Stores the
ragobject as an instance attribute.Calls the internal
_update_from_dict()method to populate instance attributes fromres_dict, recursively wrapping nested dictionaries.
Usage Example:
rag = SomeRequestHandler()
response_data = {
"id": 123,
"name": "Example",
"metadata": {
"created": "2025-01-01",
"tags": ["tag1", "tag2"]
}
}
base_obj = Base(rag, response_data)
print(base_obj.name) # Output: Example
print(base_obj.metadata.created) # Output: 2025-01-01
Method: _update_from_dict
def _update_from_dict(self, rag, res_dict):
Parameters:
rag: Same as the constructor parameter; passed down to nestedBaseinstances.res_dict: Dictionary of key-value pairs to convert into instance attributes.
Functionality:
Iterates over all items in
res_dict.For any value that is a dictionary, creates a nested
Baseobject with the samerag.For other value types, assigns them directly as instance attributes.
Implementation Detail:
Uses direct manipulation of
self.dictfor dynamic attribute assignment.Enables deep nesting of data to be represented as nested
Baseobjects.
Method: to_json
def to_json(self):
Returns:
A dictionary representing the data stored in the
Baseobject, recursively converting nestedBaseinstances into dictionaries.
Functionality:
Iterates over all instance attributes (excluding private attributes, methods, and the
ragattribute).If an attribute is itself a
Baseinstance, calls itsto_json()method recursively.Otherwise, includes the attribute's value as-is.
Use Case:
Serialize the current state of the object for JSON encoding or API submission.
Usage Example:
json_dict = base_obj.to_json()
print(json_dict)
# Output:
# {
# "id": 123,
# "name": "Example",
# "metadata": {
# "created": "2025-01-01",
# "tags": ["tag1", "tag2"]
# }
# }
HTTP Wrapper Methods
Each method delegates the corresponding HTTP operation to the stored rag object.
post
def post(self, path, json=None, stream=False, files=None):
Parameters:
path(str): API endpoint path.json(dict, optional): JSON payload to send.stream(bool, optional): Whether to stream the response.files(optional): Files to upload.
Returns:
The response object from the
rag.post()call.
Usage:
response = base_obj.post("/api/resource", json={"key": "value"})
get
def get(self, path, params=None):
Parameters:
path(str): API endpoint path.params(dict, optional): Query parameters.
Returns:
The response object from the
rag.get()call.
Usage:
response = base_obj.get("/api/resource", params={"id": 123})
rm (Delete)
def rm(self, path, json):
Parameters:
path(str): API endpoint path.json(dict): JSON payload to send with the delete request.
Returns:
The response object from the
rag.delete()call.
Usage:
response = base_obj.rm("/api/resource", json={"id": 123})
put
def put(self, path, json):
Parameters:
path(str): API endpoint path.json(dict): JSON payload for the update.
Returns:
The response object from the
rag.put()call.
Usage:
response = base_obj.put("/api/resource", json={"name": "New Name"})
Method: __str__
def __str__(self):
Returns:
A string representation of the object by converting it to JSON-compatible dictionary and then to string.
Purpose:
Provides a human-readable string format of the object for debugging or logging.
Example:
print(str(base_obj))
# Output: '{"id": 123, "name": "Example", "metadata": {"created": "2025-01-01", "tags": ["tag1", "tag2"]}}'
Important Implementation Details
Recursive Wrapping: Nested dictionaries in the input data are recursively wrapped as
Baseinstances, enabling attribute-style access to deeply nested data.Dynamic Attributes: Uses
self.dictfor dynamic attribute assignment, which means attributes can be dynamically added or removed based on the input dictionary.Delegation Pattern: All HTTP requests are delegated to the
ragobject, which abstracts the underlying HTTP client or request handling logic. This promotes separation of concerns and flexibility.Filtering in
to_json: Theto_jsonmethod filters out private attributes (those starting with__), callable attributes (methods), and theragattribute itself to avoid serializing non-data members.
Interaction with Other Parts of the System
The
Baseclass depends heavily on theragobject, which is expected to be a request abstraction layer implementing standard HTTP methods (get,post,put,delete).Likely,
ragmanages HTTP session, authentication, headers, and low-level network communication.This file acts as a base or utility model within the system, potentially used by higher-level modules or services to represent API resources.
It can be extended or composed into more specialized resource classes that handle domain-specific logic.
Visual Diagram
classDiagram
class Base {
-rag
+__init__(rag, res_dict)
-_update_from_dict(rag, res_dict)
+to_json() dict
+post(path, json=None, stream=False, files=None)
+get(path, params=None)
+rm(path, json)
+put(path, json)
+__str__()
}
Summary
The base.py file provides a generalized, recursive data model class Base for representing API responses and requests as Python objects. It encapsulates nested data, provides JSON serialization, and delegates HTTP method calls to a request handler abstraction. This makes it a flexible foundation for API client implementations in the InfiniFlow project or similar systems.