tlq-client


Nametlq-client JSON
Version 0.2.0 PyPI version JSON
download
home_pageNone
SummaryPython client library for TLQ (Tiny Little Queue)
upload_time2025-08-21 14:56:47
maintainerNone
docs_urlNone
authorNone
requires_python>=3.7
licenseMIT
keywords queue message-queue tlq microservices
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # TLQ Client for Python

A Python client library for [TLQ (Tiny Little Queue)](https://github.com/skyaktech/tlq), a minimal message queue server written in Rust.

## Features

- Simple, lightweight Python client for TLQ
- Full support for all TLQ API operations
- Built-in retry logic with exponential backoff
- Environment variable configuration
- Type hints and comprehensive error handling
- Context manager support
- Extensive test coverage

## Installation

```bash
pip install tlq-client
```

## Quick Start

```python
from tlq_client import TLQClient

# Create client with default settings (localhost:1337)
client = TLQClient()

# Add a message to the queue
message_id = client.add_message("Hello, TLQ!")
print(f"Added message: {message_id}")

# Get messages from the queue
messages = client.get_messages(count=1)
for message in messages:
    print(f"Received: {message.body} (ID: {message.id})")
    
    # Process the message...
    # Then delete it from the queue
    client.delete_messages(message.id)
```

## Configuration

### Constructor Parameters

```python
client = TLQClient(
    host="localhost",        # TLQ server hostname
    port=1337,              # TLQ server port
    timeout=30.0,           # Request timeout in seconds
    max_retries=3           # Maximum retry attempts
)
```

### Environment Variables

You can also configure the client using environment variables:

- `TLQ_HOST` - Server hostname (default: localhost)
- `TLQ_PORT` - Server port (default: 1337)
- `TLQ_TIMEOUT` - Request timeout in seconds (default: 30.0)
- `TLQ_MAX_RETRIES` - Maximum retry attempts (default: 3)

```bash
export TLQ_HOST=queue.example.com
export TLQ_PORT=8080
export TLQ_TIMEOUT=60.0
export TLQ_MAX_RETRIES=5

python your_script.py
```

## API Reference

### TLQClient

#### `health_check() -> bool`

Check if the TLQ server is healthy.

```python
if client.health_check():
    print("TLQ server is running")
else:
    print("TLQ server is not available")
```

#### `add_message(body: str) -> str`

Add a message to the queue. Returns the message ID.

```python
message_id = client.add_message("Process this task")
```

**Note:** Messages are limited to 64KB in size.

#### `get_messages(count: int = 1) -> List[TLQMessage]`

Retrieve messages from the queue.

```python
# Get one message
messages = client.get_messages()

# Get multiple messages
messages = client.get_messages(count=5)

for message in messages:
    print(f"ID: {message.id}")
    print(f"Body: {message.body}")
    print(f"State: {message.state}")
    print(f"Retry Count: {message.retry_count}")
```

#### `delete_messages(message_ids: Union[str, List[str]])`

Delete processed messages from the queue.

```python
# Delete single message
client.delete_messages(message_id)

# Delete multiple messages
client.delete_messages([id1, id2, id3])
```

#### `retry_messages(message_ids: Union[str, List[str]])`

Return messages to the queue for retry.

```python
# Retry single message
client.retry_messages(message_id)

# Retry multiple messages  
client.retry_messages([id1, id2, id3])
```

#### `purge_queue()`

Clear all messages from the queue.

```python
client.purge_queue()
```

### TLQMessage

Message objects returned by `get_messages()`:

```python
@dataclass
class TLQMessage:
    id: str           # UUID v7 message identifier
    body: str         # Message content
    state: str        # Message state (e.g., "Ready", "Processing")
    retry_count: int  # Number of retry attempts
```

## Error Handling

The client provides specific exception types for different error conditions:

```python
from tlq_client import (
    TLQError,           # Base exception
    TLQConnectionError, # Connection failures
    TLQTimeoutError,    # Request timeouts
    TLQServerError,     # Server errors (4xx, 5xx)
    TLQValidationError  # Client-side validation errors
)

try:
    client.add_message("Hello, TLQ!")
except TLQValidationError as e:
    print(f"Validation error: {e}")
except TLQConnectionError as e:
    print(f"Connection error: {e}")
except TLQTimeoutError as e:
    print(f"Timeout error: {e}")
except TLQServerError as e:
    print(f"Server error: {e} (status: {e.status_code})")
except TLQError as e:
    print(f"TLQ error: {e}")
```

## Context Manager Support

The client can be used as a context manager to ensure proper cleanup:

```python
with TLQClient() as client:
    message_id = client.add_message("Hello!")
    messages = client.get_messages()
    # Session automatically closed when exiting context
```

## Examples

### Basic Producer

```python
from tlq_client import TLQClient

def produce_messages():
    with TLQClient() as client:
        for i in range(10):
            message_id = client.add_message(f"Task {i}")
            print(f"Queued task {i}: {message_id}")

if __name__ == "__main__":
    produce_messages()
```

### Basic Consumer

```python
import time
from tlq_client import TLQClient, TLQError

def consume_messages():
    with TLQClient() as client:
        while True:
            try:
                messages = client.get_messages(count=5)
                
                if not messages:
                    print("No messages available, sleeping...")
                    time.sleep(1)
                    continue
                
                for message in messages:
                    try:
                        # Process the message
                        print(f"Processing: {message.body}")
                        time.sleep(0.1)  # Simulate work
                        
                        # Mark as completed
                        client.delete_messages(message.id)
                        print(f"Completed: {message.id}")
                        
                    except Exception as e:
                        print(f"Failed to process {message.id}: {e}")
                        # Return to queue for retry
                        client.retry_messages(message.id)
                        
            except TLQError as e:
                print(f"TLQ error: {e}")
                time.sleep(5)  # Back off on errors

if __name__ == "__main__":
    consume_messages()
```

### Configuration from Environment

```python
import os
from tlq_client import TLQClient

# Set environment variables
os.environ['TLQ_HOST'] = 'queue.myapp.com'
os.environ['TLQ_PORT'] = '8080'
os.environ['TLQ_TIMEOUT'] = '60'

# Client automatically picks up environment configuration
client = TLQClient()
print(f"Connected to {client.config.base_url}")
```

## Development

### Setup Development Environment

```bash
# Create virtual environment (recommended on macOS/Linux to avoid system Python restrictions)
python3 -m venv venv

# Activate virtual environment
# On macOS/Linux:
source venv/bin/activate
# On Windows:
# venv\Scripts\activate

# Install development dependencies
pip install -e ".[dev]"
```

### Running Tests

```bash
# Make sure virtual environment is activated
source venv/bin/activate

# Run tests
pytest

# Run tests with verbose output
pytest -v

# Run tests with coverage
pytest --cov=tlq_client --cov-report=html

# Run specific test file
pytest tests/test_client.py

# Run specific test
pytest tests/test_client.py::TestTLQClient::test_add_message_success
```

### Code Quality

```bash
# Format code
black tlq_client tests

# Sort imports  
isort tlq_client tests

# Lint code
flake8 tlq_client tests

# Type checking
mypy tlq_client
```

## Requirements

- Python 3.7+
- requests >= 2.25.0

## License

MIT License - see [LICENSE](LICENSE) file for details.

## Related Projects

- [TLQ Server](https://github.com/skyaktech/tlq) - The TLQ message queue server
- [TLQ Node.js Client](https://github.com/skyaktech/tlq-client-node) - Node.js client library

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "tlq-client",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": null,
    "keywords": "queue, message-queue, tlq, microservices",
    "author": null,
    "author_email": "Nebojsa Jakovljevic <nebojsa@skyak.tech>",
    "download_url": "https://files.pythonhosted.org/packages/b6/dc/61a900eef4b5d2680a06b7e0e37a1f0a87e3524a96c9410c31646cbe556a/tlq_client-0.2.0.tar.gz",
    "platform": null,
    "description": "# TLQ Client for Python\n\nA Python client library for [TLQ (Tiny Little Queue)](https://github.com/skyaktech/tlq), a minimal message queue server written in Rust.\n\n## Features\n\n- Simple, lightweight Python client for TLQ\n- Full support for all TLQ API operations\n- Built-in retry logic with exponential backoff\n- Environment variable configuration\n- Type hints and comprehensive error handling\n- Context manager support\n- Extensive test coverage\n\n## Installation\n\n```bash\npip install tlq-client\n```\n\n## Quick Start\n\n```python\nfrom tlq_client import TLQClient\n\n# Create client with default settings (localhost:1337)\nclient = TLQClient()\n\n# Add a message to the queue\nmessage_id = client.add_message(\"Hello, TLQ!\")\nprint(f\"Added message: {message_id}\")\n\n# Get messages from the queue\nmessages = client.get_messages(count=1)\nfor message in messages:\n    print(f\"Received: {message.body} (ID: {message.id})\")\n    \n    # Process the message...\n    # Then delete it from the queue\n    client.delete_messages(message.id)\n```\n\n## Configuration\n\n### Constructor Parameters\n\n```python\nclient = TLQClient(\n    host=\"localhost\",        # TLQ server hostname\n    port=1337,              # TLQ server port\n    timeout=30.0,           # Request timeout in seconds\n    max_retries=3           # Maximum retry attempts\n)\n```\n\n### Environment Variables\n\nYou can also configure the client using environment variables:\n\n- `TLQ_HOST` - Server hostname (default: localhost)\n- `TLQ_PORT` - Server port (default: 1337)\n- `TLQ_TIMEOUT` - Request timeout in seconds (default: 30.0)\n- `TLQ_MAX_RETRIES` - Maximum retry attempts (default: 3)\n\n```bash\nexport TLQ_HOST=queue.example.com\nexport TLQ_PORT=8080\nexport TLQ_TIMEOUT=60.0\nexport TLQ_MAX_RETRIES=5\n\npython your_script.py\n```\n\n## API Reference\n\n### TLQClient\n\n#### `health_check() -> bool`\n\nCheck if the TLQ server is healthy.\n\n```python\nif client.health_check():\n    print(\"TLQ server is running\")\nelse:\n    print(\"TLQ server is not available\")\n```\n\n#### `add_message(body: str) -> str`\n\nAdd a message to the queue. Returns the message ID.\n\n```python\nmessage_id = client.add_message(\"Process this task\")\n```\n\n**Note:** Messages are limited to 64KB in size.\n\n#### `get_messages(count: int = 1) -> List[TLQMessage]`\n\nRetrieve messages from the queue.\n\n```python\n# Get one message\nmessages = client.get_messages()\n\n# Get multiple messages\nmessages = client.get_messages(count=5)\n\nfor message in messages:\n    print(f\"ID: {message.id}\")\n    print(f\"Body: {message.body}\")\n    print(f\"State: {message.state}\")\n    print(f\"Retry Count: {message.retry_count}\")\n```\n\n#### `delete_messages(message_ids: Union[str, List[str]])`\n\nDelete processed messages from the queue.\n\n```python\n# Delete single message\nclient.delete_messages(message_id)\n\n# Delete multiple messages\nclient.delete_messages([id1, id2, id3])\n```\n\n#### `retry_messages(message_ids: Union[str, List[str]])`\n\nReturn messages to the queue for retry.\n\n```python\n# Retry single message\nclient.retry_messages(message_id)\n\n# Retry multiple messages  \nclient.retry_messages([id1, id2, id3])\n```\n\n#### `purge_queue()`\n\nClear all messages from the queue.\n\n```python\nclient.purge_queue()\n```\n\n### TLQMessage\n\nMessage objects returned by `get_messages()`:\n\n```python\n@dataclass\nclass TLQMessage:\n    id: str           # UUID v7 message identifier\n    body: str         # Message content\n    state: str        # Message state (e.g., \"Ready\", \"Processing\")\n    retry_count: int  # Number of retry attempts\n```\n\n## Error Handling\n\nThe client provides specific exception types for different error conditions:\n\n```python\nfrom tlq_client import (\n    TLQError,           # Base exception\n    TLQConnectionError, # Connection failures\n    TLQTimeoutError,    # Request timeouts\n    TLQServerError,     # Server errors (4xx, 5xx)\n    TLQValidationError  # Client-side validation errors\n)\n\ntry:\n    client.add_message(\"Hello, TLQ!\")\nexcept TLQValidationError as e:\n    print(f\"Validation error: {e}\")\nexcept TLQConnectionError as e:\n    print(f\"Connection error: {e}\")\nexcept TLQTimeoutError as e:\n    print(f\"Timeout error: {e}\")\nexcept TLQServerError as e:\n    print(f\"Server error: {e} (status: {e.status_code})\")\nexcept TLQError as e:\n    print(f\"TLQ error: {e}\")\n```\n\n## Context Manager Support\n\nThe client can be used as a context manager to ensure proper cleanup:\n\n```python\nwith TLQClient() as client:\n    message_id = client.add_message(\"Hello!\")\n    messages = client.get_messages()\n    # Session automatically closed when exiting context\n```\n\n## Examples\n\n### Basic Producer\n\n```python\nfrom tlq_client import TLQClient\n\ndef produce_messages():\n    with TLQClient() as client:\n        for i in range(10):\n            message_id = client.add_message(f\"Task {i}\")\n            print(f\"Queued task {i}: {message_id}\")\n\nif __name__ == \"__main__\":\n    produce_messages()\n```\n\n### Basic Consumer\n\n```python\nimport time\nfrom tlq_client import TLQClient, TLQError\n\ndef consume_messages():\n    with TLQClient() as client:\n        while True:\n            try:\n                messages = client.get_messages(count=5)\n                \n                if not messages:\n                    print(\"No messages available, sleeping...\")\n                    time.sleep(1)\n                    continue\n                \n                for message in messages:\n                    try:\n                        # Process the message\n                        print(f\"Processing: {message.body}\")\n                        time.sleep(0.1)  # Simulate work\n                        \n                        # Mark as completed\n                        client.delete_messages(message.id)\n                        print(f\"Completed: {message.id}\")\n                        \n                    except Exception as e:\n                        print(f\"Failed to process {message.id}: {e}\")\n                        # Return to queue for retry\n                        client.retry_messages(message.id)\n                        \n            except TLQError as e:\n                print(f\"TLQ error: {e}\")\n                time.sleep(5)  # Back off on errors\n\nif __name__ == \"__main__\":\n    consume_messages()\n```\n\n### Configuration from Environment\n\n```python\nimport os\nfrom tlq_client import TLQClient\n\n# Set environment variables\nos.environ['TLQ_HOST'] = 'queue.myapp.com'\nos.environ['TLQ_PORT'] = '8080'\nos.environ['TLQ_TIMEOUT'] = '60'\n\n# Client automatically picks up environment configuration\nclient = TLQClient()\nprint(f\"Connected to {client.config.base_url}\")\n```\n\n## Development\n\n### Setup Development Environment\n\n```bash\n# Create virtual environment (recommended on macOS/Linux to avoid system Python restrictions)\npython3 -m venv venv\n\n# Activate virtual environment\n# On macOS/Linux:\nsource venv/bin/activate\n# On Windows:\n# venv\\Scripts\\activate\n\n# Install development dependencies\npip install -e \".[dev]\"\n```\n\n### Running Tests\n\n```bash\n# Make sure virtual environment is activated\nsource venv/bin/activate\n\n# Run tests\npytest\n\n# Run tests with verbose output\npytest -v\n\n# Run tests with coverage\npytest --cov=tlq_client --cov-report=html\n\n# Run specific test file\npytest tests/test_client.py\n\n# Run specific test\npytest tests/test_client.py::TestTLQClient::test_add_message_success\n```\n\n### Code Quality\n\n```bash\n# Format code\nblack tlq_client tests\n\n# Sort imports  \nisort tlq_client tests\n\n# Lint code\nflake8 tlq_client tests\n\n# Type checking\nmypy tlq_client\n```\n\n## Requirements\n\n- Python 3.7+\n- requests >= 2.25.0\n\n## License\n\nMIT License - see [LICENSE](LICENSE) file for details.\n\n## Related Projects\n\n- [TLQ Server](https://github.com/skyaktech/tlq) - The TLQ message queue server\n- [TLQ Node.js Client](https://github.com/skyaktech/tlq-client-node) - Node.js client library\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python client library for TLQ (Tiny Little Queue)",
    "version": "0.2.0",
    "project_urls": {
        "Homepage": "https://github.com/skyaktech/tlq-client-py",
        "Issues": "https://github.com/skyaktech/tlq-client-py/issues",
        "Repository": "https://github.com/skyaktech/tlq-client-py"
    },
    "split_keywords": [
        "queue",
        " message-queue",
        " tlq",
        " microservices"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "3fd9ea75e11f1f7765ff8e841b7426f210bedbdca06a3e4545626c9448448cc4",
                "md5": "8c681960905273eac3cbc68904d765f4",
                "sha256": "f90f4e08d57bf6312486140c04d5b40b4ba6814eb3c598ffc53e5fc344ba9512"
            },
            "downloads": -1,
            "filename": "tlq_client-0.2.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "8c681960905273eac3cbc68904d765f4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 8256,
            "upload_time": "2025-08-21T14:56:46",
            "upload_time_iso_8601": "2025-08-21T14:56:46.199810Z",
            "url": "https://files.pythonhosted.org/packages/3f/d9/ea75e11f1f7765ff8e841b7426f210bedbdca06a3e4545626c9448448cc4/tlq_client-0.2.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "b6dc61a900eef4b5d2680a06b7e0e37a1f0a87e3524a96c9410c31646cbe556a",
                "md5": "22276cf446781a99f6678640b603f0dd",
                "sha256": "79f4b1dff1ee1e8a68897587615c44e2716e92e1dce29f198dfcd56cc7a06251"
            },
            "downloads": -1,
            "filename": "tlq_client-0.2.0.tar.gz",
            "has_sig": false,
            "md5_digest": "22276cf446781a99f6678640b603f0dd",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 12726,
            "upload_time": "2025-08-21T14:56:47",
            "upload_time_iso_8601": "2025-08-21T14:56:47.124996Z",
            "url": "https://files.pythonhosted.org/packages/b6/dc/61a900eef4b5d2680a06b7e0e37a1f0a87e3524a96c9410c31646cbe556a/tlq_client-0.2.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-08-21 14:56:47",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "skyaktech",
    "github_project": "tlq-client-py",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "tlq-client"
}
        
Elapsed time: 1.79405s