A lightweight async TCP server framework built on asyncio
Project description
aiosocket
A lightweight async TCP server framework built on Python's asyncio. Provides a decorator-based API for defining handlers, middleware, and filter-based routing — inspired by aiogram and FastAPI, but for raw TCP connections.
Requirements
Python 3.10+
Installation
pip install aiosocket-python
Quick Start
import asyncio
import aiosocket
server = aiosocket.AsyncTCPServer(host="127.0.0.1", port=8888)
@server.callback()
async def echo(reader: aiosocket.Reader, writer: aiosocket.Writer):
data = await reader.data()
await writer.send(data)
async def main():
await server.start()
await asyncio.Event().wait()
asyncio.run(main())
Filters
Filter routes connections by matching raw data against a regex, JSON fields, or both. Multiple filters on a single handler are evaluated in order and short-circuit on the first mismatch.
from aiosocket import AsyncTCPServer, Filter
server = AsyncTCPServer("127.0.0.1", 8888)
# Match raw bytes with a regex pattern
text_filter = Filter(pattern=r"^HELLO.*")
# Match a JSON field value
login_filter = Filter(action="login")
# Combine: must match both the pattern and the JSON field
strict_filter = Filter(pattern=r"^\{.*\}$", action="login")
@server.callback(login_filter)
async def handle_login(reader, writer):
payload = await reader.json()
await writer.send({"status": "ok", "user": payload["user"]})
@server.callback(text_filter)
async def handle_hello(reader, writer):
await writer.send(b"Hello to you too!\n")
Middleware
Every incoming connection runs all middleware whose filters match, in registration order, before any callback is invoked. Middleware can populate a shared data dict that is forwarded as keyword arguments to the matched callback.
@server.middleware()
async def log_request(reader, writer, data):
raw = await reader.data()
print(f"Received {len(raw)} bytes")
@server.middleware(login_filter)
async def authenticate(reader, writer, data):
payload = await reader.json()
data["user"] = payload.get("user")
@server.callback(login_filter)
async def greet(reader, writer, user=None):
await writer.send(f"Welcome, {user}!".encode())
Only the first callback whose filters match is invoked; subsequent callbacks are skipped.
Routers
Split your handlers across modules using Router, then mount them on the server.
from aiosocket import Router
router = Router()
@router.callback()
async def handle(reader, writer):
await writer.send(b"OK\n")
# in your main file:
server.include_router(router)
API Reference
AsyncTCPServer(host, port)
.callback(*filters)— register a connection handler; first match wins.middleware(*filters)— register middleware; all matches run before the callback.include_router(router)— merge aRouter's handlers into this server.start()— start listening (coroutine).stop()— gracefully shut down (coroutine)
Reader
.data() -> bytes— read up to 64 KiB; result is cached and concurrency-safe.json() -> dict— parse data as JSON; result is cached
Writer
.send(data: bytes | str | dict)— write and drain; dicts are JSON-serialized.close()— close the connection
Filter(pattern=None, **json_fields)
pattern— regex matched against the raw decoded bytes**json_fields— key/value pairs matched against the parsed JSON body
Router
.callback(*filters)— same asAsyncTCPServer.callback.middleware(*filters)— same asAsyncTCPServer.middleware
License
MIT
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file aiosocket_python-0.1.1.tar.gz.
File metadata
- Download URL: aiosocket_python-0.1.1.tar.gz
- Upload date:
- Size: 7.7 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
aae6b55675e3bcec2a07935dd22c58bd609d40324bde233631b331c507c8d2ac
|
|
| MD5 |
d20e68318b31025a15ba6155e8a2b773
|
|
| BLAKE2b-256 |
d7c4e282cc669661cd624e9f52df9f1d9dbeb489a52c16cc22d7d6b37213debb
|
File details
Details for the file aiosocket_python-0.1.1-py3-none-any.whl.
File metadata
- Download URL: aiosocket_python-0.1.1-py3-none-any.whl
- Upload date:
- Size: 7.6 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.2.0 CPython/3.13.11
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
dcb4f2c1da5b28143c236b1c3cc1aaa9ed54713f19dc465f8293b4983530258d
|
|
| MD5 |
0cd88046d945c3b389531273a6cb3d3e
|
|
| BLAKE2b-256 |
b14abf064683877de158fec23b800f714434ece250d14acd3414788a863bde3d
|