# -*- coding: utf-8 -*-
from setuptools import setup

packages = \
['pjrpc',
 'pjrpc.client',
 'pjrpc.client.backend',
 'pjrpc.client.integrations',
 'pjrpc.common',
 'pjrpc.server',
 'pjrpc.server.integration',
 'pjrpc.server.integration.django',
 'pjrpc.server.specs',
 'pjrpc.server.specs.extractors',
 'pjrpc.server.validators']

package_data = \
{'': ['*']}

extras_require = \
{'aio-pika': ['aio-pika>=6.8,<7.0'],
 'aiohttp': ['aiohttp>=3.7,<4.0'],
 'django': ['django>=3.0,<4.0'],
 'docgen': ['aio-pika>=6.8,<7.0',
            'aiohttp>=3.7,<4.0',
            'flask>=1.1.3',
            'jsonschema>=3.0,<4.0',
            'kombu>=5.1,<6.0',
            'pydantic>=1.7.0,<2.0.0',
            'requests>=2.0,<3.0',
            'sphinx>=4.5,<5.0'],
 'docstring-parser': ['docstring-parser>=0.8,<0.9'],
 'flask': ['flask>=1.1.3', 'markupsafe==2.0.1'],
 'httpx': ['requests>=2.0,<3.0'],
 'jsonschema': ['jsonschema>=3.0,<4.0'],
 'kombu': ['kombu>=5.1,<6.0'],
 'openapi-ui-bundles': ['openapi-ui-bundles>=0.1,<0.2'],
 'pydantic': ['pydantic>=1.7.0,<2.0.0'],
 'requests': ['requests>=2.0,<3.0'],
 'starlette': ['aiofiles>=0.7,<0.8', 'starlette>=0.12.0,<0.13.0'],
 'werkzeug': ['werkzeug>=2.0,<3.0']}

setup_kwargs = {
    'name': 'pjrpc',
    'version': '1.5.0',
    'description': 'Extensible JSON-RPC library',
    'long_description': '=====\npjrpc\n=====\n\n.. image:: https://static.pepy.tech/personalized-badge/pjrpc?period=month&units=international_system&left_color=grey&right_color=orange&left_text=Downloads/month\n    :target: https://pepy.tech/project/pjrpc\n    :alt: Downloads/month\n.. image:: https://travis-ci.org/dapper91/pjrpc.svg?branch=master\n    :target: https://travis-ci.org/dapper91/pjrpc\n    :alt: Build status\n.. image:: https://img.shields.io/pypi/l/pjrpc.svg\n    :target: https://pypi.org/project/pjrpc\n    :alt: License\n.. image:: https://img.shields.io/pypi/pyversions/pjrpc.svg\n    :target: https://pypi.org/project/pjrpc\n    :alt: Supported Python versions\n.. image:: https://codecov.io/gh/dapper91/pjrpc/branch/master/graph/badge.svg\n    :target: https://codecov.io/gh/dapper91/pjrpc\n    :alt: Code coverage\n.. image:: https://readthedocs.org/projects/pjrpc/badge/?version=stable&style=flat\n   :alt: ReadTheDocs status\n   :target: https://pjrpc.readthedocs.io/en/stable/\n\n\n``pjrpc`` is an extensible `JSON-RPC <https://www.jsonrpc.org>`_ client/server library with an intuitive interface\nthat can be easily extended and integrated in your project without writing a lot of boilerplate code.\n\nFeatures:\n\n- framework agnostic\n- intuitive api\n- extendability\n- synchronous and asynchronous client backed\n- synchronous and asynchronous server support\n- popular frameworks integration\n- builtin parameter validation\n- pytest integration\n- openapi schema generation support\n- web ui support (SwaggerUI, RapiDoc, ReDoc)\n\nInstallation\n------------\n\nYou can install pjrpc with pip:\n\n.. code-block:: console\n\n    $ pip install pjrpc\n\n\nExtra requirements\n------------------\n\n- `aiohttp <https://aiohttp.readthedocs.io>`_\n- `aio_pika <https://aio-pika.readthedocs.io>`_\n- `flask <https://flask.palletsprojects.com>`_\n- `jsonschema <https://python-jsonschema.readthedocs.io>`_\n- `kombu <https://kombu.readthedocs.io/en/stable/>`_\n- `pydantic <https://pydantic-docs.helpmanual.io/>`_\n- `requests <https://requests.readthedocs.io>`_\n- `httpx <https://www.python-httpx.org/>`_\n- `openapi-ui-bundles <https://github.com/dapper91/python-openapi-ui-bundles>`_\n- `starlette <https://www.starlette.io/>`_\n- `django <https://www.djangoproject.com>`_\n\n\nDocumentation\n-------------\n\nDocumentation is available at `Read the Docs <https://pjrpc.readthedocs.io/en/latest/>`_.\n\n\nQuickstart\n----------\n\nClient requests\n_______________\n\n``pjrpc`` client interface is very simple and intuitive. Methods may be called by name, using proxy object\nor by sending handmade ``pjrpc.common.Request`` class object. Notification requests can be made using\n``pjrpc.client.AbstractClient.notify`` method or by sending a ``pjrpc.common.Request`` object without id.\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    response: pjrpc.Response = client.send(pjrpc.Request(\'sum\', params=[1, 2], id=1))\n    print(f"1 + 2 = {response.result}")\n\n    result = client(\'sum\', a=1, b=2)\n    print(f"1 + 2 = {result}")\n\n    result = client.proxy.sum(1, 2)\n    print(f"1 + 2 = {result}")\n\n    client.notify(\'tick\')\n\n\nAsynchronous client api looks pretty much the same:\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import aiohttp as pjrpc_client\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    response = await client.send(pjrpc.Request(\'sum\', params=[1, 2], id=1))\n    print(f"1 + 2 = {response.result}")\n\n    result = await client(\'sum\', a=1, b=2)\n    print(f"1 + 2 = {result}")\n\n    result = await client.proxy.sum(1, 2)\n    print(f"1 + 2 = {result}")\n\n    await client.notify(\'tick\')\n\n\nBatch requests\n______________\n\nBatch requests also supported. You can build ``pjrpc.common.BatchRequest`` request by your hand and then send it to the\nserver. The result is a ``pjrpc.common.BatchResponse`` instance you can iterate over to get all the results or get\neach one by index:\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    batch_response = await client.batch.send(pjrpc.BatchRequest(\n        pjrpc.Request(\'sum\', [2, 2], id=1),\n        pjrpc.Request(\'sub\', [2, 2], id=2),\n        pjrpc.Request(\'div\', [2, 2], id=3),\n        pjrpc.Request(\'mult\', [2, 2], id=4),\n    ))\n    print(f"2 + 2 = {batch_response[0].result}")\n    print(f"2 - 2 = {batch_response[1].result}")\n    print(f"2 / 2 = {batch_response[2].result}")\n    print(f"2 * 2 = {batch_response[3].result}")\n\n\nThere are also several alternative approaches which are a syntactic sugar for the first one (note that the result\nis not a ``pjrpc.common.BatchResponse`` object anymore but a tuple of "plain" method invocation results):\n\n- using chain call notation:\n\n.. code-block:: python\n\n    result = await client.batch(\'sum\', 2, 2)(\'sub\', 2, 2)(\'div\', 2, 2)(\'mult\', 2, 2).call()\n    print(f"2 + 2 = {result[0]}")\n    print(f"2 - 2 = {result[1]}")\n    print(f"2 / 2 = {result[2]}")\n    print(f"2 * 2 = {result[3]}")\n\n\n- using subscription operator:\n\n.. code-block:: python\n\n    result = await client.batch[\n        (\'sum\', 2, 2),\n        (\'sub\', 2, 2),\n        (\'div\', 2, 2),\n        (\'mult\', 2, 2),\n    ]\n    print(f"2 + 2 = {result[0]}")\n    print(f"2 - 2 = {result[1]}")\n    print(f"2 / 2 = {result[2]}")\n    print(f"2 * 2 = {result[3]}")\n\n\n- using proxy chain call:\n\n.. code-block:: python\n\n    result = await client.batch.proxy.sum(2, 2).sub(2, 2).div(2, 2).mult(2, 2).call()\n    print(f"2 + 2 = {result[0]}")\n    print(f"2 - 2 = {result[1]}")\n    print(f"2 / 2 = {result[2]}")\n    print(f"2 * 2 = {result[3]}")\n\n\nWhich one to use is up to you but be aware that if any of the requests returns an error the result of the other ones\nwill be lost. In such case the first approach can be used to iterate over all the responses and get the results of\nthe succeeded ones like this:\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    batch_response = client.batch.send(pjrpc.BatchRequest(\n        pjrpc.Request(\'sum\', [2, 2], id=1),\n        pjrpc.Request(\'sub\', [2, 2], id=2),\n        pjrpc.Request(\'div\', [2, 2], id=3),\n        pjrpc.Request(\'mult\', [2, 2], id=4),\n    ))\n\n    for response in batch_response:\n        if response.is_success:\n            print(response.result)\n        else:\n            print(response.error)\n\n\nBatch notifications:\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    client.batch.notify(\'tick\').notify(\'tack\').notify(\'tick\').notify(\'tack\').call()\n\n\n\nServer\n______\n\n``pjrpc`` supports popular backend frameworks like `aiohttp <https://aiohttp.readthedocs.io>`_,\n`flask <https://flask.palletsprojects.com>`_ and message brokers like `kombu <https://kombu.readthedocs.io/en/stable/>`_\nand `aio_pika <https://aio-pika.readthedocs.io>`_.\n\n\nRunning of aiohttp based JSON-RPC server is a very simple process. Just define methods, add them to the\nregistry and run the server:\n\n.. code-block:: python\n\n    import uuid\n\n    from aiohttp import web\n\n    import pjrpc.server\n    from pjrpc.server.integration import aiohttp\n\n    methods = pjrpc.server.MethodRegistry()\n\n\n    @methods.add(context=\'request\')\n    async def add_user(request: web.Request, user: dict):\n        user_id = uuid.uuid4().hex\n        request.app[\'users\'][user_id] = user\n\n        return {\'id\': user_id, **user}\n\n\n    jsonrpc_app = aiohttp.Application(\'/api/v1\')\n    jsonrpc_app.dispatcher.add_methods(methods)\n    jsonrpc_app.app[\'users\'] = {}\n\n    if __name__ == "__main__":\n        web.run_app(jsonrpc_app.app, host=\'localhost\', port=8080)\n\n\nParameter validation\n____________________\n\nVery often besides dumb method parameters validation it is necessary to implement more "deep" validation and provide\ncomprehensive errors description to clients. Fortunately ``pjrpc`` has builtin parameter validation based on\n`pydantic <https://pydantic-docs.helpmanual.io/>`_ library which uses python type annotation for validation.\nLook at the following example: all you need to annotate method parameters (or describe more complex types beforehand if\nnecessary). ``pjrpc`` will be validating method parameters and returning informative errors to clients.\n\n\n.. code-block:: python\n\n    import enum\n    import uuid\n    from typing import List\n\n    import pydantic\n    from aiohttp import web\n\n    import pjrpc.server\n    from pjrpc.server.validators import pydantic as validators\n    from pjrpc.server.integration import aiohttp\n\n    methods = pjrpc.server.MethodRegistry()\n    validator = validators.PydanticValidator()\n\n\n    class ContactType(enum.Enum):\n        PHONE = \'phone\'\n        EMAIL = \'email\'\n\n\n    class Contact(pydantic.BaseModel):\n        type: ContactType\n        value: str\n\n\n    class User(pydantic.BaseModel):\n        name: str\n        surname: str\n        age: int\n        contacts: List[Contact]\n\n\n    @methods.add(context=\'request\')\n    @validator.validate\n    async def add_user(request: web.Request, user: User):\n        user_id = uuid.uuid4()\n        request.app[\'users\'][user_id] = user\n\n        return {\'id\': user_id, **user.dict()}\n\n\n    class JSONEncoder(pjrpc.server.JSONEncoder):\n\n        def default(self, o):\n            if isinstance(o, uuid.UUID):\n                return o.hex\n            if isinstance(o, enum.Enum):\n                return o.value\n\n            return super().default(o)\n\n\n    jsonrpc_app = aiohttp.Application(\'/api/v1\', json_encoder=JSONEncoder)\n    jsonrpc_app.dispatcher.add_methods(methods)\n    jsonrpc_app.app[\'users\'] = {}\n\n    if __name__ == "__main__":\n        web.run_app(jsonrpc_app.app, host=\'localhost\', port=8080)\n\n\nError handling\n______________\n\n``pjrpc`` implements all the errors listed in `protocol specification <https://www.jsonrpc.org/specification#error_object>`_\nwhich can be found in ``pjrpc.common.exceptions`` module so that error handling is very simple and "pythonic-way":\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    try:\n        result = client.proxy.sum(1, 2)\n    except pjrpc.MethodNotFound as e:\n        print(e)\n\n\nDefault error list can be easily extended. All you need to create an error class inherited from\n``pjrpc.exc.JsonRpcError`` and define an error code and a description message. ``pjrpc`` will be automatically\ndeserializing custom errors for you:\n\n.. code-block:: python\n\n    import pjrpc\n    from pjrpc.client.backend import requests as pjrpc_client\n\n    class UserNotFound(pjrpc.exc.JsonRpcError):\n        code = 1\n        message = \'user not found\'\n\n\n    client = pjrpc_client.Client(\'http://localhost/api/v1\')\n\n    try:\n        result = client.proxy.get_user(user_id=1)\n    except UserNotFound as e:\n        print(e)\n\n\nOn the server side everything is also pretty straightforward:\n\n.. code-block:: python\n\n    import uuid\n\n    import flask\n\n    import pjrpc\n    from pjrpc.server import MethodRegistry\n    from pjrpc.server.integration import flask as integration\n\n    app = flask.Flask(__name__)\n\n    methods = pjrpc.server.MethodRegistry()\n\n\n    class UserNotFound(pjrpc.exc.JsonRpcError):\n        code = 1\n        message = \'user not found\'\n\n\n    @methods.add\n    def add_user(user: dict):\n        user_id = uuid.uuid4().hex\n        flask.current_app.users[user_id] = user\n\n        return {\'id\': user_id, **user}\n\n    @methods.add\n     def get_user(self, user_id: str):\n        user = flask.current_app.users.get(user_id)\n        if not user:\n            raise UserNotFound(data=user_id)\n\n        return user\n\n\n    json_rpc = integration.JsonRPC(\'/api/v1\')\n    json_rpc.dispatcher.add_methods(methods)\n\n    app.users = {}\n\n    json_rpc.init_app(app)\n\n    if __name__ == "__main__":\n        app.run(port=80)\n\n\n\nOpen API specification\n______________________\n\n``pjrpc`` has built-in `OpenAPI <https://swagger.io/specification/>`_ and `OpenRPC <https://spec.open-rpc.org/#introduction>`_\nspecification generation support and integrated web UI as an extra dependency. Three UI types are supported:\n\n- SwaggerUI (`<https://swagger.io/tools/swagger-ui/>`_)\n- RapiDoc (`<https://mrin9.github.io/RapiDoc/>`_)\n- ReDoc (`<https://github.com/Redocly/redoc>`_)\n\nWeb UI extra dependency can be installed using the following code:\n\n.. code-block:: console\n\n    $ pip install pjrpc[openapi-ui-bundles]\n\nThe following example illustrates how to configure OpenAPI specification generation\nand Swagger UI web tool with basic auth:\n\n.. code-block:: python\n\n    import uuid\n    from typing import Any, Optional\n\n    import flask\n    import flask_httpauth\n    import pydantic\n    import flask_cors\n    from werkzeug import security\n\n    import pjrpc.server.specs.extractors.pydantic\n    from pjrpc.server.integration import flask as integration\n    from pjrpc.server.validators import pydantic as validators\n    from pjrpc.server.specs import extractors, openapi as specs\n\n\n    app = flask.Flask(\'myapp\')\n    flask_cors.CORS(app, resources={"/myapp/api/v1/*": {"origins": "*"}})\n\n    methods = pjrpc.server.MethodRegistry()\n    validator = validators.PydanticValidator()\n\n    auth = flask_httpauth.HTTPBasicAuth()\n    credentials = {"admin": security.generate_password_hash("admin")}\n\n\n    @auth.verify_password\n    def verify_password(username: str, password: str) -> Optional[str]:\n        if username in credentials and security.check_password_hash(credentials.get(username), password):\n            return username\n\n\n    class AuthenticatedJsonRPC(integration.JsonRPC):\n        @auth.login_required\n        def _rpc_handle(self, dispatcher: pjrpc.server.Dispatcher) -> flask.Response:\n            return super()._rpc_handle(dispatcher)\n\n\n    class JSONEncoder(pjrpc.JSONEncoder):\n        def default(self, o: Any) -> Any:\n            if isinstance(o, pydantic.BaseModel):\n                return o.dict()\n            if isinstance(o, uuid.UUID):\n                return str(o)\n\n            return super().default(o)\n\n\n    class UserIn(pydantic.BaseModel):\n        """\n        User registration data.\n        """\n\n        name: str\n        surname: str\n        age: int\n\n\n    class UserOut(UserIn):\n        """\n        Registered user data.\n        """\n\n        id: uuid.UUID\n\n\n    class AlreadyExistsError(pjrpc.exc.JsonRpcError):\n        """\n        User already registered error.\n        """\n\n        code = 2001\n        message = "user already exists"\n\n\n    class NotFoundError(pjrpc.exc.JsonRpcError):\n        """\n        User not found error.\n        """\n\n        code = 2002\n        message = "user not found"\n\n\n    @specs.annotate(\n        tags=[\'users\'],\n        errors=[AlreadyExistsError],\n        examples=[\n            specs.MethodExample(\n                summary="Simple example",\n                params=dict(\n                    user={\n                        \'name\': \'John\',\n                        \'surname\': \'Doe\',\n                        \'age\': 25,\n                    },\n                ),\n                result={\n                    \'id\': \'c47726c6-a232-45f1-944f-60b98966ff1b\',\n                    \'name\': \'John\',\n                    \'surname\': \'Doe\',\n                    \'age\': 25,\n                },\n            ),\n        ],\n    )\n    @methods.add\n    @validator.validate\n    def add_user(user: UserIn) -> UserOut:\n        """\n        Creates a user.\n\n        :param object user: user data\n        :return object: registered user\n        :raise AlreadyExistsError: user already exists\n        """\n\n        for existing_user in flask.current_app.users_db.values():\n            if user.name == existing_user.name:\n                raise AlreadyExistsError()\n\n        user_id = uuid.uuid4().hex\n        flask.current_app.users_db[user_id] = user\n\n        return UserOut(id=user_id, **user.dict())\n\n\n    @specs.annotate(\n        tags=[\'users\'],\n        errors=[NotFoundError],\n        examples=[\n            specs.MethodExample(\n                summary=\'Simple example\',\n                params=dict(\n                    user_id=\'c47726c6-a232-45f1-944f-60b98966ff1b\',\n                ),\n                result={\n                    \'id\': \'c47726c6-a232-45f1-944f-60b98966ff1b\',\n                    \'name\': \'John\',\n                    \'surname\': \'Doe\',\n                    \'age\': 25,\n                },\n            ),\n        ],\n    )\n    @methods.add\n    @validator.validate\n    def get_user(user_id: uuid.UUID) -> UserOut:\n        """\n        Returns a user.\n\n        :param object user_id: user id\n        :return object: registered user\n        :raise NotFoundError: user not found\n        """\n\n        user = flask.current_app.users_db.get(user_id.hex)\n        if not user:\n            raise NotFoundError()\n\n        return UserOut(id=user_id, **user.dict())\n\n\n    @specs.annotate(\n        tags=[\'users\'],\n        errors=[NotFoundError],\n        examples=[\n            specs.MethodExample(\n                summary=\'Simple example\',\n                params=dict(\n                    user_id=\'c47726c6-a232-45f1-944f-60b98966ff1b\',\n                ),\n                result=None,\n            ),\n        ],\n    )\n    @methods.add\n    @validator.validate\n    def delete_user(user_id: uuid.UUID) -> None:\n        """\n        Deletes a user.\n\n        :param object user_id: user id\n        :raise NotFoundError: user not found\n        """\n\n        user = flask.current_app.users_db.pop(user_id.hex, None)\n        if not user:\n            raise NotFoundError()\n\n\n    json_rpc = AuthenticatedJsonRPC(\n        \'/api/v1\',\n        json_encoder=JSONEncoder,\n        spec=specs.OpenAPI(\n            info=specs.Info(version="1.0.0", title="User storage"),\n            servers=[\n                specs.Server(\n                    url=\'http://127.0.0.1:8080\',\n                ),\n            ],\n            security_schemes=dict(\n                basicAuth=specs.SecurityScheme(\n                    type=specs.SecuritySchemeType.HTTP,\n                    scheme=\'basic\',\n                ),\n            ),\n            security=[\n                dict(basicAuth=[]),\n            ],\n            schema_extractor=extractors.pydantic.PydanticSchemaExtractor(),\n            ui=specs.SwaggerUI(),\n            # ui=specs.RapiDoc(),\n            # ui=specs.ReDoc(),\n        ),\n    )\n    json_rpc.dispatcher.add_methods(methods)\n\n    app.users_db = {}\n\n    myapp = flask.Blueprint(\'myapp\', __name__, url_prefix=\'/myapp\')\n    json_rpc.init_app(myapp)\n\n    app.register_blueprint(myapp)\n\n    if __name__ == "__main__":\n        app.run(port=8080)\n\n\nSpecification is available on http://localhost:8080/myapp/api/v1/openapi.json\n\nWeb UI is running on http://localhost:8080/myapp/api/v1/ui/\n\nSwagger UI:\n~~~~~~~~~~~\n\n.. image:: docs/source/_static/swagger-ui-screenshot.png\n  :width: 1024\n  :alt: Open API full example\n\nRapiDoc:\n~~~~~~~~\n\n.. image:: docs/source/_static/rapidoc-screenshot.png\n  :width: 1024\n  :alt: Open API cli example\n\nRedoc:\n~~~~~~\n\n.. image:: docs/source/_static/redoc-screenshot.png\n  :width: 1024\n  :alt: Open API method example\n',
    'author': 'Dmitry Pershin',
    'author_email': 'dapper1291@gmail.com',
    'maintainer': None,
    'maintainer_email': None,
    'url': 'https://github.com/dapper91/pjrpc',
    'packages': packages,
    'package_data': package_data,
    'extras_require': extras_require,
    'python_requires': '>=3.7,<4.0',
}


setup(**setup_kwargs)
