Skip to main content

The easiest way to use sockets in Python

Project description

EasyNetwork

The easiest way to use sockets in Python!

PyPI PyPI - License PyPI - Python Version

Test Documentation Status Codecov CodeFactor Grade

pre-commit pre-commit.ci status

Checked with mypy Code style: black Imports: isort security: bandit

Hatch project pdm-managed

Installation

From PyPI repository

pip install --user easynetwork

From source

git clone https://github.com/francis-clairicia/EasyNetwork.git
cd EasyNetwork
pip install --user .

Overview

EasyNetwork completely encapsulates the socket handling, providing you with a higher level interface that allows an application/software to completely handle the logic part with Python objects, without worrying about how to process, send or receive data over the network.

The communication protocol can be whatever you want, be it JSON, Pickle, ASCII, structure, base64 encoded, compressed, or any other format that is not part of the standard library. You choose the data format and the library takes care of the rest.

This project is especially useful for simple message exchange between clients and servers.

Works with TCP, UDP, and Unix sockets.

Interested ? Here is the documentation : https://easynetwork.readthedocs.io/

Usage

TCP Echo server with JSON data

import asyncio
import logging
from collections.abc import AsyncGenerator
from typing import Any, TypeAlias

from easynetwork.protocol import StreamProtocol
from easynetwork.serializers import JSONSerializer
from easynetwork.servers import AsyncTCPNetworkServer
from easynetwork.servers.handlers import AsyncStreamClient, AsyncStreamRequestHandler

# These TypeAliases are there to help you understand
# where requests and responses are used in the code
RequestType: TypeAlias = Any
ResponseType: TypeAlias = Any


class JSONProtocol(StreamProtocol[ResponseType, RequestType]):
    def __init__(self) -> None:
        super().__init__(JSONSerializer())


class EchoRequestHandler(AsyncStreamRequestHandler[RequestType, ResponseType]):
    def __init__(self) -> None:
        self.logger: logging.Logger = logging.getLogger(self.__class__.__name__)

    async def handle(
        self,
        client: AsyncStreamClient[ResponseType],
    ) -> AsyncGenerator[None, RequestType]:
        # A JSON request has been sent by this client
        data: Any = yield

        self.logger.info(f"{client!r} sent {data!r}")

        # As a good echo handler, the request is sent back to the client
        await client.send_packet(data)

        # Leaving the generator will NOT close the connection,
        # a new generator will be created afterwards.
        # You may manually close the connection if you want to:
        # await client.aclose()


async def main() -> None:
    host = None  # Bind on all interfaces
    port = 9000
    protocol = JSONProtocol()
    handler = EchoRequestHandler()

    logging.basicConfig(
        level=logging.INFO,
        format="[ %(levelname)s ] [ %(name)s ] %(message)s",
    )

    async with AsyncTCPNetworkServer(host, port, protocol, handler) as server:
        await server.serve_forever()


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except* KeyboardInterrupt:
        pass

TCP Echo client with JSON data

from typing import Any, TypeAlias

from easynetwork.clients import TCPNetworkClient
from easynetwork.protocol import StreamProtocol
from easynetwork.serializers import JSONSerializer

RequestType: TypeAlias = Any
ResponseType: TypeAlias = Any


class JSONProtocol(StreamProtocol[RequestType, ResponseType]):
    def __init__(self) -> None:
        super().__init__(JSONSerializer())


def main() -> None:
    with TCPNetworkClient(("localhost", 9000), JSONProtocol()) as client:
        client.send_packet({"data": {"my_body": ["as json"]}})
        response = client.recv_packet()  # response should be the sent dictionary
        print(response)  # prints {'data': {'my_body': ['as json']}}


if __name__ == "__main__":
    main()

Asynchronous version ( with async def )

import asyncio

from easynetwork.clients import AsyncTCPNetworkClient

...

async def main() -> None:
    async with AsyncTCPNetworkClient(("localhost", 9000), JSONProtocol()) as client:
        await client.send_packet({"data": {"my_body": ["as json"]}})
        response = await client.recv_packet()
        print(response)  # prints {'data': {'my_body': ['as json']}}


if __name__ == "__main__":
    asyncio.run(main())

License

This project is licensed under the terms of the Apache Software License 2.0.

AnyIO's typed attributes

AnyIO's typed attributes is incorporated in easynetwork.lowlevel.typed_attr from anyio 4.2, which is distributed under the MIT license.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

easynetwork-1.2.0.tar.gz (616.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

easynetwork-1.2.0-py3-none-any.whl (295.6 kB view details)

Uploaded Python 3

File details

Details for the file easynetwork-1.2.0.tar.gz.

File metadata

  • Download URL: easynetwork-1.2.0.tar.gz
  • Upload date:
  • Size: 616.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for easynetwork-1.2.0.tar.gz
Algorithm Hash digest
SHA256 fc1ce254c38083ba52ba6bbaf0fa20c9059547ecc25946a44da49f177e864897
MD5 34c9536d698d2be5d168b206058c9daf
BLAKE2b-256 b814b0a28fb68d69c087d6ac066671ecebcdfa6ffe37fd34ee0d87125333e12b

See more details on using hashes here.

Provenance

The following attestation bundles were made for easynetwork-1.2.0.tar.gz:

Publisher: release.yml on francis-clairicia/EasyNetwork

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file easynetwork-1.2.0-py3-none-any.whl.

File metadata

  • Download URL: easynetwork-1.2.0-py3-none-any.whl
  • Upload date:
  • Size: 295.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for easynetwork-1.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 aa245eb7c7799087b264784822a1aeb35471f82e53dc01d5408f4946a445d0a0
MD5 704b45a1db802e9aeea424e3b47a4d74
BLAKE2b-256 761c7cc50640690f0cd9ba47d2a77b73e713eb69e63dc99ad176d876b1caa83f

See more details on using hashes here.

Provenance

The following attestation bundles were made for easynetwork-1.2.0-py3-none-any.whl:

Publisher: release.yml on francis-clairicia/EasyNetwork

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page