# PI func -> Protocol Interface Functions
PIfunc revolutionizes how you build networked applications by letting you **write your function once** and expose it via **multiple communication protocols simultaneously**. No duplicate code. No inconsistencies. Just clean, maintainable, protocol-agnostic code.
## ๐ Examples
### Parameter Handling
```python
@service(
http={"path": "/api/products", "method": "POST"},
mqtt={"topic": "products/create"}
)
def create_product(product: dict) -> dict:
"""Create a new product.
Note: When working with dictionary parameters, use `dict` instead of `Dict`
for better type handling across protocols.
"""
return {
"id": product["id"],
"name": product["name"],
"price": product["price"],
"in_stock": product.get("in_stock", True)
}
# Call via HTTP:
# POST /api/products
# {"product": {"id": "123", "name": "Widget", "price": 99.99}}
# Call via MQTT:
# Topic: products/create
# Payload: {"product": {"id": "123", "name": "Widget", "price": 99.99}}
```
4. Or use the CLI:
```bash
pifunc call add --protocol http --args '{"a": 5, "b": 3}'
# 8
```
## kill
```bash
pkill -f "python calculator.py" && python calculator.py
```
## โจ Features
- **Multi-Protocol Support**: Expose functions via HTTP/REST, gRPC, MQTT, WebSocket, and GraphQL
- **Zero Boilerplate**: Single decorator approach with sensible defaults
- **Type Safety**: Automatic type validation and conversion
- **Hot Reload**: Instant updates during development
- **Protocol-Specific Configurations**: Fine-tune each protocol interface
- **Automatic Documentation**: OpenAPI, gRPC reflection, and GraphQL introspection
- **Comprehensive CLI**: Manage and test your services with ease
- **Monitoring & Health Checks**: Built-in observability
- **Enterprise-Ready**: Authentication, authorization, and middleware support
## ๐ Supported Protocols
| Protocol | Description | Best For |
|----------|-------------|----------|
| **HTTP/REST** | RESTful API with JSON | Web clients, general API access |
| **gRPC** | High-performance RPC | Microservices, performance-critical systems |
| **MQTT** | Lightweight pub/sub | IoT devices, mobile apps |
| **WebSocket** | Bidirectional comms | Real-time applications, chat |
| **GraphQL** | Query language | Flexible data requirements |
## ๐ Examples
### Advanced Configuration
```python
@service(
# HTTP configuration
http={
"path": "/api/users/{user_id}",
"method": "GET",
"middleware": [auth_middleware, logging_middleware]
},
# MQTT configuration
mqtt={
"topic": "users/get",
"qos": 1,
"retain": False
},
# WebSocket configuration
websocket={
"event": "user.get",
"namespace": "/users"
},
# GraphQL configuration
graphql={
"field_name": "user",
"description": "Get user by ID"
}
)
def get_user(user_id: str) -> dict: # Use dict instead of Dict
"""Get user details by ID."""
return db.get_user(user_id)
```
### Debugging and Logging
PIfunc provides detailed logging for both HTTP and MQTT adapters to help with debugging:
```python
import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
@service(
grpc={"streaming": True},
websocket={"event": "monitoring.metrics"}
http={"path": "/api/data", "method": "POST"},
mqtt={"topic": "data/process"}
)
async def stream_metrics(interval: int = 1):
"""Stream system metrics."""
while True:
metrics = get_system_metrics()
yield metrics
await asyncio.sleep(interval)
```
### Working with Complex Types
```python
@dataclass
class Product:
id: str
name: str
price: float
in_stock: bool
@service()
def create_product(product: Product) -> Product:
"""Create a new product."""
# PIfunc automatically converts JSON to your dataclass
product.id = generate_id()
db.save_product(product)
return product
```
## ๐ ๏ธ CLI Usage
PIfunc includes a CLI for interacting with your services:
```bash
# Call a function via HTTP (default protocol)
pifunc call add --args '{"a": 5, "b": 3}'
# Call a function with specific protocol
pifunc call add --protocol http --args '{"a": 5, "b": 3}'
# Get help
pifunc --help
pifunc call --help
```
Note: Additional CLI features like service management, client code generation, documentation viewing, and benchmarking are coming in future releases.
## ๐ Documentation
Comprehensive documentation is available at [https://www.pifunc.com/docs](https://www.pifunc.com/docs)
- [API Reference](https://www.pifunc.com/docs/api-reference)
- [Protocol Configurations](https://www.pifunc.com/docs/protocols)
- [Advanced Usage](https://www.pifunc.com/docs/advanced)
- [Deployment Guide](https://www.pifunc.com/docs/deployment)
- [Extending PIfunc](https://www.pifunc.com/docs/extending)
def process_data(data: dict) -> dict:
"""Process data with detailed logging."""
return {"processed": data}
## ๐งช Testing
PIfunc includes a comprehensive test suite that ensures reliability across all supported protocols and features:
### CLI Tests
- Command-line interface functionality
- Protocol-specific service calls
- Error handling and edge cases
- Help command documentation
### Service Tests
- Service decorator functionality
- Protocol-specific configurations (HTTP, MQTT, WebSocket)
- Complex data type handling
- Async function support
- Middleware integration
### HTTP Adapter Tests
- Route registration and handling
- Parameter parsing (path, query, body)
- Request/response processing
- Error handling
- CORS support
- Middleware execution
### Integration Tests
- Cross-protocol communication
- Real-world service scenarios
- Data streaming capabilities
- Multi-protocol support validation
```bash
python -m venv venv && source venv/bin/activate && pip install -r requirements.txt -r requirements-dev.txt && python3 -m pip install -e .
# Logs will show:
# - Incoming request/message details
# - Parameter conversion steps
# - Function execution details
# - Response/publication details
# - Any errors or issues that occur
```
To run the tests:
```bash
# Install development dependencies
pip install -r requirements-dev.txt
# Run all tests
python -m pytest -v
pytest
# Run specific test categories
pytest tests/test_cli.py
pytest tests/test_service.py
pytest tests/test_http_adapter.py
pytest tests/test_integration.py
```
## PUBLISH
```bash
python -m venv venv && source venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt
```
```bash
sudo pip install --upgrade pip build twine
pip install --upgrade pip build twine
python -m build
twine check dist/*
twine upload dist/*
```
## ๐ค Contributing
Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for how to get started.
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request
## ๐ License
PIfunc is licensed under the Apache License 2.0. See [LICENSE](LICENSE) for details.
Generate directory structures from ASCII art or Markdown files.
See [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.
---
<div align="center">
<img src="assets/logo.svg" alt="PIfunc Logo" width="200">
<h1>PIfunc</h1>
<p><strong>Protocol Interface Functions</strong></p>
<p>One function, every protocol. Everywhere.</p>
<p>
<a href="#installation"><strong>Installation</strong></a> โข
<a href="#quick-start"><strong>Quick Start</strong></a> โข
<a href="#features"><strong>Features</strong></a> โข
<a href="#examples"><strong>Examples</strong></a> โข
<a href="#documentation"><strong>Documentation</strong></a> โข
<a href="#contributing"><strong>Contributing</strong></a> โข
<a href="#license"><strong>License</strong></a>
</p>
<p>
<a href="https://github.com/pifunc/pifunc/actions">
<img src="https://github.com/pifunc/pifunc/workflows/Tests/badge.svg" alt="Tests">
</a>
<a href="https://pypi.org/project/pifunc/">
<img src="https://img.shields.io/pypi/v/pifunc.svg" alt="PyPI">
</a>
<a href="https://pepy.tech/project/pifunc">
<img src="https://pepy.tech/badge/pifunc" alt="Downloads">
</a>
<a href="https://github.com/pifunc/pifunc/blob/main/LICENSE">
<img src="https://img.shields.io/github/license/pifunc/pifunc.svg" alt="License">
</a>
<a href="https://discord.gg/pifunc">
<img src="https://img.shields.io/discord/1156621449362239529?color=7289da&label=discord&logo=discord&logoColor=white" alt="Discord">
</a>
</p>
</div>
---
---
---
<div align="center">
<p>Built with โค๏ธ by the PIfunc team and contributors</p>
<p>
<a href="https://www.pifunc.com">Website</a> โข
<a href="https://twitter.com/pifunc">Twitter</a> โข
<a href="https://discord.gg/pifunc">Discord</a>
</p>
</div>
Raw data
{
"_id": null,
"home_page": "https://github.com/pi-func/pifunc",
"name": "pifunc",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.11",
"maintainer_email": null,
"keywords": null,
"author": "Tom Sapletta",
"author_email": "info@softreck.dev",
"download_url": "https://files.pythonhosted.org/packages/df/5e/e2c54e2748dfa2169b4e887d2140669caa769fc81c7479d633583bc4053d/pifunc-0.1.7.tar.gz",
"platform": null,
"description": "# PI func -> Protocol Interface Functions\n\nPIfunc revolutionizes how you build networked applications by letting you **write your function once** and expose it via **multiple communication protocols simultaneously**. No duplicate code. No inconsistencies. Just clean, maintainable, protocol-agnostic code.\n\n\n## \ud83d\udcda Examples\n\n### Parameter Handling\n\n```python\n@service(\n http={\"path\": \"/api/products\", \"method\": \"POST\"},\n mqtt={\"topic\": \"products/create\"}\n)\ndef create_product(product: dict) -> dict:\n \"\"\"Create a new product.\n \n Note: When working with dictionary parameters, use `dict` instead of `Dict`\n for better type handling across protocols.\n \"\"\"\n return {\n \"id\": product[\"id\"],\n \"name\": product[\"name\"],\n \"price\": product[\"price\"],\n \"in_stock\": product.get(\"in_stock\", True)\n }\n\n# Call via HTTP:\n# POST /api/products\n# {\"product\": {\"id\": \"123\", \"name\": \"Widget\", \"price\": 99.99}}\n\n# Call via MQTT:\n# Topic: products/create\n# Payload: {\"product\": {\"id\": \"123\", \"name\": \"Widget\", \"price\": 99.99}}\n```\n\n4. Or use the CLI:\n\n```bash\npifunc call add --protocol http --args '{\"a\": 5, \"b\": 3}'\n# 8\n```\n\n\n## kill\n\n```bash\npkill -f \"python calculator.py\" && python calculator.py\n```\n\n## \u2728 Features\n\n- **Multi-Protocol Support**: Expose functions via HTTP/REST, gRPC, MQTT, WebSocket, and GraphQL\n- **Zero Boilerplate**: Single decorator approach with sensible defaults\n- **Type Safety**: Automatic type validation and conversion\n- **Hot Reload**: Instant updates during development\n- **Protocol-Specific Configurations**: Fine-tune each protocol interface\n- **Automatic Documentation**: OpenAPI, gRPC reflection, and GraphQL introspection\n- **Comprehensive CLI**: Manage and test your services with ease\n- **Monitoring & Health Checks**: Built-in observability\n- **Enterprise-Ready**: Authentication, authorization, and middleware support\n\n## \ud83d\udd0c Supported Protocols\n\n| Protocol | Description | Best For |\n|----------|-------------|----------|\n| **HTTP/REST** | RESTful API with JSON | Web clients, general API access |\n| **gRPC** | High-performance RPC | Microservices, performance-critical systems |\n| **MQTT** | Lightweight pub/sub | IoT devices, mobile apps |\n| **WebSocket** | Bidirectional comms | Real-time applications, chat |\n| **GraphQL** | Query language | Flexible data requirements |\n\n## \ud83d\udcda Examples\n\n### Advanced Configuration\n\n```python\n@service(\n # HTTP configuration\n http={\n \"path\": \"/api/users/{user_id}\",\n \"method\": \"GET\",\n \"middleware\": [auth_middleware, logging_middleware]\n },\n # MQTT configuration\n mqtt={\n \"topic\": \"users/get\",\n \"qos\": 1,\n \"retain\": False\n },\n # WebSocket configuration\n websocket={\n \"event\": \"user.get\",\n \"namespace\": \"/users\"\n },\n # GraphQL configuration\n graphql={\n \"field_name\": \"user\",\n \"description\": \"Get user by ID\"\n }\n)\ndef get_user(user_id: str) -> dict: # Use dict instead of Dict\n \"\"\"Get user details by ID.\"\"\"\n return db.get_user(user_id)\n```\n\n### Debugging and Logging\n\nPIfunc provides detailed logging for both HTTP and MQTT adapters to help with debugging:\n\n```python\nimport logging\n\n# Enable debug logging\nlogging.basicConfig(level=logging.DEBUG)\n\n@service(\n grpc={\"streaming\": True},\n websocket={\"event\": \"monitoring.metrics\"}\n http={\"path\": \"/api/data\", \"method\": \"POST\"},\n mqtt={\"topic\": \"data/process\"}\n)\nasync def stream_metrics(interval: int = 1):\n \"\"\"Stream system metrics.\"\"\"\n while True:\n metrics = get_system_metrics()\n yield metrics\n await asyncio.sleep(interval)\n```\n\n### Working with Complex Types\n\n```python\n@dataclass\nclass Product:\n id: str\n name: str\n price: float\n in_stock: bool\n\n@service()\ndef create_product(product: Product) -> Product:\n \"\"\"Create a new product.\"\"\"\n # PIfunc automatically converts JSON to your dataclass\n product.id = generate_id()\n db.save_product(product)\n return product\n```\n\n## \ud83d\udee0\ufe0f CLI Usage\n\nPIfunc includes a CLI for interacting with your services:\n\n```bash\n# Call a function via HTTP (default protocol)\npifunc call add --args '{\"a\": 5, \"b\": 3}'\n\n# Call a function with specific protocol\npifunc call add --protocol http --args '{\"a\": 5, \"b\": 3}'\n\n# Get help\npifunc --help\npifunc call --help\n```\n\nNote: Additional CLI features like service management, client code generation, documentation viewing, and benchmarking are coming in future releases.\n\n## \ud83d\udcd6 Documentation\n\nComprehensive documentation is available at [https://www.pifunc.com/docs](https://www.pifunc.com/docs)\n\n- [API Reference](https://www.pifunc.com/docs/api-reference)\n- [Protocol Configurations](https://www.pifunc.com/docs/protocols)\n- [Advanced Usage](https://www.pifunc.com/docs/advanced)\n- [Deployment Guide](https://www.pifunc.com/docs/deployment)\n- [Extending PIfunc](https://www.pifunc.com/docs/extending)\ndef process_data(data: dict) -> dict:\n \"\"\"Process data with detailed logging.\"\"\"\n return {\"processed\": data}\n\n## \ud83e\uddea Testing\n\nPIfunc includes a comprehensive test suite that ensures reliability across all supported protocols and features:\n\n### CLI Tests\n- Command-line interface functionality\n- Protocol-specific service calls\n- Error handling and edge cases\n- Help command documentation\n\n### Service Tests\n- Service decorator functionality\n- Protocol-specific configurations (HTTP, MQTT, WebSocket)\n- Complex data type handling\n- Async function support\n- Middleware integration\n\n### HTTP Adapter Tests\n- Route registration and handling\n- Parameter parsing (path, query, body)\n- Request/response processing\n- Error handling\n- CORS support\n- Middleware execution\n\n### Integration Tests\n- Cross-protocol communication\n- Real-world service scenarios\n- Data streaming capabilities\n- Multi-protocol support validation\n\n```bash\npython -m venv venv && source venv/bin/activate && pip install -r requirements.txt -r requirements-dev.txt && python3 -m pip install -e .\n# Logs will show:\n# - Incoming request/message details\n# - Parameter conversion steps\n# - Function execution details\n# - Response/publication details\n# - Any errors or issues that occur\n```\n\nTo run the tests:\n\n```bash\n# Install development dependencies\npip install -r requirements-dev.txt\n\n# Run all tests\npython -m pytest -v\npytest\n\n# Run specific test categories\npytest tests/test_cli.py\npytest tests/test_service.py\npytest tests/test_http_adapter.py\npytest tests/test_integration.py\n```\n\n\n## PUBLISH\n\n\n```bash\npython -m venv venv && source venv/bin/activate && pip install --upgrade pip && pip install -r requirements.txt\n```\n\n```bash\nsudo pip install --upgrade pip build twine\npip install --upgrade pip build twine\npython -m build\ntwine check dist/*\ntwine upload dist/*\n```\n\n## \ud83e\udd1d Contributing\n\nContributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for how to get started.\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## \ud83d\udcc4 License\n\nPIfunc is licensed under the Apache License 2.0. See [LICENSE](LICENSE) for details.\n\n\n\nGenerate directory structures from ASCII art or Markdown files.\n\nSee [CONTRIBUTING.md](CONTRIBUTING.md) for details on how to contribute to this project.\n\n---\n\n<div align=\"center\">\n <img src=\"assets/logo.svg\" alt=\"PIfunc Logo\" width=\"200\">\n <h1>PIfunc</h1>\n <p><strong>Protocol Interface Functions</strong></p>\n <p>One function, every protocol. Everywhere.</p>\n \n <p>\n <a href=\"#installation\"><strong>Installation</strong></a> \u2022\n <a href=\"#quick-start\"><strong>Quick Start</strong></a> \u2022\n <a href=\"#features\"><strong>Features</strong></a> \u2022\n <a href=\"#examples\"><strong>Examples</strong></a> \u2022\n <a href=\"#documentation\"><strong>Documentation</strong></a> \u2022\n <a href=\"#contributing\"><strong>Contributing</strong></a> \u2022\n <a href=\"#license\"><strong>License</strong></a>\n </p>\n \n <p>\n <a href=\"https://github.com/pifunc/pifunc/actions\">\n <img src=\"https://github.com/pifunc/pifunc/workflows/Tests/badge.svg\" alt=\"Tests\">\n </a>\n <a href=\"https://pypi.org/project/pifunc/\">\n <img src=\"https://img.shields.io/pypi/v/pifunc.svg\" alt=\"PyPI\">\n </a>\n <a href=\"https://pepy.tech/project/pifunc\">\n <img src=\"https://pepy.tech/badge/pifunc\" alt=\"Downloads\">\n </a>\n <a href=\"https://github.com/pifunc/pifunc/blob/main/LICENSE\">\n <img src=\"https://img.shields.io/github/license/pifunc/pifunc.svg\" alt=\"License\">\n </a>\n <a href=\"https://discord.gg/pifunc\">\n <img src=\"https://img.shields.io/discord/1156621449362239529?color=7289da&label=discord&logo=discord&logoColor=white\" alt=\"Discord\">\n </a>\n </p>\n</div>\n\n\n---\n\n---\n\n---\n\n<div align=\"center\">\n <p>Built with \u2764\ufe0f by the PIfunc team and contributors</p>\n <p>\n <a href=\"https://www.pifunc.com\">Website</a> \u2022\n <a href=\"https://twitter.com/pifunc\">Twitter</a> \u2022\n <a href=\"https://discord.gg/pifunc\">Discord</a>\n </p>\n</div>\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Generate directory structure from ASCII art or Markdown files",
"version": "0.1.7",
"project_urls": {
"Homepage": "https://github.com/pi-func/pifunc"
},
"split_keywords": [],
"urls": [
{
"comment_text": null,
"digests": {
"blake2b_256": "c029819b34b550fdeb6e9459fea36291c844ace8809d613753afc7ec6c97d862",
"md5": "e72875a47e8e32be01a8284afd0bb6ca",
"sha256": "f64aa00dded34cc2afe8930ee61cdb2a783b3cb1a3f265cc22d32bb09faae9cd"
},
"downloads": -1,
"filename": "pifunc-0.1.7-py3-none-any.whl",
"has_sig": false,
"md5_digest": "e72875a47e8e32be01a8284afd0bb6ca",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.11",
"size": 33253,
"upload_time": "2025-03-19T21:44:00",
"upload_time_iso_8601": "2025-03-19T21:44:00.789414Z",
"url": "https://files.pythonhosted.org/packages/c0/29/819b34b550fdeb6e9459fea36291c844ace8809d613753afc7ec6c97d862/pifunc-0.1.7-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": null,
"digests": {
"blake2b_256": "df5ee2c54e2748dfa2169b4e887d2140669caa769fc81c7479d633583bc4053d",
"md5": "14126c988b30e3a355ce93cfc341c7bb",
"sha256": "999bd5bce5578d0bd60b2df542eda250cfafeca75db6435701524c9b67ed7868"
},
"downloads": -1,
"filename": "pifunc-0.1.7.tar.gz",
"has_sig": false,
"md5_digest": "14126c988b30e3a355ce93cfc341c7bb",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.11",
"size": 123544,
"upload_time": "2025-03-19T21:44:02",
"upload_time_iso_8601": "2025-03-19T21:44:02.448624Z",
"url": "https://files.pythonhosted.org/packages/df/5e/e2c54e2748dfa2169b4e887d2140669caa769fc81c7479d633583bc4053d/pifunc-0.1.7.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2025-03-19 21:44:02",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "pi-func",
"github_project": "pifunc",
"github_not_found": true,
"lcname": "pifunc"
}