[Python-modules-commits] [python-json-rpc] 01/03: New upstream version 1.10.3

Ghislain Vaillant ghisvail-guest at moszumanska.debian.org
Wed Oct 18 21:08:07 UTC 2017


This is an automated email from the git hooks/post-receive script.

ghisvail-guest pushed a commit to branch debian/master
in repository python-json-rpc.

commit 2e479aa7c5d52bec31205b31bd977dcd2a0327bb
Author: Ghislain Antony Vaillant <ghisvail at gmail.com>
Date:   Wed Oct 18 19:06:52 2017 +0100

    New upstream version 1.10.3
---
 PKG-INFO                                      | 152 ++++++
 README.rst                                    | 131 +++++
 json_rpc.egg-info/PKG-INFO                    | 152 ++++++
 json_rpc.egg-info/SOURCES.txt                 |  38 ++
 json_rpc.egg-info/dependency_links.txt        |   1 +
 json_rpc.egg-info/pbr.json                    |   1 +
 json_rpc.egg-info/top_level.txt               |   1 +
 jsonrpc/__init__.py                           |  11 +
 jsonrpc/backend/__init__.py                   |   0
 jsonrpc/backend/django.py                     |  82 +++
 jsonrpc/backend/flask.py                      |  91 ++++
 jsonrpc/base.py                               |  85 +++
 jsonrpc/dispatcher.py                         | 122 +++++
 jsonrpc/exceptions.py                         | 185 +++++++
 jsonrpc/jsonrpc.py                            |  24 +
 jsonrpc/jsonrpc1.py                           | 148 ++++++
 jsonrpc/jsonrpc2.py                           | 263 ++++++++++
 jsonrpc/manager.py                            | 129 +++++
 jsonrpc/six.py                                | 584 +++++++++++++++++++++
 jsonrpc/tests/__init__.py                     |   0
 jsonrpc/tests/test_backend_django/__init__.py |   0
 jsonrpc/tests/test_backend_django/settings.py |  10 +
 jsonrpc/tests/test_backend_django/tests.py    |  83 +++
 jsonrpc/tests/test_backend_django/urls.py     |   8 +
 jsonrpc/tests/test_backend_flask/__init__.py  |   0
 jsonrpc/tests/test_backend_flask/tests.py     | 174 ++++++
 jsonrpc/tests/test_base.py                    |  38 ++
 jsonrpc/tests/test_bug29.py                   |  33 ++
 jsonrpc/tests/test_dispatcher.py              | 128 +++++
 jsonrpc/tests/test_examples20.py              | 171 ++++++
 jsonrpc/tests/test_jsonrpc.py                 |   1 +
 jsonrpc/tests/test_jsonrpc1.py                | 429 +++++++++++++++
 jsonrpc/tests/test_jsonrpc2.py                | 727 ++++++++++++++++++++++++++
 jsonrpc/tests/test_jsonrpc_errors.py          | 149 ++++++
 jsonrpc/tests/test_manager.py                 | 170 ++++++
 jsonrpc/tests/test_utils.py                   | 111 ++++
 jsonrpc/utils.py                              |  83 +++
 setup.cfg                                     |   8 +
 setup.py                                      |  53 ++
 39 files changed, 4576 insertions(+)

diff --git a/PKG-INFO b/PKG-INFO
new file mode 100644
index 0000000..bb058c1
--- /dev/null
+++ b/PKG-INFO
@@ -0,0 +1,152 @@
+Metadata-Version: 1.1
+Name: json-rpc
+Version: 1.10.3
+Summary: JSON-RPC transport realisation
+Home-page: https://github.com/pavlov99/json-rpc
+Author: Kirill Pavlov
+Author-email: kirill.pavlov at phystech.edu
+License: MIT
+Description: json-rpc
+        ========
+        
+        .. image:: https://badges.gitter.im/Join%20Chat.svg
+           :alt: Join the chat at https://gitter.im/pavlov99/json-rpc
+           :target: https://gitter.im/pavlov99/json-rpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
+        
+        .. image:: https://travis-ci.org/pavlov99/json-rpc.png?branch=master
+            :target: https://travis-ci.org/pavlov99/json-rpc?branch=master
+            :alt: Build Status
+        
+        .. image:: https://coveralls.io/repos/pavlov99/json-rpc/badge.png?branch=master
+            :target: https://coveralls.io/r/pavlov99/json-rpc?branch=master
+            :alt: Coverage Status
+            
+        .. image:: https://www.codacy.com/project/badge/34e0c2c696214041ae4fd5cfcb4af401
+            :target: https://www.codacy.com/app/pavlov99/json-rpc
+        
+        
+        `JSON-RPC2.0 <http://www.jsonrpc.org/specification>`_ and `JSON-RPC1.0 <http://json-rpc.org/wiki/specification>`_ transport specification implementation.
+        Supports python2.6+, python3.3+, PyPy. Has optional Django and Flask support. 200+ tests.
+        
+        Documentation: http://json-rpc.readthedocs.org
+        
+        This implementation does not have any transport functionality realization, only protocol.
+        Any client or server realization is easy based on current code, but requires transport libraries, such as requests, gevent or zmq, see `examples <https://github.com/pavlov99/json-rpc/tree/master/examples>`_.
+        
+        Install
+        -------
+        
+        .. code-block:: python
+        
+            pip install json-rpc
+        
+        Tests
+        -----
+        
+        .. code-block:: python
+        
+            tox
+        
+        Features
+        --------
+        
+        - Vanilla python, no dependencies
+        - Optional backend support for Django, Flask
+        - json-rpc 1.1 and 2.0 support
+        
+        Quickstart
+        ----------
+        Server (uses `Werkzeug <http://werkzeug.pocoo.org/>`_)
+        
+        .. code-block:: python
+        
+            from werkzeug.wrappers import Request, Response
+            from werkzeug.serving import run_simple
+        
+            from jsonrpc import JSONRPCResponseManager, dispatcher
+        
+        
+            @dispatcher.add_method
+            def foobar(**kwargs):
+                return kwargs["foo"] + kwargs["bar"]
+        
+        
+            @Request.application
+            def application(request):
+                # Dispatcher is dictionary {<method_name>: callable}
+                dispatcher["echo"] = lambda s: s
+                dispatcher["add"] = lambda a, b: a + b
+        
+                response = JSONRPCResponseManager.handle(
+                    request.data, dispatcher)
+                return Response(response.json, mimetype='application/json')
+        
+        
+            if __name__ == '__main__':
+                run_simple('localhost', 4000, application)
+        
+        Client (uses `requests <http://www.python-requests.org/en/latest/>`_)
+        
+        .. code-block:: python
+        
+            import requests
+            import json
+        
+        
+            def main():
+                url = "http://localhost:4000/jsonrpc"
+                headers = {'content-type': 'application/json'}
+        
+                # Example echo method
+                payload = {
+                    "method": "echo",
+                    "params": ["echome!"],
+                    "jsonrpc": "2.0",
+                    "id": 0,
+                }
+                response = requests.post(
+                    url, data=json.dumps(payload), headers=headers).json()
+        
+                assert response["result"] == "echome!"
+                assert response["jsonrpc"]
+                assert response["id"] == 0
+        
+            if __name__ == "__main__":
+                main()
+        
+        Competitors
+        -----------
+        There are `several libraries <http://en.wikipedia.org/wiki/JSON-RPC#Implementations>`_ implementing JSON-RPC protocol. List below represents python libraries, none of the supports python3. tinyrpc looks better than others.
+        
+        
+        Testing
+        -------
+        json-rpc is a python library, it supports pythons: 2.6, 2.7, 3.3, 3.4. There is optional support for django1.6 (python2.6 does not support django1.7).
+        
+        Contributors
+        ------------
+        
+        * Kirill Pavlov `@pavlov99 <https://github.com/pavlov99>`_
+        * Jan Willems `@jw <https://github.com/jw>`_
+        * Robby Dermody (xnova) `@robby-dermody <https://github.com/robby-dermody>`_
+        * matee911 `@matee911 <https://github.com/matee911>`_
+        * Malyshev Artem `@proofit404 <https://github.com/proofit404>`_
+        * Julian Hille `@julianhille <https://github.com/julianhille>`_
+        * Pavel Evdokimov `@Santinell <https://github.com/Santinell>`_
+        * Lev Orekhov `@lorehov <https://github.com/lorehov>`_
+        * Sergey Nikitin `@nikitinsm <https://github.com/nikitinsm>`_
+        * Jean-Christophe Bohin `@jcbohin <https://github.com/jcbohin>`_
+        * arnuschky `@arnuschky <https://github.com/arnuschky>`_
+        
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Natural Language :: English
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..e5f2b10
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,131 @@
+json-rpc
+========
+
+.. image:: https://badges.gitter.im/Join%20Chat.svg
+   :alt: Join the chat at https://gitter.im/pavlov99/json-rpc
+   :target: https://gitter.im/pavlov99/json-rpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
+
+.. image:: https://travis-ci.org/pavlov99/json-rpc.png?branch=master
+    :target: https://travis-ci.org/pavlov99/json-rpc?branch=master
+    :alt: Build Status
+
+.. image:: https://coveralls.io/repos/pavlov99/json-rpc/badge.png?branch=master
+    :target: https://coveralls.io/r/pavlov99/json-rpc?branch=master
+    :alt: Coverage Status
+    
+.. image:: https://www.codacy.com/project/badge/34e0c2c696214041ae4fd5cfcb4af401
+    :target: https://www.codacy.com/app/pavlov99/json-rpc
+
+
+`JSON-RPC2.0 <http://www.jsonrpc.org/specification>`_ and `JSON-RPC1.0 <http://json-rpc.org/wiki/specification>`_ transport specification implementation.
+Supports python2.6+, python3.3+, PyPy. Has optional Django and Flask support. 200+ tests.
+
+Documentation: http://json-rpc.readthedocs.org
+
+This implementation does not have any transport functionality realization, only protocol.
+Any client or server realization is easy based on current code, but requires transport libraries, such as requests, gevent or zmq, see `examples <https://github.com/pavlov99/json-rpc/tree/master/examples>`_.
+
+Install
+-------
+
+.. code-block:: python
+
+    pip install json-rpc
+
+Tests
+-----
+
+.. code-block:: python
+
+    tox
+
+Features
+--------
+
+- Vanilla python, no dependencies
+- Optional backend support for Django, Flask
+- json-rpc 1.1 and 2.0 support
+
+Quickstart
+----------
+Server (uses `Werkzeug <http://werkzeug.pocoo.org/>`_)
+
+.. code-block:: python
+
+    from werkzeug.wrappers import Request, Response
+    from werkzeug.serving import run_simple
+
+    from jsonrpc import JSONRPCResponseManager, dispatcher
+
+
+    @dispatcher.add_method
+    def foobar(**kwargs):
+        return kwargs["foo"] + kwargs["bar"]
+
+
+    @Request.application
+    def application(request):
+        # Dispatcher is dictionary {<method_name>: callable}
+        dispatcher["echo"] = lambda s: s
+        dispatcher["add"] = lambda a, b: a + b
+
+        response = JSONRPCResponseManager.handle(
+            request.data, dispatcher)
+        return Response(response.json, mimetype='application/json')
+
+
+    if __name__ == '__main__':
+        run_simple('localhost', 4000, application)
+
+Client (uses `requests <http://www.python-requests.org/en/latest/>`_)
+
+.. code-block:: python
+
+    import requests
+    import json
+
+
+    def main():
+        url = "http://localhost:4000/jsonrpc"
+        headers = {'content-type': 'application/json'}
+
+        # Example echo method
+        payload = {
+            "method": "echo",
+            "params": ["echome!"],
+            "jsonrpc": "2.0",
+            "id": 0,
+        }
+        response = requests.post(
+            url, data=json.dumps(payload), headers=headers).json()
+
+        assert response["result"] == "echome!"
+        assert response["jsonrpc"]
+        assert response["id"] == 0
+
+    if __name__ == "__main__":
+        main()
+
+Competitors
+-----------
+There are `several libraries <http://en.wikipedia.org/wiki/JSON-RPC#Implementations>`_ implementing JSON-RPC protocol. List below represents python libraries, none of the supports python3. tinyrpc looks better than others.
+
+
+Testing
+-------
+json-rpc is a python library, it supports pythons: 2.6, 2.7, 3.3, 3.4. There is optional support for django1.6 (python2.6 does not support django1.7).
+
+Contributors
+------------
+
+* Kirill Pavlov `@pavlov99 <https://github.com/pavlov99>`_
+* Jan Willems `@jw <https://github.com/jw>`_
+* Robby Dermody (xnova) `@robby-dermody <https://github.com/robby-dermody>`_
+* matee911 `@matee911 <https://github.com/matee911>`_
+* Malyshev Artem `@proofit404 <https://github.com/proofit404>`_
+* Julian Hille `@julianhille <https://github.com/julianhille>`_
+* Pavel Evdokimov `@Santinell <https://github.com/Santinell>`_
+* Lev Orekhov `@lorehov <https://github.com/lorehov>`_
+* Sergey Nikitin `@nikitinsm <https://github.com/nikitinsm>`_
+* Jean-Christophe Bohin `@jcbohin <https://github.com/jcbohin>`_
+* arnuschky `@arnuschky <https://github.com/arnuschky>`_
diff --git a/json_rpc.egg-info/PKG-INFO b/json_rpc.egg-info/PKG-INFO
new file mode 100644
index 0000000..bb058c1
--- /dev/null
+++ b/json_rpc.egg-info/PKG-INFO
@@ -0,0 +1,152 @@
+Metadata-Version: 1.1
+Name: json-rpc
+Version: 1.10.3
+Summary: JSON-RPC transport realisation
+Home-page: https://github.com/pavlov99/json-rpc
+Author: Kirill Pavlov
+Author-email: kirill.pavlov at phystech.edu
+License: MIT
+Description: json-rpc
+        ========
+        
+        .. image:: https://badges.gitter.im/Join%20Chat.svg
+           :alt: Join the chat at https://gitter.im/pavlov99/json-rpc
+           :target: https://gitter.im/pavlov99/json-rpc?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
+        
+        .. image:: https://travis-ci.org/pavlov99/json-rpc.png?branch=master
+            :target: https://travis-ci.org/pavlov99/json-rpc?branch=master
+            :alt: Build Status
+        
+        .. image:: https://coveralls.io/repos/pavlov99/json-rpc/badge.png?branch=master
+            :target: https://coveralls.io/r/pavlov99/json-rpc?branch=master
+            :alt: Coverage Status
+            
+        .. image:: https://www.codacy.com/project/badge/34e0c2c696214041ae4fd5cfcb4af401
+            :target: https://www.codacy.com/app/pavlov99/json-rpc
+        
+        
+        `JSON-RPC2.0 <http://www.jsonrpc.org/specification>`_ and `JSON-RPC1.0 <http://json-rpc.org/wiki/specification>`_ transport specification implementation.
+        Supports python2.6+, python3.3+, PyPy. Has optional Django and Flask support. 200+ tests.
+        
+        Documentation: http://json-rpc.readthedocs.org
+        
+        This implementation does not have any transport functionality realization, only protocol.
+        Any client or server realization is easy based on current code, but requires transport libraries, such as requests, gevent or zmq, see `examples <https://github.com/pavlov99/json-rpc/tree/master/examples>`_.
+        
+        Install
+        -------
+        
+        .. code-block:: python
+        
+            pip install json-rpc
+        
+        Tests
+        -----
+        
+        .. code-block:: python
+        
+            tox
+        
+        Features
+        --------
+        
+        - Vanilla python, no dependencies
+        - Optional backend support for Django, Flask
+        - json-rpc 1.1 and 2.0 support
+        
+        Quickstart
+        ----------
+        Server (uses `Werkzeug <http://werkzeug.pocoo.org/>`_)
+        
+        .. code-block:: python
+        
+            from werkzeug.wrappers import Request, Response
+            from werkzeug.serving import run_simple
+        
+            from jsonrpc import JSONRPCResponseManager, dispatcher
+        
+        
+            @dispatcher.add_method
+            def foobar(**kwargs):
+                return kwargs["foo"] + kwargs["bar"]
+        
+        
+            @Request.application
+            def application(request):
+                # Dispatcher is dictionary {<method_name>: callable}
+                dispatcher["echo"] = lambda s: s
+                dispatcher["add"] = lambda a, b: a + b
+        
+                response = JSONRPCResponseManager.handle(
+                    request.data, dispatcher)
+                return Response(response.json, mimetype='application/json')
+        
+        
+            if __name__ == '__main__':
+                run_simple('localhost', 4000, application)
+        
+        Client (uses `requests <http://www.python-requests.org/en/latest/>`_)
+        
+        .. code-block:: python
+        
+            import requests
+            import json
+        
+        
+            def main():
+                url = "http://localhost:4000/jsonrpc"
+                headers = {'content-type': 'application/json'}
+        
+                # Example echo method
+                payload = {
+                    "method": "echo",
+                    "params": ["echome!"],
+                    "jsonrpc": "2.0",
+                    "id": 0,
+                }
+                response = requests.post(
+                    url, data=json.dumps(payload), headers=headers).json()
+        
+                assert response["result"] == "echome!"
+                assert response["jsonrpc"]
+                assert response["id"] == 0
+        
+            if __name__ == "__main__":
+                main()
+        
+        Competitors
+        -----------
+        There are `several libraries <http://en.wikipedia.org/wiki/JSON-RPC#Implementations>`_ implementing JSON-RPC protocol. List below represents python libraries, none of the supports python3. tinyrpc looks better than others.
+        
+        
+        Testing
+        -------
+        json-rpc is a python library, it supports pythons: 2.6, 2.7, 3.3, 3.4. There is optional support for django1.6 (python2.6 does not support django1.7).
+        
+        Contributors
+        ------------
+        
+        * Kirill Pavlov `@pavlov99 <https://github.com/pavlov99>`_
+        * Jan Willems `@jw <https://github.com/jw>`_
+        * Robby Dermody (xnova) `@robby-dermody <https://github.com/robby-dermody>`_
+        * matee911 `@matee911 <https://github.com/matee911>`_
+        * Malyshev Artem `@proofit404 <https://github.com/proofit404>`_
+        * Julian Hille `@julianhille <https://github.com/julianhille>`_
+        * Pavel Evdokimov `@Santinell <https://github.com/Santinell>`_
+        * Lev Orekhov `@lorehov <https://github.com/lorehov>`_
+        * Sergey Nikitin `@nikitinsm <https://github.com/nikitinsm>`_
+        * Jean-Christophe Bohin `@jcbohin <https://github.com/jcbohin>`_
+        * arnuschky `@arnuschky <https://github.com/arnuschky>`_
+        
+Platform: UNKNOWN
+Classifier: Development Status :: 5 - Production/Stable
+Classifier: Environment :: Console
+Classifier: License :: OSI Approved :: MIT License
+Classifier: Natural Language :: English
+Classifier: Operating System :: OS Independent
+Classifier: Programming Language :: Python :: 2.6
+Classifier: Programming Language :: Python :: 2.7
+Classifier: Programming Language :: Python :: 3.3
+Classifier: Programming Language :: Python :: 3.4
+Classifier: Programming Language :: Python :: Implementation :: PyPy
+Classifier: Topic :: Software Development :: Libraries :: Python Modules
diff --git a/json_rpc.egg-info/SOURCES.txt b/json_rpc.egg-info/SOURCES.txt
new file mode 100644
index 0000000..09d817d
--- /dev/null
+++ b/json_rpc.egg-info/SOURCES.txt
@@ -0,0 +1,38 @@
+README.rst
+setup.cfg
+setup.py
+json_rpc.egg-info/PKG-INFO
+json_rpc.egg-info/SOURCES.txt
+json_rpc.egg-info/dependency_links.txt
+json_rpc.egg-info/pbr.json
+json_rpc.egg-info/top_level.txt
+jsonrpc/__init__.py
+jsonrpc/base.py
+jsonrpc/dispatcher.py
+jsonrpc/exceptions.py
+jsonrpc/jsonrpc.py
+jsonrpc/jsonrpc1.py
+jsonrpc/jsonrpc2.py
+jsonrpc/manager.py
+jsonrpc/six.py
+jsonrpc/utils.py
+jsonrpc/backend/__init__.py
+jsonrpc/backend/django.py
+jsonrpc/backend/flask.py
+jsonrpc/tests/__init__.py
+jsonrpc/tests/test_base.py
+jsonrpc/tests/test_bug29.py
+jsonrpc/tests/test_dispatcher.py
+jsonrpc/tests/test_examples20.py
+jsonrpc/tests/test_jsonrpc.py
+jsonrpc/tests/test_jsonrpc1.py
+jsonrpc/tests/test_jsonrpc2.py
+jsonrpc/tests/test_jsonrpc_errors.py
+jsonrpc/tests/test_manager.py
+jsonrpc/tests/test_utils.py
+jsonrpc/tests/test_backend_django/__init__.py
+jsonrpc/tests/test_backend_django/settings.py
+jsonrpc/tests/test_backend_django/tests.py
+jsonrpc/tests/test_backend_django/urls.py
+jsonrpc/tests/test_backend_flask/__init__.py
+jsonrpc/tests/test_backend_flask/tests.py
\ No newline at end of file
diff --git a/json_rpc.egg-info/dependency_links.txt b/json_rpc.egg-info/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/json_rpc.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/json_rpc.egg-info/pbr.json b/json_rpc.egg-info/pbr.json
new file mode 100644
index 0000000..e5de438
--- /dev/null
+++ b/json_rpc.egg-info/pbr.json
@@ -0,0 +1 @@
+{"is_release": false, "git_version": "2b7d5af"}
\ No newline at end of file
diff --git a/json_rpc.egg-info/top_level.txt b/json_rpc.egg-info/top_level.txt
new file mode 100644
index 0000000..1d0ccdd
--- /dev/null
+++ b/json_rpc.egg-info/top_level.txt
@@ -0,0 +1 @@
+jsonrpc
diff --git a/jsonrpc/__init__.py b/jsonrpc/__init__.py
new file mode 100644
index 0000000..06b43bd
--- /dev/null
+++ b/jsonrpc/__init__.py
@@ -0,0 +1,11 @@
+__version = (1, 10, 3)
+
+__version__ = version = '.'.join(map(str, __version))
+__project__ = PROJECT = __name__
+
+from .manager import JSONRPCResponseManager
+from .dispatcher import Dispatcher
+
+dispatcher = Dispatcher()
+
+# lint_ignore=W0611,W0401
diff --git a/jsonrpc/backend/__init__.py b/jsonrpc/backend/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/jsonrpc/backend/django.py b/jsonrpc/backend/django.py
new file mode 100644
index 0000000..9053887
--- /dev/null
+++ b/jsonrpc/backend/django.py
@@ -0,0 +1,82 @@
+from __future__ import absolute_import
+
+from django.views.decorators.csrf import csrf_exempt
+from django.conf.urls import url
+from django.http import HttpResponse, HttpResponseNotAllowed
+import copy
+import json
+import logging
+import time
+
+from ..exceptions import JSONRPCInvalidRequestException
+from ..jsonrpc import JSONRPCRequest
+from ..manager import JSONRPCResponseManager
+from ..utils import DatetimeDecimalEncoder
+from ..dispatcher import Dispatcher
+
+
+logger = logging.getLogger(__name__)
+
+
+class JSONRPCAPI(object):
+    def __init__(self, dispatcher=None):
+        self.dispatcher = dispatcher if dispatcher is not None \
+            else Dispatcher()
+
+    @property
+    def urls(self):
+        urls = [
+            url(r'^$', self.jsonrpc),
+            url(r'map$', self.jsonrpc_map),
+        ]
+
+        return urls
+
+    @csrf_exempt
+    def jsonrpc(self, request):
+        """ JSON-RPC 2.0 handler."""
+        if request.method != "POST":
+            return HttpResponseNotAllowed(["POST"])
+
+        request_str = request.body.decode('utf8')
+        try:
+            jsonrpc_request = JSONRPCRequest.from_json(request_str)
+        except (TypeError, ValueError, JSONRPCInvalidRequestException):
+            response = JSONRPCResponseManager.handle(
+                request_str, self.dispatcher)
+        else:
+            jsonrpc_request.params = jsonrpc_request.params or {}
+            jsonrpc_request_params = copy.copy(jsonrpc_request.params)
+            if isinstance(jsonrpc_request.params, dict):
+                jsonrpc_request.params.update(request=request)
+
+            t1 = time.time()
+            response = JSONRPCResponseManager.handle_request(
+                jsonrpc_request, self.dispatcher)
+            t2 = time.time()
+            logger.info('{0}({1}) {2:.2f} sec'.format(
+                jsonrpc_request.method, jsonrpc_request_params, t2 - t1))
+
+        if response:
+            def serialize(s):
+                return json.dumps(s, cls=DatetimeDecimalEncoder)
+
+            response.serialize = serialize
+            response = response.json
+
+        return HttpResponse(response, content_type="application/json")
+
+    def jsonrpc_map(self, request):
+        """ Map of json-rpc available calls.
+
+        :return str:
+
+        """
+        result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
+            "{0}: {1}".format(fname, f.__doc__)
+            for fname, f in self.dispatcher.items()
+        ]))
+        return HttpResponse(result)
+
+
+api = JSONRPCAPI()
diff --git a/jsonrpc/backend/flask.py b/jsonrpc/backend/flask.py
new file mode 100644
index 0000000..d73c273
--- /dev/null
+++ b/jsonrpc/backend/flask.py
@@ -0,0 +1,91 @@
+from __future__ import absolute_import
+
+import copy
+import json
+import logging
+import time
+from uuid import uuid4
+
+from flask import Blueprint, request, Response
+
+from ..exceptions import JSONRPCInvalidRequestException
+from ..jsonrpc import JSONRPCRequest
+from ..manager import JSONRPCResponseManager
+from ..utils import DatetimeDecimalEncoder
+from ..dispatcher import Dispatcher
+
+
+logger = logging.getLogger(__name__)
+
+
+class JSONRPCAPI(object):
+    def __init__(self, dispatcher=None, check_content_type=True):
+        """
+
+        :param dispatcher: methods dispatcher
+        :param check_content_type: if True - content-type must be
+            "application/json"
+        :return:
+
+        """
+        self.dispatcher = dispatcher if dispatcher is not None \
+            else Dispatcher()
+        self.check_content_type = check_content_type
+
+    def as_blueprint(self, name=None):
+        blueprint = Blueprint(name if name else str(uuid4()), __name__)
+        blueprint.add_url_rule(
+            '/', view_func=self.jsonrpc, methods=['POST'])
+        blueprint.add_url_rule(
+            '/map', view_func=self.jsonrpc_map, methods=['GET'])
+        return blueprint
+
+    def as_view(self):
+        return self.jsonrpc
+
+    def jsonrpc(self):
+        request_str = self._get_request_str()
+        try:
+            jsonrpc_request = JSONRPCRequest.from_json(request_str)
+        except (TypeError, ValueError, JSONRPCInvalidRequestException):
+            response = JSONRPCResponseManager.handle(
+                request_str, self.dispatcher)
+        else:
+            jsonrpc_request.params = jsonrpc_request.params or {}
+            jsonrpc_request_params = copy.copy(jsonrpc_request.params)
+            t1 = time.time()
+            response = JSONRPCResponseManager.handle_request(
+                jsonrpc_request, self.dispatcher)
+            t2 = time.time()
+            logger.info('{0}({1}) {2:.2f} sec'.format(
+                jsonrpc_request.method, jsonrpc_request_params, t2 - t1))
+
+        if response:
+            response.serialize = self._serialize
+            response = response.json
+
+        return Response(response, content_type="application/json")
+
+    def jsonrpc_map(self):
+        """ Map of json-rpc available calls.
+
+        :return str:
+
+        """
+        result = "<h1>JSON-RPC map</h1><pre>{0}</pre>".format("\n\n".join([
+            "{0}: {1}".format(fname, f.__doc__)
+            for fname, f in self.dispatcher.items()
+        ]))
+        return Response(result)
+
+    def _get_request_str(self):
+        if self.check_content_type or request.data:
+            return request.data
+        return list(request.form.keys())[0]
+
+    @staticmethod
+    def _serialize(s):
+        return json.dumps(s, cls=DatetimeDecimalEncoder)
+
+
+api = JSONRPCAPI()
diff --git a/jsonrpc/base.py b/jsonrpc/base.py
new file mode 100644
index 0000000..9359e85
--- /dev/null
+++ b/jsonrpc/base.py
@@ -0,0 +1,85 @@
+from .utils import JSONSerializable
+
+
+class JSONRPCBaseRequest(JSONSerializable):
+
+    """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 requests."""
+
+    def __init__(self, method=None, params=None, _id=None,
+                 is_notification=None):
+        self.data = dict()
+        self.method = method
+        self.params = params
+        self._id = _id
+        self.is_notification = is_notification
+
+    @property
+    def data(self):
+        return self._data
+
+    @data.setter
+    def data(self, value):
+        if not isinstance(value, dict):
+            raise ValueError("data should be dict")
+
+        self._data = value
+
+    @property
+    def args(self):
+        """ Method position arguments.
+
+        :return tuple args: method position arguments.
+
+        """
+        return tuple(self.params) if isinstance(self.params, list) else ()
+
+    @property
+    def kwargs(self):
+        """ Method named arguments.
+
+        :return dict kwargs: method named arguments.
+
+        """
+        return self.params if isinstance(self.params, dict) else {}
+
+    @property
+    def json(self):
+        return self.serialize(self.data)
+
+
+class JSONRPCBaseResponse(JSONSerializable):
+
+    """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 responses."""
+
+    def __init__(self, **kwargs):
+        self.data = dict()
+
+        try:
+            self.result = kwargs['result']
+        except KeyError:
+            pass
+
+        try:
+            self.error = kwargs['error']
+        except KeyError:
+            pass
+
+        self._id = kwargs.get('_id')
+
+        if 'result' not in kwargs and 'error' not in kwargs:
+            raise ValueError("Either result or error should be used")
+
+    @property
+    def data(self):
+        return self._data
+
+    @data.setter
+    def data(self, value):
+        if not isinstance(value, dict):
+            raise ValueError("data should be dict")
+
+        self._data = value
+
+    @property
+    def json(self):
+        return self.serialize(self.data)
diff --git a/jsonrpc/dispatcher.py b/jsonrpc/dispatcher.py
new file mode 100644
index 0000000..2bf5e43
--- /dev/null
+++ b/jsonrpc/dispatcher.py
@@ -0,0 +1,122 @@
+""" Dispatcher is used to add methods (functions) to the server.
+
+For usage examples see :meth:`Dispatcher.add_method`
+
+"""
+import collections
+
+
+class Dispatcher(collections.MutableMapping):
+
+    """ Dictionary like object which maps method_name to method."""
+
+    def __init__(self, prototype=None):
+        """ Build method dispatcher.
+
+        Parameters
+        ----------
+        prototype : object or dict, optional
+            Initial method mapping.
+
+        Examples
+        --------
+
+        Init object with method dictionary.
+
+        >>> Dispatcher({"sum": lambda a, b: a + b})
+        None
+
+        """
+        self.method_map = dict()
+
+        if prototype is not None:
+            self.build_method_map(prototype)
+
+    def __getitem__(self, key):
+        return self.method_map[key]
+
+    def __setitem__(self, key, value):
+        self.method_map[key] = value
+
+    def __delitem__(self, key):
+        del self.method_map[key]
+
+    def __len__(self):
+        return len(self.method_map)
+
+    def __iter__(self):
+        return iter(self.method_map)
+
+    def __repr__(self):
+        return repr(self.method_map)
+
+    def add_class(self, cls):
+        prefix = cls.__name__.lower() + '.'
+        self.build_method_map(cls(), prefix)
+
+    def add_object(self, obj):
+        prefix = obj.__class__.__name__.lower() + '.'
+        self.build_method_map(obj, prefix)
+
+    def add_dict(self, dict, prefix=''):
+        if prefix:
+            prefix += '.'
+        self.build_method_map(dict, prefix)
+
+    def add_method(self, f, name=None):
+        """ Add a method to the dispatcher.
+
+        Parameters
+        ----------
+        f : callable
+            Callable to be added.
+        name : str, optional
+            Name to register (the default is function **f** name)
+
+        Notes
+        -----
+        When used as a decorator keeps callable object unmodified.
+
+        Examples
+        --------
+
+        Use as method
+
+        >>> d = Dispatcher()
+        >>> d.add_method(lambda a, b: a + b, name="sum")
+        <function __main__.<lambda>>
+
+        Or use as decorator
+
+        >>> d = Dispatcher()
+        >>> @d.add_method
+            def mymethod(*args, **kwargs):
+                print(args, kwargs)
+
+        """
+        self.method_map[name or f.__name__] = f
+        return f
+
+    def build_method_map(self, prototype, prefix=''):
+        """ Add prototype methods to the dispatcher.
+
+        Parameters
+        ----------
+        prototype : object or dict
+            Initial method mapping.
+            If given prototype is a dictionary then all callable objects will
+            be added to dispatcher.
+            If given prototype is an object then all public methods will
+            be used.
+        prefix: string, optional
+            Prefix of methods
+
+        """
+        if not isinstance(prototype, dict):
+            prototype = dict((method, getattr(prototype, method))
+                             for method in dir(prototype)
+                             if not method.startswith('_'))
+
+        for attr, method in prototype.items():
+            if callable(method):
+                self[prefix + attr] = method
diff --git a/jsonrpc/exceptions.py b/jsonrpc/exceptions.py
new file mode 100644
index 0000000..175ba92
--- /dev/null
+++ b/jsonrpc/exceptions.py
@@ -0,0 +1,185 @@
+""" JSON-RPC Exceptions."""
+from . import six
+import json
... 3848 lines suppressed ...

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/python-modules/packages/python-json-rpc.git



More information about the Python-modules-commits mailing list