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 and UDP.

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]:
        data: Any = yield  # A JSON request has been sent by this client

        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:
        try:
            await server.serve_forever()
        except asyncio.CancelledError:
            pass


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

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()  # response should be the sent dictionary
        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.

easynetwork.lowlevel.typed_attr

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

Copyright (c) 2018 Alex Grönholm

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

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.0.0rc8.tar.gz (371.1 kB view hashes)

Uploaded Source

Built Distribution

easynetwork-1.0.0rc8-py3-none-any.whl (198.2 kB view hashes)

Uploaded Python 3

Supported by

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