easynetwork


Nameeasynetwork JSON
Version 1.0.0rc8 PyPI version JSON
download
home_pageNone
SummaryThe easiest way to use sockets in Python
upload_time2024-04-06 16:59:27
maintainerNone
docs_urlNone
authorNone
requires_python>=3.11
licenseNone
keywords async asynchronous client communication networking serialization server socket
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # EasyNetwork

The easiest way to use sockets in Python!

[![PyPI](https://img.shields.io/pypi/v/easynetwork)](https://pypi.org/project/easynetwork/)
[![PyPI - License](https://img.shields.io/pypi/l/easynetwork)](https://github.com/francis-clairicia/EasyNetwork/blob/main/LICENSE)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/easynetwork)

[![Test](https://github.com/francis-clairicia/EasyNetwork/actions/workflows/test.yml/badge.svg)](https://github.com/francis-clairicia/EasyNetwork/actions/workflows/test.yml)
[![Documentation Status](https://readthedocs.org/projects/easynetwork/badge/?version=latest)](https://easynetwork.readthedocs.io/en/latest/?badge=latest)
[![Codecov](https://img.shields.io/codecov/c/github/francis-clairicia/EasyNetwork)](https://codecov.io/gh/francis-clairicia/EasyNetwork)
[![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/francis-clairicia/EasyNetwork)](https://www.codefactor.io/repository/github/francis-clairicia/easynetwork)

[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/francis-clairicia/EasyNetwork/main.svg)](https://results.pre-commit.ci/latest/github/francis-clairicia/EasyNetwork/main)

[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)
[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)
[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)

[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)
[![pdm-managed](https://img.shields.io/badge/pdm-managed-blueviolet)](https://pdm.fming.dev)

## Installation
### From PyPI repository
```sh
pip install --user easynetwork
```

### From source
```sh
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
```py
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
```py
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()
```

<details markdown="1">
<summary>Asynchronous version ( with <code>async def</code> )</summary>

```py
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())
```

</details>

## License
This project is licensed under the terms of the [Apache Software License 2.0](https://github.com/francis-clairicia/EasyNetwork/blob/main/LICENSE).

### `easynetwork.lowlevel.typed_attr`

AnyIO's typed attributes incorporated in `easynetwork.lowlevel.typed_attr` from [anyio 4.2](https://github.com/agronholm/anyio/tree/4.2.0), 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.
```

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "easynetwork",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.11",
    "maintainer_email": null,
    "keywords": "async, asynchronous, client, communication, networking, serialization, server, socket",
    "author": null,
    "author_email": "FrankySnow9 <clairicia.rcj.francis@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/a0/13/183877a141e78b2773a7dbdca8e245fa92025432927ee1705d5f8a58008e/easynetwork-1.0.0rc8.tar.gz",
    "platform": null,
    "description": "# EasyNetwork\n\nThe easiest way to use sockets in Python!\n\n[![PyPI](https://img.shields.io/pypi/v/easynetwork)](https://pypi.org/project/easynetwork/)\n[![PyPI - License](https://img.shields.io/pypi/l/easynetwork)](https://github.com/francis-clairicia/EasyNetwork/blob/main/LICENSE)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/easynetwork)\n\n[![Test](https://github.com/francis-clairicia/EasyNetwork/actions/workflows/test.yml/badge.svg)](https://github.com/francis-clairicia/EasyNetwork/actions/workflows/test.yml)\n[![Documentation Status](https://readthedocs.org/projects/easynetwork/badge/?version=latest)](https://easynetwork.readthedocs.io/en/latest/?badge=latest)\n[![Codecov](https://img.shields.io/codecov/c/github/francis-clairicia/EasyNetwork)](https://codecov.io/gh/francis-clairicia/EasyNetwork)\n[![CodeFactor Grade](https://img.shields.io/codefactor/grade/github/francis-clairicia/EasyNetwork)](https://www.codefactor.io/repository/github/francis-clairicia/easynetwork)\n\n[![pre-commit](https://img.shields.io/badge/pre--commit-enabled-brightgreen?logo=pre-commit)](https://github.com/pre-commit/pre-commit)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/francis-clairicia/EasyNetwork/main.svg)](https://results.pre-commit.ci/latest/github/francis-clairicia/EasyNetwork/main)\n\n[![Checked with mypy](http://www.mypy-lang.org/static/mypy_badge.svg)](http://mypy-lang.org/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://pycqa.github.io/isort/)\n[![security: bandit](https://img.shields.io/badge/security-bandit-yellow.svg)](https://github.com/PyCQA/bandit)\n\n[![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)\n[![pdm-managed](https://img.shields.io/badge/pdm-managed-blueviolet)](https://pdm.fming.dev)\n\n## Installation\n### From PyPI repository\n```sh\npip install --user easynetwork\n```\n\n### From source\n```sh\ngit clone https://github.com/francis-clairicia/EasyNetwork.git\ncd EasyNetwork\npip install --user .\n```\n\n## Overview\nEasyNetwork completely encapsulates the socket handling, providing you with a higher level interface\nthat allows an application/software to completely handle the logic part with Python objects,\nwithout worrying about how to process, send or receive data over the network.\n\nThe communication protocol can be whatever you want, be it JSON, Pickle, ASCII, structure, base64 encoded,\ncompressed, or any other format that is not part of the standard library.\nYou choose the data format and the library takes care of the rest.\n\nThis project is especially useful for simple **message** exchange between clients and servers.\n\nWorks with TCP and UDP.\n\nInterested ? Here is the documentation : https://easynetwork.readthedocs.io/\n\n## Usage\n### TCP Echo server with JSON data\n```py\nimport asyncio\nimport logging\nfrom collections.abc import AsyncGenerator\nfrom typing import Any, TypeAlias\n\nfrom easynetwork.protocol import StreamProtocol\nfrom easynetwork.serializers import JSONSerializer\nfrom easynetwork.servers import AsyncTCPNetworkServer\nfrom easynetwork.servers.handlers import AsyncStreamClient, AsyncStreamRequestHandler\n\n# These TypeAliases are there to help you understand\n# where requests and responses are used in the code\nRequestType: TypeAlias = Any\nResponseType: TypeAlias = Any\n\n\nclass JSONProtocol(StreamProtocol[ResponseType, RequestType]):\n    def __init__(self) -> None:\n        super().__init__(JSONSerializer())\n\n\nclass EchoRequestHandler(AsyncStreamRequestHandler[RequestType, ResponseType]):\n    def __init__(self) -> None:\n        self.logger: logging.Logger = logging.getLogger(self.__class__.__name__)\n\n    async def handle(\n        self,\n        client: AsyncStreamClient[ResponseType],\n    ) -> AsyncGenerator[None, RequestType]:\n        data: Any = yield  # A JSON request has been sent by this client\n\n        self.logger.info(f\"{client!r} sent {data!r}\")\n\n        # As a good echo handler, the request is sent back to the client\n        await client.send_packet(data)\n\n        # Leaving the generator will NOT close the connection,\n        # a new generator will be created afterwards.\n        # You may manually close the connection if you want to:\n        # await client.aclose()\n\n\nasync def main() -> None:\n    host = None  # Bind on all interfaces\n    port = 9000\n    protocol = JSONProtocol()\n    handler = EchoRequestHandler()\n\n    logging.basicConfig(\n        level=logging.INFO,\n        format=\"[ %(levelname)s ] [ %(name)s ] %(message)s\",\n    )\n\n    async with AsyncTCPNetworkServer(host, port, protocol, handler) as server:\n        try:\n            await server.serve_forever()\n        except asyncio.CancelledError:\n            pass\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n### TCP Echo client with JSON data\n```py\nfrom typing import Any, TypeAlias\n\nfrom easynetwork.clients import TCPNetworkClient\nfrom easynetwork.protocol import StreamProtocol\nfrom easynetwork.serializers import JSONSerializer\n\nRequestType: TypeAlias = Any\nResponseType: TypeAlias = Any\n\n\nclass JSONProtocol(StreamProtocol[RequestType, ResponseType]):\n    def __init__(self) -> None:\n        super().__init__(JSONSerializer())\n\n\ndef main() -> None:\n    with TCPNetworkClient((\"localhost\", 9000), JSONProtocol()) as client:\n        client.send_packet({\"data\": {\"my_body\": [\"as json\"]}})\n        response = client.recv_packet()  # response should be the sent dictionary\n        print(response)  # prints {'data': {'my_body': ['as json']}}\n\n\nif __name__ == \"__main__\":\n    main()\n```\n\n<details markdown=\"1\">\n<summary>Asynchronous version ( with <code>async def</code> )</summary>\n\n```py\nimport asyncio\n\nfrom easynetwork.clients import AsyncTCPNetworkClient\n\n...\n\nasync def main() -> None:\n    async with AsyncTCPNetworkClient((\"localhost\", 9000), JSONProtocol()) as client:\n        await client.send_packet({\"data\": {\"my_body\": [\"as json\"]}})\n        response = await client.recv_packet()  # response should be the sent dictionary\n        print(response)  # prints {'data': {'my_body': ['as json']}}\n\n\nif __name__ == \"__main__\":\n    asyncio.run(main())\n```\n\n</details>\n\n## License\nThis project is licensed under the terms of the [Apache Software License 2.0](https://github.com/francis-clairicia/EasyNetwork/blob/main/LICENSE).\n\n### `easynetwork.lowlevel.typed_attr`\n\nAnyIO's typed attributes incorporated in `easynetwork.lowlevel.typed_attr` from [anyio 4.2](https://github.com/agronholm/anyio/tree/4.2.0), which is distributed under the MIT license:\n```\nCopyright (c) 2018 Alex Gr\u00f6nholm\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n```\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "The easiest way to use sockets in Python",
    "version": "1.0.0rc8",
    "project_urls": {
        "Documentation": "https://easynetwork.readthedocs.io/",
        "Issue Tracker": "https://github.com/francis-clairicia/EasyNetwork/issues",
        "Release Notes": "https://github.com/francis-clairicia/EasyNetwork/releases",
        "Source Code": "https://github.com/francis-clairicia/EasyNetwork"
    },
    "split_keywords": [
        "async",
        " asynchronous",
        " client",
        " communication",
        " networking",
        " serialization",
        " server",
        " socket"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "06b1b86ce916ac89c7afda7d94f0a70235cda2da8ad4ec73d4b85ff23fe04334",
                "md5": "97f71ad6198a97c15c4f25088aa2da80",
                "sha256": "8413c8d9711ee02e4a3331692ce56c741a24fd7aca99cabae4969906ac662108"
            },
            "downloads": -1,
            "filename": "easynetwork-1.0.0rc8-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "97f71ad6198a97c15c4f25088aa2da80",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.11",
            "size": 198201,
            "upload_time": "2024-04-06T16:59:25",
            "upload_time_iso_8601": "2024-04-06T16:59:25.143471Z",
            "url": "https://files.pythonhosted.org/packages/06/b1/b86ce916ac89c7afda7d94f0a70235cda2da8ad4ec73d4b85ff23fe04334/easynetwork-1.0.0rc8-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a013183877a141e78b2773a7dbdca8e245fa92025432927ee1705d5f8a58008e",
                "md5": "356ef5be8864bf9e3d020b363b873601",
                "sha256": "ad71e880161c30a3f832e1500f8798178d33844277a915605d463f39a4a7aec9"
            },
            "downloads": -1,
            "filename": "easynetwork-1.0.0rc8.tar.gz",
            "has_sig": false,
            "md5_digest": "356ef5be8864bf9e3d020b363b873601",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.11",
            "size": 371063,
            "upload_time": "2024-04-06T16:59:27",
            "upload_time_iso_8601": "2024-04-06T16:59:27.064131Z",
            "url": "https://files.pythonhosted.org/packages/a0/13/183877a141e78b2773a7dbdca8e245fa92025432927ee1705d5f8a58008e/easynetwork-1.0.0rc8.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-04-06 16:59:27",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "francis-clairicia",
    "github_project": "EasyNetwork",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "tox": true,
    "lcname": "easynetwork"
}
        
Elapsed time: 0.22574s