### Basic Configuration with Retries Example Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Demonstrates a basic Tile38 client configuration with both exponential backoff and error-specific retry policies applied. This setup retries connection and timeout errors up to 5 times. ```python from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError, Pyle38TimeoutError tile38 = Tile38( url="redis://localhost:9851", options=[ WithRetryExponentialBackoff(5), # 5 retries with exponential backoff WithRetryOnError(Pyle38ConnectionError, Pyle38TimeoutError), ] ) ``` -------------------------------- ### Start Tile38 Instance with Docker Compose Source: https://github.com/iwpnd/pyle38/blob/main/README.md Starts Tile38 instances using Docker Compose. This is a convenient way to set up Tile38 for local development. ```bash docker-compose up ``` -------------------------------- ### Install Pyle38 using pip Source: https://github.com/iwpnd/pyle38/blob/main/README.md Installs the pyle38 package using pip. Ensure Python 3.10.0 or higher is installed. ```sh pip install pyle38 ``` -------------------------------- ### Install Pyle38 using Poetry Source: https://github.com/iwpnd/pyle38/blob/main/README.md Adds the pyle38 package to a project managed by Poetry. This is an alternative to pip installation. ```sh poetry add pyle38 ``` -------------------------------- ### Get Command Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Constructs a Get command to build and execute GET commands. Requires a client, key, and object ID. ```python Get(client: Client, key: str, oid: str) -> Get ``` -------------------------------- ### Get Command key Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Sets or updates the key for the Get command. Returns the Get command instance. ```python key(key: str) -> Get ``` -------------------------------- ### Retry Algorithm Example Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Demonstrates the exponential backoff pattern for retries, showing wait times between attempts. ```text Attempt 1: Fail immediately, no wait Attempt 2: Wait ~13ms Attempt 3: Wait ~26ms Attempt 4: Wait ~52ms Attempt 5: Wait ~104ms ...exponential growth... Attempt 10: Wait ~6.6 seconds ``` -------------------------------- ### Initialize Tile38 Client Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/tile38-main-client.md Demonstrates basic Tile38 client initialization with leader and optional follower URLs. Includes examples with and without a follower, and with retry configurations. ```python import asyncio from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError, Pyle38TimeoutError async def main(): # Basic initialization tile38 = Tile38(url="redis://localhost:9851") # With follower for read scaling tile38 = Tile38( url="redis://localhost:9851", follower_url="redis://localhost:9852" ) # With retry configuration tile38 = Tile38( url="redis://localhost:9851", options=[ WithRetryExponentialBackoff(10), WithRetryOnError(Pyle38ConnectionError, Pyle38TimeoutError), ] ) await tile38.quit() asyncio.run(main()) ``` -------------------------------- ### Get Command Builder Methods Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Overview of methods available on the Get builder class for retrieving object data in different formats. ```python class Get(Executable): def __init__(self, client: Client, key: str, oid: str) -> None def key(self, key: str) -> Get def id(self, oid: str) -> Get def withfields(self, flag: bool = True) -> Get async def asObject() -> ObjectResponse async def asStringObject() -> ObjectResponse[str] async def asBounds() -> BoundsNeSwResponse async def asPoint() -> PointResponse async def asHash(precision: int) -> HashResponse ``` -------------------------------- ### SCAN with WHERE and ASCOUNT Source: https://github.com/iwpnd/pyle38/blob/main/README.md Example of using the SCAN command with a WHERE clause to filter by field values and ASCOUNT to get the number of matching objects. ```APIDOC ## SCAN with WHERE and ASCOUNT Incrementally iterate through a given collection key, filtering by field values and returning a count. ### Method ``` SCAN key WHERE fieldname min_value max_value ASCOUNT ``` ### Parameters #### Path Parameters - **key** (string) - Required - The name of the collection key to scan. #### Options - **WHERE** (fieldname, min_value, max_value) - Required - Filter output by fieldname and values. #### Outputs - **ASCOUNT** - Required - Returns a count of the objects in the search. ### Example ```python await tile38.scan('fleet').where("maxspeed", 100, 120).asCount() ``` ### Response Example (Success) ```json { "ok":true, "count":1, "cursor":0, "elapsed":"42.8µs" } ``` ``` -------------------------------- ### Production Configuration with Retries Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Recommended production setup for Tile38 client, including exponential backoff and retries on connection and timeout errors. ```python from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError, Pyle38TimeoutError # Recommended for production tile38 = Tile38( url="redis://localhost:9851", follower_url="redis://localhost:9852", options=[ WithRetryExponentialBackoff(10), # Generous retries WithRetryOnError( Pyle38ConnectionError, # Transient network issues Pyle38TimeoutError, # Server under load ), ] ) ``` -------------------------------- ### Method Chaining Example: Set with Options Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Illustrates setting a point with associated fields and options like expiration and conditional setting (NX). ```python # Set with multiple options await tile38.set('fleet', 'truck1') .point(52.25, 13.37) .fields({'maxSpeed': 90, 'mileage': 50000}) .ex(3600) .nx() .exec() ``` -------------------------------- ### Search String Values by Pattern Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Search for string values within a collection that match a glob pattern. This example finds all driver names starting with 'J'. ```python response = await tile38.search('fleet')\ .match('J*') .asStringObjects() ``` -------------------------------- ### Get Command withfields Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Enables or disables the retrieval of fields for the Get command. Defaults to true. ```python withfields(flag: bool = True) -> Get ``` -------------------------------- ### IPython Example for Tile38 Interaction Source: https://github.com/iwpnd/pyle38/blob/main/README.md Shows how to use Pyle38 within an IPython environment, including enabling autoawait and performing set and within operations. Assumes Tile38 is accessible. ```python In [1]: %autoawait asyncio In [2]: from pyle38 import Tile38 In [3]: tile38 = Tile38(url='redis://localhost:9851', follower_url='redis://localhost:9852') In [4]: await tile38.set("fleet", "truck").point(52.25,13.37).exec() Out[4]: JSONResponse(ok=True, elapsed='51.9µs', err=None) In [5]: response = await tile38.within("fleet") ...: .circle(52.25, 13.37, 1000) .asObjects() In [6]: print(response.dict()) ``` -------------------------------- ### Method Chaining Example: Long Chain Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Demonstrates constructing a complex query by chaining multiple builder methods. ```python # Long chain response = await tile38.within('fleet') .circle(52.25, 13.37, 1000) .limit(100) .cursor(0) .match('truck*') .where('maxSpeed', 80, 120) .nofields() .asIds() ``` -------------------------------- ### Get Command Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Build and execute GET commands. This command builder is used for retrieving data associated with a key and object ID, with various formatting options. ```APIDOC ## Get Command ### Description Build and execute GET commands. This command builder is used for retrieving data associated with a key and object ID, with various formatting options. ### Constructor ```python Get(client: Client, key: str, oid: str) -> Get ``` ### Methods - `asHash(precision: int) async -> HashResponse` - `asBounds() async -> BoundsNeSwResponse` - `asObject() async -> ObjectResponse` - `asPoint() async -> PointResponse` - `asStringObject() async -> ObjectResponse[str]` - `id(oid: str) -> Get` - `key(key: str) -> Get` - `withfields(flag: bool = True) -> Get` ``` -------------------------------- ### Tile38 Leader/Follower Client Instantiation Source: https://github.com/iwpnd/pyle38/blob/main/README.md Instantiates the Tile38 client with both leader and follower URLs. This setup is for read-only operations on the follower. ```python from pyle38.tile38 import Tile38 tile38 = Tile38('redis://localhost:9851', 'redis://localhost:9851') ``` -------------------------------- ### Example Bounds Data Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/types.md Provides an example JSON structure for the 'ne' and 'sw' corners within bounds data, including latitude, longitude, and optional height. ```python { "ne": {"lat": 33.491, "lon": -112.245, "z": None}, "sw": {"lat": 33.462, "lon": -112.268, "z": None} } ``` -------------------------------- ### Example ObjectsResponse JSON Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/types.md An example of a JSON response for the ObjectsResponse type, showing a Point object with associated fields. ```json { "ok": True, "elapsed": "48.8µs", "objects": [ { "object": { "type": "Point", "coordinates": [13.37, 52.25] }, "id": "truck1", "distance": None, "fields": {"maxSpeed": 90} } ], "count": 1, "cursor": 0 } ``` -------------------------------- ### Get Command asPoint Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Retrieves the object as a point response. Executes asynchronously. ```python asPoint() async -> PointResponse ``` -------------------------------- ### Get a string object Source: https://github.com/iwpnd/pyle38/blob/main/README.md Use `get` with `asStringObject()` to retrieve an object that has been stored as a string. This is useful for simple key-value storage. ```python await tile38.set('fleet', 'truck1:driver').string('John').exec() await tile38.get('fleet', 'truck1:driver').asStringObject() ``` -------------------------------- ### Get Command asObject Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Retrieves the object as a generic object response. Executes asynchronously. ```python asObject() async -> ObjectResponse ``` -------------------------------- ### Set up a Geofence Webhook Source: https://github.com/iwpnd/pyle38/blob/main/README.md Configure a webhook to send events to a specified endpoint when objects enter a geofenced area. This example sets up a hook for a 500m radius around a specific point in the 'fleet' collection. ```python await tile38.sethook('warehouse', 'http://10.0.20.78/endpoint') .nearby('fleet') .point(33.5123, -112.2693, 500) .activate() ``` -------------------------------- ### Get Command asStringObject Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Retrieves the object as a string object response. Executes asynchronously. ```python asStringObject() async -> ObjectResponse[str] ``` -------------------------------- ### Get withfields() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Demonstrates how to include field data in the response when retrieving an object. ```python def withfields(self, flag: bool = True) -> Get ``` ```python response = await tile38.get('fleet', 'truck1')\ .withfields() .asObject() print(response.fields) # {'maxSpeed': 90, 'mileage': 50000} ``` -------------------------------- ### Get Server Statistics (Follower) Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieves basic server statistics specific to the follower role. Use this to get a general overview of the follower's status. ```python async def server() -> ServerStatsResponseFollower ``` -------------------------------- ### Get Tile38 Server Info (Follower) Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieve server information and statistics specific to the follower instance. This includes metadata and operational stats. ```python response = await tile38.info() ``` -------------------------------- ### GET Source: https://github.com/iwpnd/pyle38/blob/main/README.md Retrieves an object by its collection and ID, with options to format the output. ```APIDOC ## GET ### Description Retrieves an object by its collection and ID, with options to format the output. ### Method `get(collection, id)` ### Parameters #### Path Parameters - **collection** (string) - Required - The name of the collection. - **id** (string) - Required - The ID of the object. ### Options - `.withfields()`: Includes fields associated with the object. Zero values are omitted. ### Output Formats - `.asObject()`: (default) Returns the object in its original format. - `.asBounds()`: Returns the minimum bounding rectangle. - `.asHash(precision)`: Returns the object as a hash with specified precision. - `.asPoint()`: Returns the object as a point. - `.asStringObject()`: Returns the object as a string. ### Request Example ```python # Get as object await tile38.get('fleet', 'truck1').asObject() # Get as string object await tile38.set('fleet', 'truck1:driver').string('John').exec() await tile38.get('fleet', 'truck1:driver').asStringObject() ``` ### Response Example ```json { "type": "object", "geometry": { "type": "Point", "coordinates": [-112.2693, 33.5123] }, "id": "truck1", "fields": { "weight": 9000 } } ``` ``` -------------------------------- ### Get Server Configuration Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Retrieve a specific server configuration key, such as 'keepalive'. ```python response = await tile38.config_get('keepalive') # response.properties = {'keepalive': '300'} ``` -------------------------------- ### Get Tile38 Leader Server Information Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/leader-write-operations.md Retrieve detailed server metadata specific to a Tile38 leader instance. ```python await tile38.info() ``` -------------------------------- ### CONFIG GET / REWRITE / SET Source: https://github.com/iwpnd/pyle38/blob/main/README.md Manage Tile38 server configuration. Use `config_get` to retrieve settings, `config_set` to modify them, and `config_rewrite` to apply changes. Supports options like `requirepass`, `leaderauth`, `protected-mode`, `maxmemory`, `autogc`, and `keep_alive`. ```APIDOC ## CONFIG GET / REWRITE / SET ### Description Manages Tile38 server configuration. `config_get` retrieves settings, `config_set` modifies them, and `config_rewrite` applies changes. Supports various options for security, memory, and performance tuning. ### Method GET, SET, REWRITE (Implied by Python SDK methods) ### Parameters #### Query Parameters (for GET) - **key** (string) - Required - The configuration key to retrieve. #### Request Body (for SET) - **key** (string) - Required - The configuration key to set. - **value** (string) - Required - The new value for the configuration key. ### Request Example (Python SDK) ```python await tile38.config_get('keepalive') await tile38.config_set('keepalive', 400) await tile38.config_rewrite() ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates success of the operation. - **properties** (object) - Contains the configuration key-value pairs (for GET). - **elapsed** (string) - The time taken for the operation. #### Response Example (GET) ```json { "ok":true, "properties":{ "keepalive":"300" }, "elapsed":"54.6µs" } ``` #### Response Example (SET/REWRITE) ```json {"ok":true,"elapsed":"36.9µs"} ``` ``` -------------------------------- ### Kubernetes Readiness Probe Configuration Source: https://github.com/iwpnd/pyle38/blob/main/README.md Example configuration for a Kubernetes readiness probe using the /healthz HTTP endpoint of Tile38. Ensures traffic is only sent to ready instances. ```yaml // values.yaml readinessProbe: httpGet: scheme: HTTP path: /healthz port: 9851 initialDelaySeconds: 60 ``` -------------------------------- ### Set Environment Variables for Tile38 Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Configure the leader and follower URIs for Tile38. This example shows how to export them as environment variables before running a Python application. ```bash export TILE38_LEADER_URI=redis://localhost:9851 export TILE38_FOLLOWER_URI=redis://localhost:9852 python my_app.py ``` -------------------------------- ### Get Server Statistics Source: https://github.com/iwpnd/pyle38/blob/main/README.md Retrieves general statistics about the Tile38 server. For more detailed metrics, use the server_extended command. ```python await tile38.server() ``` -------------------------------- ### Get and Set Configuration Source: https://github.com/iwpnd/pyle38/blob/main/README.md Fetches the current value of a configuration key and then sets a new value. Changes made with config_set require config_rewrite to take effect. ```python await tile38.config_get('keepalive') > { "ok":true, "properties":{ "keepalive":"300" }, "elapsed":"54.6µs" } await tile38.config_set('keepalive', 400) > {"ok":true,"elapsed":"36.9µs"} await tile38.config_rewrite() > {"ok":true,"elapsed":"363µs"} await tile38.config_get('keepalive') > { "ok":true, "properties":{ "keepalive":"400" }, "elapsed":"33.8µs" } ``` -------------------------------- ### Handle Tile38PathNotFoundError Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/errors.md Example of catching Tile38PathNotFoundError when using jget. If the path is not found, it demonstrates setting the path first. ```python from pyle38.errors import Tile38PathNotFoundError try: response = await tile38.jget('users', '123', 'profile.address.zip') except Tile38PathNotFoundError: print("JSON path not found") # Set the path first await tile38.jset('users', '123', 'profile.address.zip', '"12345"') ``` -------------------------------- ### Get Command asBounds Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Retrieves the object's bounds (min/max latitude and longitude). Executes asynchronously. ```python asBounds() async -> BoundsNeSwResponse ``` -------------------------------- ### Get Configuration Value Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieves the current value of a specific configuration parameter. Use this to inspect server settings. ```python async def config_get(name: ConfigKeys) -> ConfigGetResponse ``` -------------------------------- ### Initialize Tile38 Client and Perform Operations Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Demonstrates initializing the Tile38 client, performing a write operation (setting a point with fields and expiration), and a read operation (within a circle). Includes cleanup. ```python import asyncio from pyle38 import Tile38 async def main(): tile38 = Tile38(url="redis://localhost:9851") # Write operation await tile38.set("fleet", "truck1")\ .point(52.25, 13.37)\ .fields({"maxSpeed": 90}) .exec() # Read operation response = await tile38.within("fleet")\ .circle(52.25, 13.37, 1000) .asObjects() print(f"Found {response.count} vehicles") # Cleanup await tile38.quit() asyncio.run(main()) ``` -------------------------------- ### Get Command id Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Sets or updates the object ID for the Get command. Returns the Get command instance. ```python id(oid: str) -> Get ``` -------------------------------- ### Initialize Tile38 Client with Leader and Follower Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Configure the Tile38 client to use a leader URI for write operations and a follower URI for read operations to distribute load. ```python tile38 = Tile38( url="redis://localhost:9851", # leader for writes follower_url="redis://localhost:9852" # follower for reads ) # Writes go to leader await tile38.set('fleet', 'truck1').point(52.25, 13.37).exec() # Reads can use follower to distribute load response = await tile38.follower().within('fleet') .circle(52.25, 13.37, 1000) .asObjects() ``` -------------------------------- ### Instantiate Tile38 with Environment Variables Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Create a Tile38 client instance that automatically uses connection details from environment variables. ```python from pyle38 import Tile38 # Uses environment variables tile38 = Tile38() ``` -------------------------------- ### Configure Tile38 via Environment Variables Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Set Tile38 connection URLs using environment variables for flexible configuration. ```bash export TILE38_LEADER_URI=redis://localhost:9851 export TILE38_FOLLOWER_URI=redis://localhost:9852 ``` -------------------------------- ### Basic Tile38 Client Import Source: https://github.com/iwpnd/pyle38/blob/main/README.md Imports the Tile38 client and instantiates it with a connection URL. This is the initial step for interacting with Tile38. ```python from pyle38 import Tile38 tile38 = Tile38('redis://localhost:9851') ``` -------------------------------- ### Execute Command on Follower Source: https://github.com/iwpnd/pyle38/blob/main/README.md Sends a GET command specifically to the follower instance. This ensures read operations do not impact the leader's performance. ```python await tile38.follower().get('fleet', 'truck1').asObject() ``` -------------------------------- ### Get an object by ID Source: https://github.com/iwpnd/pyle38/blob/main/README.md Use `get` to retrieve an object by its collection and ID. The `asObject()` method returns the object in its native format. ```python await tile38.get('fleet', 'truck1').asObject() ``` -------------------------------- ### Basic Asynchronous Tile38 Interaction Source: https://github.com/iwpnd/pyle38/blob/main/README.md Demonstrates setting a point and querying within a circle using the asynchronous client. Ensure Tile38 is running locally on the default port. ```python import asyncio from pyle38 import Tile38 async def main(): tile38 = Tile38(url="redis://localhost:9851", follower_url="redis://localhost:9851") await tile38.set("fleet", "truck").point(52.25,13.37).exec() response = await tile38.follower() .within("fleet") .circle(52.25, 13.37, 1000) .asObjects() assert response.ok print(response.dict()) await tile38.quit() asyncio.run(main()) ``` -------------------------------- ### Set Object and Get Response Dictionary Source: https://github.com/iwpnd/pyle38/blob/main/README.md Sets a point object in Tile38 and retrieves the response as a dictionary. Useful for inspecting the command's execution details. ```python response = await tile38.set('fleet','truck1') .point(52.25,13.37) .exec() print(response.dict()) > {'ok': True, 'elapsed': '40.7µs'} ``` -------------------------------- ### get() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieves a specific object from a collection by its key and ID. It returns a Get builder that allows for specifying the output format of the retrieved object. ```APIDOC ## GET /get ### Description Get a specific object from a collection. ### Method GET ### Endpoint /get/{key}/{oid} ### Parameters #### Path Parameters - **key** (str) - Required - Collection name - **oid** (str) - Required - Object ID ### Response #### Success Response (200) - **object** (object) - The retrieved object in GeoJSON format. ### Request Example ```json { "example": "response.object" } ``` ### Response Example ```json { "example": {"type": "Point", "coordinates": [13.37, 52.25]} } ``` ``` -------------------------------- ### Tile38 Main Client Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/COMPLETION_SUMMARY.txt Documentation for the main Tile38 class, including its constructor and methods for managing leader and follower roles. ```APIDOC ## Tile38 Main Client ### Description Documentation for the main Tile38 class, including its constructor and methods for managing leader and follower roles. ### Class Tile38 ### Methods - **__init__(...)** - Constructor with all parameters. - **follower()** - Initializes and returns a Follower client instance. - **quit()** - Closes the connection to the Tile38 server. ``` -------------------------------- ### Python Search Command Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Instantiate a Search command builder. Requires a client instance and a key. ```python Search(client: Client, key: str) -> Search ``` -------------------------------- ### Get Object and Inspect Full Response Dictionary Source: https://github.com/iwpnd/pyle38/blob/main/README.md Retrieves a specific object from Tile38 and prints the entire response as a dictionary. Includes status, elapsed time, and the object data. ```python print(response.dict()) > { 'ok': True, 'elapsed': '29.3µs', 'object': { 'type': 'Point', 'coordinates': [13.37, 52.25] } } ``` -------------------------------- ### Set and get JSON values Source: https://github.com/iwpnd/pyle38/blob/main/README.md Use `jset` to set values within a JSON document stored under a key and ID, and `jget` to retrieve the entire JSON document. ```python await tile38.jset('user', 901, 'name', 'Tom') await tile38.jget('user', 901) > {'name': 'Tom'} await tile38.jset('user', 901, 'name.first', 'Tom') await tile38.jset('user', 901, 'name.first', 'Anderson') await tile38.jget('user', 901) > {'name': { 'first': 'Tom', 'last': 'Anderson' }} ``` -------------------------------- ### Get Command Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieve a single object from a collection in various output formats. The Get builder allows for chaining methods to specify retrieval options and format. ```APIDOC ## GET /key/{key}/object/{id} ### Description Retrieve a single object from a collection in various output formats. ### Method GET ### Endpoint /key/{key}/object/{id} ### Parameters #### Query Parameters - **withfields** (bool) - Optional - Whether to include fields in the response. ### Response #### Success Response (200) - **object** (ObjectResponse) - The retrieved object, which can be a GeoJSON object, string, point coordinates, bounding box, or geohash depending on the method used. #### Response Example (asObject) { "example": { "type": "Point", "coordinates": [13.37, 52.25] } } #### Response Example (asStringObject) { "example": "John" } #### Response Example (asPoint) { "example": { "lat": 52.25, "lon": 13.37, "z": null } } #### Response Example (asBounds) { "example": { "ne": {"lat": 52.26, "lon": 13.38}, "sw": {"lat": 52.24, "lon": 13.36} } } #### Response Example (asHash) { "example": "u33d9n" } ``` -------------------------------- ### Tile38 Client Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Instantiate the primary client class for interacting with Tile38. Supports specifying a direct URL, a follower URL, and custom client options. ```python Tile38( url: str | None = None, follower_url: str | None = None, options: list[Callable[..., ClientOptions]] = [] ) -> Tile38 ``` -------------------------------- ### Get asPoint() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieves an object's coordinates as a point. ```python async def asPoint() -> PointResponse ``` ```python response = await tile38.get('fleet', 'truck1').asPoint() print(response.point) # {'lat': 52.25, 'lon': 13.37, 'z': None} ``` -------------------------------- ### Get asStringObject() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieves an object that was set as a string value. ```python async def asStringObject() -> ObjectResponse[str] ``` ```python await tile38.set('fleet', 'truck1:driver').string('John').exec() response = await tile38.get('fleet', 'truck1:driver').asStringObject() print(response.object) # 'John' ``` -------------------------------- ### Leader Client Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Instantiate the Leader client for write operations and admin commands. Requires a URL and accepts optional client options. ```python Leader(url: str, opts: list[Callable[..., ClientOptions]] = []) -> Leader ``` -------------------------------- ### Get asObject() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieves an object from Tile38 as a GeoJSON object. ```python async def asObject() -> ObjectResponse ``` ```python response = await tile38.get('fleet', 'truck1').asObject() print(response.object) # {'type': 'Point', 'coordinates': [13.37, 52.25]} ``` -------------------------------- ### Handle Pyle38NoLeaderSetError Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/errors.md Shows correct ways to initialize Tile38 with a leader URL, either explicitly or via an environment variable. It also demonstrates catching Pyle38NoLeaderSetError when no leader URL is specified. ```python from pyle38 import Tile38 from pyle38.errors import Pyle38NoLeaderSetError # With explicit URL tile38 = Tile38(url="redis://localhost:9851") # OK # With environment variable import os os.environ['TILE38_LEADER_URI'] = "redis://localhost:9851" tile38 = Tile38() # OK # Without URL - error try: tile38 = Tile38(url=None) except Pyle38NoLeaderSetError as e: print(f"Error: {e}") ``` -------------------------------- ### Get asBounds() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieves an object's geometry as a bounding box. ```python async def asBounds() -> BoundsNeSwResponse ``` ```python response = await tile38.get('fleet', 'truck1').asBounds() print(response.bounds) # {'ne': {...}, 'sw': {...}} ``` -------------------------------- ### Get Single Object Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Retrieves a single object by key and ID as an ObjectResponse. ```python .get(key, id).asObject() ``` -------------------------------- ### info() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieve detailed information and statistics about the Tile38 server, specifically from the follower's perspective. ```APIDOC ## info() ### Description Get server information and statistics, specifically for the follower version of Tile38. ### Method GET (Implicit) ### Endpoint (Not explicitly defined, assumed to be part of a Tile38 client operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python response = await tile38.info() ``` ### Response #### Success Response (200) `InfoFollowerResponse` - An object containing server metadata and statistics. #### Response Example ```json { "server": { "version": "1.0.0", "role": "follower" }, "stats": { "num_collections": 5, "memory_usage": 102400 } } ``` ``` -------------------------------- ### Tile38 Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/tile38-main-client.md Initializes the Tile38 client, managing connections to leader and optional follower instances. Supports configuration options for retry behavior. ```APIDOC ## Tile38 Constructor ### Description Initializes the Tile38 client, managing connections to leader and optional follower instances. Supports configuration options for retry behavior. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method Signature ```python Tile38( url: str | None = None, follower_url: str | None = None, options: list[Callable[..., ClientOptions]] = [] ) -> Tile38 ``` #### Parameters - **url** (str | None) - Required - Connection URL for the Tile38 leader instance. Set via environment variable or passed explicitly. Raises `Pyle38NoLeaderSetError` if not provided. - **follower_url** (str | None) - Optional - Connection URL for the Tile38 follower instance. If provided, allows explicit follower operations via `.follower()` method. - **options** (list[Callable[..., ClientOptions]]) - Optional - List of client configuration callables. Supports `WithRetryExponentialBackoff()` and `WithRetryOnError()` options for connection resilience. ### Returns `Tile38` - Initialized Tile38 instance with leader and optional follower connections. ### Raises - `Pyle38NoLeaderSetError`: When no leader URL is provided and `TILE38_LEADER_URI` environment variable is not set. ### Example ```python import asyncio from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError, Pyle38TimeoutError async def main(): # Basic initialization tile38 = Tile38(url="redis://localhost:9851") # With follower for read scaling tile38 = Tile38( url="redis://localhost:9851", follower_url="redis://localhost:9852" ) # With retry configuration tile38 = Tile38( url="redis://localhost:9851", options=[ WithRetryExponentialBackoff(10), WithRetryOnError(Pyle38ConnectionError, Pyle38TimeoutError), ] ) await tile38.quit() asyncio.run(main()) ``` ``` -------------------------------- ### Initialize Tile38 Client with Retries Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Connect to Tile38 using a connection pool and configure retry mechanisms for transient errors like connection issues or timeouts. ```python from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError, Pyle38TimeoutError tile38 = Tile38( url="redis://localhost:9851", options=[ WithRetryExponentialBackoff(10), WithRetryOnError(Pyle38ConnectionError, Pyle38TimeoutError), ] ) ``` -------------------------------- ### server() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Get server statistics specific to the follower mode. This includes follower-specific fields. ```APIDOC ## server() ### Description Get server statistics (follower version). ### Method GET ### Endpoint /server ### Response #### Success Response (200) - **response** (ServerStatsResponseFollower) - Server stats including follower-specific fields. ``` -------------------------------- ### Leader and Follower Configuration with Retries Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Configure a Tile38 client with a leader and follower URL, applying aggressive retry options for transient errors. ```python from pyle38 import Tile38 from pyle38.client_options import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38ConnectionError # Leader with aggressive retries tile38 = Tile38( url="redis://localhost:9851", follower_url="redis://localhost:9852", options=[ WithRetryExponentialBackoff(10), WithRetryOnError(Pyle38ConnectionError), ] ) # Both leader and follower use same options # If different options needed, configure at server level ``` -------------------------------- ### No Retry Configuration Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Instantiate a Tile38 client without any retry mechanisms for immediate failure. ```python from pyle38 import Tile38 # No retries - fail fast tile38 = Tile38(url="redis://localhost:9851", options=[]) # or tile38 = Tile38(url="redis://localhost:9851") ``` -------------------------------- ### Follower Client Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Instantiate the Follower client for read and query operations. Requires a URL and accepts optional client options. ```python Follower( url: str, opts: list[Callable[..., ClientOptions]] = [] ) -> Follower ``` -------------------------------- ### INFO Source: https://github.com/iwpnd/pyle38/blob/main/README.md Retrieves information about the Tile38 server, similar to the `SERVER` command but with potentially different metrics. ```APIDOC ## INFO ### Description Retrieves information about the Tile38 server. This command is similar to `SERVER` but may provide a different set of metrics. ### Method GET ### Endpoint /info ### Request Example (Python SDK) ```python await tile38.info() ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates success of the operation. - **details** (object) - Contains various server information metrics. - **elapsed** (string) - The time taken for the operation. #### Response Example ```json { "ok": true, "details": { "tile38_version": "1.5.0", "uptime": 3600, "...other_info...": "..." }, "elapsed": "XX.Xµs" } ``` ``` -------------------------------- ### Get Command asHash Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Retrieves the object as a hash with specified precision. Executes asynchronously. ```python asHash(precision: int) async -> HashResponse ``` -------------------------------- ### Get asHash() Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Retrieves an object's geometry as a geohash string with specified precision. ```python async def asHash(precision: int) -> HashResponse ``` ```python response = await tile38.get('fleet', 'truck1').asHash(6) print(response.hash) # 'u33d9n' ``` -------------------------------- ### Get Specific Field Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Retrieves a specific field's value for an object. Returns a dictionary. ```python .fget(key, id, field) ``` -------------------------------- ### Within Command Quadkey Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Sets the search area using a quadkey. This is a search area method. ```python quadkey(value: str) -> Within ``` -------------------------------- ### Iterate through a collection Source: https://github.com/iwpnd/pyle38/blob/main/README.md Initiates an incremental scan of the 'fleet' collection. Use this to start iterating through all items in a collection. ```python await tile38.scan('fleet') ``` -------------------------------- ### Persist Server Configuration Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/configuration.md Rewrite the current server configuration to disk to make changes permanent. ```python # Change a config value await tile38.config_set('keepalive', 600) # Persist it await tile38.config_rewrite() # Verify it response = await tile38.config_get('keepalive') assert response.properties['keepalive'] == '600' ``` -------------------------------- ### Handle Pyle38NoHookToActivateError Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/errors.md Demonstrates the correct usage of setting up a hook with a search area before calling .activate(). It also shows how to catch Pyle38NoHookToActivateError when .activate() is called without a defined search area. ```python from pyle38.errors import Pyle38NoHookToActivateError # Correct - with search area await tile38.sethook('alert', 'http://example.com/notify') .within('fleet') .bounds(33.4, -112.2, 33.5, -112.1) .activate() # Incorrect - no search area try: await tile38.sethook('alert', 'http://example.com/notify').activate() except Pyle38NoHookToActivateError as e: print(f"Error: {e}") ``` -------------------------------- ### Set Command Builder Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Build and execute SET commands using a fluent interface. ```APIDOC ## Set Command Builder ### Description Build and execute SET commands. ### Constructor ```python Set(client: Client, key: str, oid: str) -> Set ``` ### Methods - `bounds(min_lat: float, min_lon: float, max_lat: float, max_lon: float) -> Set` - `ex(seconds: int) -> Set` - `fields(fields: Fields) -> Set` - `hash(value: str) -> Set` - `id(value: str) -> Set` - `key(value: str) -> Set` - `nx(flag: bool = True) -> Set` - `object(value: dict) -> Set` - `point(lat: float, lon: float, z?: float) -> Set` - `string(value: str) -> Set` - `xx(flag: bool = True) -> Set` - `exec() async -> JSONResponse` ``` -------------------------------- ### FGET Command Source: https://github.com/iwpnd/pyle38/blob/main/README.md Gets the value of a specific field for a given object. Raises `Tile38FieldNotFoundError` if the field does not exist on the object. ```APIDOC ## FGET Command ### Description Gets the value of a specific field for a given object. Raises `Tile38FieldNotFoundError` if the field does not exist on the object. ### Method FGET ### Endpoint Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Input - `key` (string): The key of the object. - `id` (string): The ID of the object. - `field` (string): The name of the field to retrieve. ### Request Example ```python response = await tile38.fget('fleet', 'truck1', 'maxSpeed').exec() print(response.ok) > True print(response.dict()) > { 'ok': True, 'elapsed': '29.3µs', 'value': 90 } ``` ### Response - `ok` (boolean): Indicates if the operation was successful. - `elapsed` (string): The time taken for the command to execute. - `value` (any): The value of the requested field. ``` -------------------------------- ### Tile38 Client with Retry Options Source: https://github.com/iwpnd/pyle38/blob/main/README.md Configures the Tile38 client with custom options, including exponential backoff for retries and specific error types to retry on. Requires importing necessary classes. ```python from pyle38 import Tile38 from pyle38.client_config import WithRetryExponentialBackoff, WithRetryOnError from pyle38.errors import Pyle38TimeoutError, Pyle38ConnectionError tile38 = Tile38( url='redis://localhost:9851', options=[ # for 10 retries WithRetryExponentialBackoff(10), # retries the following errors WithRetryOnError(Pyle38ConnectionError, Pyle38TimeoutError), ] ) ``` -------------------------------- ### exec() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Execute the compiled command and return the raw response from Tile38. ```APIDOC ## exec() ### Description Execute the compiled command. ### Returns `dict` - Raw response from Tile38. ``` -------------------------------- ### Set Command and Event Output Source: https://github.com/iwpnd/pyle38/blob/main/README.md Executes a 'set' command to add a point to the 'fleet' key and shows the expected event output. This demonstrates how data is published when a point is set. ```python await tile38.set('fleet', 'bus') .point(33.5123001, -112.2693001) .exec(); # event = > { "command": "set", "group": "5c5203ccf5ec4e4f349fd038", "detect": "inside", "hook": "warehouse", "key": "fleet", "time": "2021-03-22T13:06:36.769273-07:00", "id": "bus", "meta": {}, "object": { "type": "Point", "coordinates": [-112.2693001, 33.5123001] } } ``` -------------------------------- ### bounds() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Get the minimum bounding rectangle that encompasses all objects within a collection. Returns a polygon representing these bounds. ```APIDOC ## bounds(key: str) ### Description Get the minimum bounding rectangle for all objects in a collection. ### Method GET (Implicit) ### Endpoint (Not explicitly defined, assumed to be part of a Tile38 client operation) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python response = await tile38.bounds('fleet') print(response.bounds) # Polygon with min/max coordinates ``` ### Response #### Success Response (200) `BoundsResponse` - A polygon object representing the minimum bounding rectangle. #### Response Example ```json { "bounds": { "type": "Polygon", "coordinates": [[[ 13.37, 52.25 ], [ 13.38, 52.25 ], [ 13.38, 52.26 ], [ 13.37, 52.26 ], [ 13.37, 52.25 ]]] } } ``` ``` -------------------------------- ### Create a Webhook for Warehouse Alerts Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/README.md Sets up a webhook to receive notifications when trucks enter or exit a specified warehouse zone. The webhook will be triggered by 'enter' or 'exit' events and will send data to the provided URL. ```python await tile38.sethook( 'warehouse_alert', 'http://api.example.com/events' ).within('fleet').bounds(33.4, -112.2, 33.5, -112.1) .detect(['enter', 'exit']) .meta({'zone_id': 'warehouse_a'}) .commands(['set']) .activate() ``` -------------------------------- ### Get JSON Field as Raw String Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieve a JSON field as an unparsed string by specifying the 'RAW' mode. ```python response = await tile38.jget('users', '123', 'data', 'RAW') ``` -------------------------------- ### Get Full JSON Object Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Retrieve the entire JSON object associated with a given key and object ID. ```python response = await tile38.jget('users', '123') ``` -------------------------------- ### Scan All Objects in Collection Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/follower-read-operations.md Incrementally iterate through all objects in a collection. This example scans all vehicles without any specific filters. ```python response = await tile38.scan('fleet').asObjects() ``` -------------------------------- ### Handle Pyle38NoFollowerSetError Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/errors.md Illustrates the correct usage of the .follower() method when a follower URI is provided during Tile38 initialization. It also shows how to catch Pyle38NoFollowerSetError when no follower URI is set. ```python from pyle38.errors import Pyle38NoFollowerSetError # With follower tile38 = Tile38( url="redis://localhost:9851", follower_url="redis://localhost:9852" ) response = await tile38.follower().get('fleet', 'truck1').asObject() # OK # Without follower - error tile38_no_follower = Tile38(url="redis://localhost:9851") try: response = await tile38_no_follower.follower().get('fleet', 'truck1').asObject() except Pyle38NoFollowerSetError as e: print(f"Error: {e}") ``` -------------------------------- ### compile() Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/query-builders.md Generates the command and arguments tuple. Must be implemented by subclasses. ```APIDOC ## compile() ### Description Generate the command and arguments tuple. Must be implemented by subclasses. ### Returns `Compiled` - Tuple of (Command, CommandArgs). ``` -------------------------------- ### Set Command Builder Constructor Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Initialize a Set command builder. This is used to construct and execute SET commands, requiring a client instance, key, and object ID. ```python Set(client: Client, key: str, oid: str) -> Set ``` -------------------------------- ### Get statistics for keys Source: https://github.com/iwpnd/pyle38/blob/main/README.md Use `stats` to retrieve statistics such as memory usage and object counts for one or more specified keys. ```python await tile38.stats('fleet1', 'fleet2') ``` -------------------------------- ### Within Command Get Method Source: https://github.com/iwpnd/pyle38/blob/main/_autodocs/api-index.md Specifies a key and ID to retrieve within the Within search. This is a search area method. ```python get(key: str, id: str) -> Within ```