├── jsonrpc ├── backend │ ├── __init__.py │ ├── flask.py │ └── django.py ├── tests │ ├── __init__.py │ ├── test_backend_django │ │ ├── __init__.py │ │ ├── urls.py │ │ ├── settings.py │ │ └── test_backend.py │ ├── test_backend_flask │ │ ├── __init__.py │ │ └── test_backend.py │ ├── test_jsonrpc.py │ ├── py35_utils.py │ ├── test_bug29.py │ ├── test_pep3107.py │ ├── test_base.py │ ├── test_dispatcher.py │ ├── test_utils.py │ ├── test_jsonrpc_errors.py │ ├── test_examples20.py │ ├── test_manager.py │ └── test_jsonrpc1.py ├── __init__.py ├── jsonrpc.py ├── base.py ├── utils.py ├── jsonrpc1.py ├── dispatcher.py ├── exceptions.py ├── manager.py ├── jsonrpc2.py └── six.py ├── docs ├── _static │ └── README.txt ├── requirements.txt ├── source │ ├── dispatcher.rst │ ├── jsonrpc.rst │ ├── index.rst │ ├── django_integration.rst │ ├── flask_integration.rst │ ├── quickstart.rst │ ├── exceptions.rst │ └── conf.py ├── make.bat └── Makefile ├── MANIFEST.in ├── setup.cfg ├── .gitignore ├── .coveragerc ├── Makefile ├── .github └── FUNDING.yml ├── examples ├── server.py └── client.py ├── ISSUE_TEMPLATE.md ├── LICENSE.txt ├── PULL_REQUEST_TEMPLATE.md ├── AUTHORS ├── tox.ini ├── .circleci └── config.yml ├── setup.py ├── changelog ├── CODE_OF_CONDUCT.md ├── README.rst └── CONTRIBUTING.md /jsonrpc/backend/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /jsonrpc/tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_django/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_flask/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /docs/_static/README.txt: -------------------------------------------------------------------------------- 1 | Place static files here. 2 | -------------------------------------------------------------------------------- /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | sphinx>=1.3 2 | sphinx_rtd_theme 3 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_jsonrpc.py: -------------------------------------------------------------------------------- 1 | """ Tets base JSON-RPC structures.""" 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.py 2 | include README.rst 3 | include LICENSE.txt 4 | include MANIFEST.in 5 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test=pytest 3 | 4 | [bdist_wheel] 5 | universal = 1 6 | 7 | [metadata] 8 | license_file = LICENSE.txt 9 | -------------------------------------------------------------------------------- /docs/source/dispatcher.rst: -------------------------------------------------------------------------------- 1 | Method dispatcher 2 | ================= 3 | 4 | .. automodule:: jsonrpc.dispatcher 5 | :members: 6 | :special-members: __init__ 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.egg 2 | *.egg-info 3 | *.py[c|o] 4 | .eggs/ 5 | .DS_Store 6 | .coverage 7 | .env 8 | .env3 9 | .ropeproject 10 | .tox 11 | build/ 12 | dist/ 13 | docs/_build/ 14 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_django/urls.py: -------------------------------------------------------------------------------- 1 | from django.conf.urls import url, include 2 | from jsonrpc.backend.django import api 3 | 4 | urlpatterns = [ 5 | url(r'', include(api.urls)), 6 | url(r'^prefix/', include(api.urls)), 7 | ] 8 | -------------------------------------------------------------------------------- /jsonrpc/tests/py35_utils.py: -------------------------------------------------------------------------------- 1 | # Python3.5+ code. 2 | # This won't even parse in earlier versions, so it's kept in a separate file 3 | # and imported when needed. 4 | 5 | 6 | def distance(a: float, b: float) -> float: 7 | return (a ** 2 + b ** 2) ** 0.5 8 | -------------------------------------------------------------------------------- /.coveragerc: -------------------------------------------------------------------------------- 1 | [run] 2 | omit= 3 | jsonrpc/six.py 4 | jsonrpc/tests/* 5 | source=jsonrpc 6 | 7 | [report] 8 | omit= 9 | jsonrpc/six.py 10 | jsonrpc/tests/* 11 | exclude_lines= 12 | raise NotImplementedError() 13 | def is_invalid_params_py2 14 | -------------------------------------------------------------------------------- /jsonrpc/__init__.py: -------------------------------------------------------------------------------- 1 | from .manager import JSONRPCResponseManager 2 | from .dispatcher import Dispatcher 3 | 4 | __version = (1, 15, 0) 5 | 6 | __version__ = version = '.'.join(map(str, __version)) 7 | __project__ = PROJECT = __name__ 8 | 9 | dispatcher = Dispatcher() 10 | 11 | # lint_ignore=W0611,W0401 12 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_django/settings.py: -------------------------------------------------------------------------------- 1 | SECRET_KEY = 'secret' 2 | ROOT_URLCONF = 'jsonrpc.tests.test_backend_django.urls' 3 | ALLOWED_HOSTS = ['testserver'] 4 | DATABASE_ENGINE = 'django.db.backends.sqlite3' 5 | DATABASES = { 6 | 'default': { 7 | 'ENGINE': 'django.db.backends.sqlite3', 8 | 'NAME': ':memory:', 9 | } 10 | } 11 | JSONRPC_MAP_VIEW_ENABLED = True 12 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: help 2 | # target: help - Display callable targets 3 | help: 4 | @egrep "^# target:" [Mm]akefile 5 | 6 | .PHONY: clean 7 | # target: clean - Display callable targets 8 | clean: 9 | @rm -rf build dist docs/_build 10 | @find . -name \*.py[co] -delete 11 | @find . -name *\__pycache__ -delete 12 | 13 | .PHONY: upload 14 | # target: upload - Upload module on PyPI 15 | upload: 16 | @python setup.py sdist bdist_wheel upload || echo 'Upload already' 17 | 18 | .PHONY: serve 19 | # target: serve - server docs 20 | serve: 21 | python3 -mhttp.server 22 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: pavlov99 4 | patreon: # Replace with a single Patreon username 5 | open_collective: json-rpc 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /docs/source/jsonrpc.rst: -------------------------------------------------------------------------------- 1 | jsonrpc Package 2 | =============== 3 | 4 | JSONRPC 5 | ------- 6 | 7 | .. automodule:: jsonrpc.jsonrpc 8 | :members: 9 | :undoc-members: 10 | :show-inheritance: 11 | 12 | Exceptions 13 | ---------- 14 | 15 | .. automodule:: jsonrpc.exceptions 16 | :members: 17 | :undoc-members: 18 | :show-inheritance: 19 | 20 | Manager 21 | ------- 22 | 23 | .. automodule:: jsonrpc.manager 24 | :members: 25 | :undoc-members: 26 | :show-inheritance: 27 | 28 | jsonrpc.backend.django module 29 | ----------------------------- 30 | 31 | .. automodule:: jsonrpc.backend.django 32 | :members: 33 | :undoc-members: 34 | :show-inheritance: 35 | -------------------------------------------------------------------------------- /jsonrpc/jsonrpc.py: -------------------------------------------------------------------------------- 1 | """ JSON-RPC wrappers for version 1.0 and 2.0. 2 | 3 | Objects diring init operation try to choose JSON-RPC 2.0 and in case of error 4 | JSON-RPC 1.0. 5 | from_json methods could decide what format is it by presence of 'jsonrpc' 6 | attribute. 7 | 8 | """ 9 | from .utils import JSONSerializable 10 | from .jsonrpc1 import JSONRPC10Request 11 | from .jsonrpc2 import JSONRPC20Request 12 | 13 | 14 | class JSONRPCRequest(JSONSerializable): 15 | 16 | """ JSONRPC Request.""" 17 | 18 | @classmethod 19 | def from_json(cls, json_str): 20 | data = cls.deserialize(json_str) 21 | return cls.from_data(data) 22 | 23 | @classmethod 24 | def from_data(cls, data): 25 | if isinstance(data, dict) and "jsonrpc" not in data: 26 | return JSONRPC10Request.from_data(data) 27 | else: 28 | return JSONRPC20Request.from_data(data) 29 | -------------------------------------------------------------------------------- /examples/server.py: -------------------------------------------------------------------------------- 1 | """ Example of json-rpc usage with Wergzeug and requests. 2 | 3 | NOTE: there are no Werkzeug and requests in dependencies of json-rpc. 4 | NOTE: server handles all url paths the same way (there are no different urls). 5 | 6 | """ 7 | 8 | from werkzeug.wrappers import Request, Response 9 | from werkzeug.serving import run_simple 10 | 11 | from jsonrpc import JSONRPCResponseManager, dispatcher 12 | 13 | 14 | @dispatcher.add_method 15 | def foobar(**kwargs): 16 | return kwargs["foo"] + kwargs["bar"] 17 | 18 | 19 | @Request.application 20 | def application(request): 21 | # Dispatcher is dictionary {: callable} 22 | dispatcher["echo"] = lambda s: s 23 | dispatcher["add"] = lambda a, b: a + b 24 | 25 | response = JSONRPCResponseManager.handle( 26 | request.get_data(cache=False, as_text=True), dispatcher) 27 | return Response(response.json, mimetype='application/json') 28 | 29 | 30 | if __name__ == '__main__': 31 | run_simple('localhost', 4000, application) 32 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_bug29.py: -------------------------------------------------------------------------------- 1 | """ Exmples of usage with tests. 2 | 3 | Tests in this file represent examples taken from JSON-RPC specification. 4 | http://www.jsonrpc.org/specification#examples 5 | 6 | """ 7 | import sys 8 | import json 9 | 10 | from ..manager import JSONRPCResponseManager 11 | 12 | if sys.version_info < (2, 7): 13 | import unittest2 as unittest 14 | else: 15 | import unittest 16 | 17 | 18 | def isjsonequal(json1, json2): 19 | return json.loads(json1) == json.loads(json2) 20 | 21 | 22 | class TestJSONRPCExamples(unittest.TestCase): 23 | def setUp(self): 24 | self.dispatcher = { 25 | "return_none": lambda: None, 26 | } 27 | 28 | def test_none_as_result(self): 29 | req = '{"jsonrpc": "2.0", "method": "return_none", "id": 0}' 30 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 31 | self.assertTrue(isjsonequal( 32 | response.json, 33 | '{"jsonrpc": "2.0", "result": null, "id": 0}' 34 | )) 35 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_pep3107.py: -------------------------------------------------------------------------------- 1 | from ..manager import JSONRPCResponseManager 2 | 3 | import sys 4 | 5 | if sys.version_info < (2, 7): 6 | import unittest2 as unittest 7 | else: 8 | import unittest 9 | 10 | 11 | class TestJSONRPCResponseManager(unittest.TestCase): 12 | @unittest.skipIf(sys.version_info < (3, 5), "Test Py3.5+ functionality") 13 | def test_typeerror_with_annotations(self): 14 | """If a function has Python3 annotations and is called with improper 15 | arguments, make sure the framework doesn't fail with inspect.getargspec 16 | """ 17 | from .py35_utils import distance 18 | 19 | dispatcher = { 20 | "distance": distance, 21 | } 22 | 23 | req = '{"jsonrpc": "2.0", "method": "distance", "params": [], "id": 1}' 24 | result = JSONRPCResponseManager.handle(req, dispatcher) 25 | 26 | # Make sure this returns JSONRPCInvalidParams rather than raising 27 | # UnboundLocalError 28 | self.assertEqual(result.error['code'], -32602) 29 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_base.py: -------------------------------------------------------------------------------- 1 | """ Test base JSON-RPC classes.""" 2 | import sys 3 | 4 | from ..base import JSONRPCBaseRequest, JSONRPCBaseResponse 5 | 6 | if sys.version_info < (2, 7): 7 | import unittest2 as unittest 8 | else: 9 | import unittest 10 | 11 | 12 | class TestJSONRPCBaseRequest(unittest.TestCase): 13 | 14 | """ Test JSONRPCBaseRequest functionality.""" 15 | 16 | def test_data(self): 17 | request = JSONRPCBaseRequest() 18 | self.assertEqual(request.data, {}) 19 | 20 | with self.assertRaises(ValueError): 21 | request.data = [] 22 | 23 | with self.assertRaises(ValueError): 24 | request.data = None 25 | 26 | 27 | class TestJSONRPCBaseResponse(unittest.TestCase): 28 | 29 | """ Test JSONRPCBaseResponse functionality.""" 30 | 31 | def test_data(self): 32 | response = JSONRPCBaseResponse(result="") 33 | self.assertEqual(response.data, {}) 34 | 35 | with self.assertRaises(ValueError): 36 | response.data = [] 37 | 38 | with self.assertRaises(ValueError): 39 | response.data = None 40 | -------------------------------------------------------------------------------- /ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 9 | 10 | ### Description 11 | 12 | [Description of the issue] 13 | 14 | ### Steps to Reproduce 15 | 16 | 1. [First Step] 17 | 2. [Second Step] 18 | 3. [and so on...] 19 | 20 | **Expected behavior:** [What you expect to happen] 21 | 22 | **Actual behavior:** [What actually happens] 23 | 24 | **Reproduces how often:** [What percentage of the time does it reproduce?] 25 | 26 | ### Versions 27 | 28 | You can get this information from copy and pasting the output of `python --version` from the command line. Also, please include the OS and what version of the OS you're running. 29 | 30 | ### Additional Information 31 | 32 | Any additional information, configuration or data that might be necessary to reproduce the issue. 33 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2013-2018 Kirill Pavlov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Requirements 2 | 3 | * Filling out the template is required. Any pull request that does not include enough information to be reviewed in a timely manner may be closed at the maintainers' discretion. 4 | * All new code requires tests to ensure against regressions. 5 | * If pull request breaks tests it would not be merged. 6 | 7 | ### Description of the Change 8 | 9 | 14 | 15 | ### Alternate Designs 16 | 17 | 18 | 19 | ### Benefits 20 | 21 | 22 | 23 | ### Possible Drawbacks 24 | 25 | 26 | 27 | ### Applicable Issues 28 | 29 | 30 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Here is an inevitably incomplete list of MUCH-APPRECIATED CONTRIBUTORS -- 2 | people who have submitted patches, reported bugs, added translations, helped 3 | answer newbie questions, and generally made json-rpc that much better: 4 | 5 | Contributors 6 | ------------ 7 | Kirill Pavlov (@pavlov99) 8 | Jan Willems (@jw) 9 | Robby Dermody (@robby-dermody) 10 | Mateusz Pawlik (@matee911) 11 | Malyshev Artem (@proofit404) 12 | Julian Hille (@julianhille) 13 | Pavel Evdokimov (@Santinell) 14 | Lev Orekhov (@lorehov) 15 | Sergey Nikitin (@nikitinsm) 16 | Jean-Christophe Bohin (@jcbohin) 17 | Arne Brutschy (@arnuschky) 18 | Piper Merriam (pipermerriam) 19 | Luke Lee (@durden) 20 | Mike Purvis (@mikepurvis) 21 | Seth Hill (@sethrh) 22 | Sergey Magafurov (@smagafurov) 23 | Laurent Mazuel (@lmazuel) 24 | Igor Melnyk (@liminspace) 25 | Ghislain Antony Vaillant (@ghisvail) 26 | Chris Jerdonek (@cjerdonek) 27 | Paulie Peña (@ppena-LiveData) 28 | Matt Fisher (@MattFisher) 29 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | .. json-rpc documentation master file, created by 2 | sphinx-quickstart on Sun Oct 13 15:41:10 2013. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | JSON-RPC transport implementation 7 | ================================= 8 | 9 | :Source code: https://github.com/pavlov99/json-rpc 10 | :Issue tracker: https://github.com/pavlov99/json-rpc/issues 11 | 12 | JSON-RPC is a stateless, light-weight remote procedure call (RPC) protocol. Primarily this specification defines several data structures and the rules around their processing. It is transport agnostic in that the concepts can be used within the same process, over sockets, over http, or in many various message passing environments. It uses JSON (RFC 4627) as data format. 13 | 14 | .. raw:: html 15 | 16 | 17 | 18 | Features 19 | -------- 20 | 21 | * Supports `JSON-RPC2.0 `_ and `JSON-RPC1.0 `_ 22 | * Implementation is complete and 100% tested 23 | * Does not depend on transport realisation, no external dependencies 24 | * It comes with request manager and optional Django support 25 | * Compatible with Python 2.6, 2.7, 3.x >= 3.2, PyPy 26 | 27 | Contents 28 | -------- 29 | 30 | .. toctree:: 31 | :maxdepth: 2 32 | 33 | quickstart 34 | dispatcher 35 | exceptions 36 | django_integration 37 | flask_integration 38 | 39 | jsonrpc 40 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py{26, 27, 33, 34, 35, 36, 37, 38}, pypy, pypy3, pycodestyle, cov 3 | 4 | [testenv] 5 | commands = pytest 6 | setenv = DJANGO_SETTINGS_MODULE=jsonrpc.tests.test_backend_django.settings 7 | deps = 8 | pytest==5.2.2 9 | Django==2.2.7 10 | Flask==1.1.1 11 | 12 | # Python 2.6 configuration. Latest Django support is 1.6 13 | [testenv:py26] 14 | deps = 15 | pytest==4.0.2 16 | attrs==19.1.0 17 | Django==1.6 18 | Flask==0.12.2 19 | mock==2.0.0 20 | unittest2==1.1.0 21 | 22 | # Python 2.7 configuration. 23 | # Django 1.11 is likely to be the last version to support Python 2.7 24 | # https://www.djangoproject.com/weblog/2015/jun/25/roadmap/ 25 | [testenv:py27] 26 | deps = 27 | pytest==4.0.2 28 | attrs==19.1.0 29 | mock==2.0.0 30 | Django==1.11 31 | Flask==0.12.2 32 | 33 | [testenv:py33] 34 | deps = 35 | pytest==4.0.2 36 | attrs==19.1.0 37 | Django==1.11 38 | Flask==0.12.2 39 | 40 | [testenv:py34] 41 | deps = 42 | pytest==4.0.2 43 | attrs==19.1.0 44 | Django==1.11 45 | Flask==0.12.2 46 | 47 | [testenv:pypy] 48 | deps = 49 | pytest==4.0.2 50 | attrs==19.1.0 51 | mock==2.0.0 52 | Django==1.11 53 | Flask==0.12.2 54 | 55 | [testenv:pycodestyle] 56 | deps = pycodestyle 57 | commands = pycodestyle setup.py jsonrpc --exclude=jsonrpc/six.py --show-source --show-pep8 58 | 59 | [testenv:pylama] 60 | deps = pylama==1.5.4 61 | commands = pylama --linters=pep8,pep257,mccabe,pyflakes,pylint jsonrpc 62 | 63 | [testenv:cov] 64 | deps = 65 | {[testenv]deps} 66 | coverage==4.5.2 67 | codecov==2.0.15 68 | 69 | commands = 70 | coverage run -m pytest 71 | coverage report 72 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | workflows: 3 | version: 2 4 | test: 5 | jobs: 6 | - py27 7 | - py34 8 | - py35 9 | - py36 10 | - py37 11 | - py38 12 | jobs: 13 | py36: &test-template 14 | docker: 15 | - image: circleci/python:3.6 16 | working_directory: ~/repo 17 | steps: 18 | - checkout 19 | - run: 20 | name: Install test dependencies 21 | command: | 22 | python -m venv venv || virtualenv venv 23 | venv/bin/pip install tox 24 | - run: 25 | name: Run tests 26 | command: | 27 | venv/bin/tox -e $CIRCLE_JOB 28 | py27: 29 | <<: *test-template 30 | docker: 31 | - image: circleci/python:2.7 32 | py33: 33 | <<: *test-template 34 | docker: 35 | - image: circleci/python:3.3 36 | py34: 37 | <<: *test-template 38 | docker: 39 | - image: circleci/python:3.4 40 | py35: 41 | <<: *test-template 42 | docker: 43 | - image: circleci/python:3.5 44 | py37: 45 | <<: *test-template 46 | docker: 47 | - image: circleci/python:3.7 48 | py38: 49 | <<: *test-template 50 | docker: 51 | - image: circleci/python:3.8 52 | pycodestyle: 53 | <<: *test-template 54 | cov: 55 | <<: *test-template 56 | steps: 57 | - checkout 58 | - run: 59 | name: Install test dependencies 60 | command: | 61 | python -m venv venv || virtualenv venv 62 | venv/bin/pip install tox 63 | - run: 64 | name: Generate coverage report 65 | command: | 66 | venv/bin/tox -e $CIRCLE_JOB 67 | .tox/cov/bin/codecov --token db4c9cc4-799b-49b0-ab9a-51dde80fb946 68 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import os.path 3 | import sys 4 | from setuptools import setup, find_packages 5 | from jsonrpc import version 6 | 7 | 8 | def read(fname): 9 | try: 10 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 11 | except IOError: 12 | return "" 13 | 14 | 15 | setup_requires = ["pytest-runner"] if sys.argv in ['pytest', 'test'] else [] 16 | 17 | setup( 18 | name="json-rpc", 19 | version=version, 20 | packages=find_packages(), 21 | setup_requires=setup_requires, 22 | tests_require=["pytest"], 23 | 24 | # metadata for upload to PyPI 25 | author="Kirill Pavlov", 26 | author_email="k@p99.io", 27 | url="https://github.com/pavlov99/json-rpc", 28 | description="JSON-RPC transport implementation", 29 | long_description=read('README.rst'), 30 | 31 | # Full list: 32 | # https://pypi.python.org/pypi?%3Aaction=list_classifiers 33 | classifiers=[ 34 | "Development Status :: 5 - Production/Stable", 35 | "Environment :: Console", 36 | "License :: OSI Approved :: MIT License", 37 | "Natural Language :: English", 38 | "Operating System :: OS Independent", 39 | "Programming Language :: Python :: 2.6", 40 | "Programming Language :: Python :: 2.7", 41 | "Programming Language :: Python :: 3.3", 42 | "Programming Language :: Python :: 3.4", 43 | "Programming Language :: Python :: 3.5", 44 | "Programming Language :: Python :: 3.6", 45 | "Programming Language :: Python :: 3.7", 46 | "Programming Language :: Python :: 3.8", 47 | "Programming Language :: Python :: Implementation :: PyPy", 48 | "Topic :: Software Development :: Libraries :: Python Modules", 49 | ], 50 | license="MIT", 51 | ) 52 | -------------------------------------------------------------------------------- /docs/source/django_integration.rst: -------------------------------------------------------------------------------- 1 | Integration with Django 2 | ======================= 3 | 4 | .. note:: Django backend is optionally supported. Library itself does not depend on Django. 5 | 6 | Django integration is similar project to project. Starting from version 1.8.4 json-rpc support it and provides convenient way of integration. To add json-rpc to Django project follow steps. 7 | 8 | Create api instance 9 | ------------------- 10 | 11 | If you want to use default (global) object, skip this step. In most cases it is enougth to start with it, even if you plan to add another version later. Default api is located here: 12 | 13 | .. code-block:: python 14 | 15 | from jsonrpc.backend.django import api 16 | 17 | 18 | If you would like to use different api versions (not, you could name methods differently) or use cudtom dispatcher, use 19 | 20 | .. code-block:: python 21 | 22 | from jsonrpc.backend.django import JSONRPCAPI 23 | api = JSONRPCAPI(dispatcher=) 24 | 25 | Later on we assume that you use default api instance 26 | 27 | Add api urls to the project 28 | --------------------------- 29 | 30 | In your urls.py file add 31 | 32 | .. code-block:: python 33 | 34 | urlpatterns = patterns( 35 | ... 36 | url(r'^api/jsonrpc/', include(api.urls)), 37 | ) 38 | 39 | Add methods to api 40 | ------------------ 41 | 42 | .. code-block:: python 43 | 44 | @api.dispatcher.add_method 45 | def my_method(request, *args, **kwargs): 46 | return args, kwargs 47 | 48 | .. note:: first argument of each method should be request. In this case it is possible to get user and control access to data 49 | 50 | Make requests to api 51 | -------------------- 52 | 53 | To use api, send `POST` request to api address. Make sure your message has correct format. 54 | Also json-rpc generates method's map. It is available at `/map` url. 55 | -------------------------------------------------------------------------------- /docs/source/flask_integration.rst: -------------------------------------------------------------------------------- 1 | Integration with Flask 2 | ====================== 3 | 4 | .. note:: Flask backend is optionaly supported. Library itself does not depend on Flask. 5 | 6 | Create api instance 7 | ------------------- 8 | 9 | If you want to use default (global) object, skip this step. In most cases it is enough to start with it, even if you plan to add another version later. Default api is located here: 10 | 11 | .. code-block:: python 12 | 13 | from jsonrpc.backend.flask import api 14 | 15 | 16 | If you would like to use different api versions (not, you could name methods differently) or use custom dispatcher, use 17 | 18 | .. code-block:: python 19 | 20 | from jsonrpc.backend.flask import JSONRPCAPI 21 | api = JSONRPCAPI(dispatcher=) 22 | 23 | Later on we assume that you use default api instance. 24 | 25 | Add api endpoint to the project 26 | ------------------------------- 27 | 28 | You have to options to add new endpoint to your Flask application. 29 | 30 | First - register as a blueprint. In this case, as small bonus, you got a /map handler, which prints all registered methods. 31 | 32 | .. code-block:: python 33 | 34 | from flask import Flask 35 | 36 | from jsonrpc.backend.flask import api 37 | 38 | app = Flask(__name__) 39 | app.register_blueprint(api.as_blueprint()) 40 | 41 | 42 | Second - register as a usual view. 43 | 44 | .. code-block:: python 45 | 46 | from flask import Flask 47 | 48 | from jsonrpc.backend.flask import api 49 | 50 | app = Flask(__name__) 51 | app.add_url_rule('/', 'api', api.as_view(), methods=['POST']) 52 | 53 | 54 | Add methods to api 55 | ------------------ 56 | 57 | .. code-block:: python 58 | 59 | @api.dispatcher.add_method 60 | def my_method(*args, **kwargs): 61 | return args, kwargs 62 | 63 | 64 | Make requests to api 65 | -------------------- 66 | 67 | To use api, send `POST` request to api address. Make sure your message has correct format. 68 | -------------------------------------------------------------------------------- /examples/client.py: -------------------------------------------------------------------------------- 1 | import requests 2 | import json 3 | 4 | 5 | def main(): 6 | url = "http://localhost:4000/jsonrpc" 7 | headers = {'content-type': 'application/json'} 8 | 9 | # Example echo method 10 | payload = { 11 | "method": "echo", 12 | "params": ["echome!"], 13 | "jsonrpc": "2.0", 14 | "id": 0, 15 | } 16 | response = requests.post( 17 | url, data=json.dumps(payload), headers=headers).json() 18 | 19 | assert response["result"] == "echome!" 20 | assert response["jsonrpc"] == "2.0" 21 | assert response["id"] == 0 22 | 23 | # Example echo method JSON-RPC 1.0 24 | payload = { 25 | "method": "echo", 26 | "params": ["echome!"], 27 | "id": 0, 28 | } 29 | response = requests.post( 30 | url, data=json.dumps(payload), headers=headers).json() 31 | 32 | assert response["result"] == "echome!" 33 | assert response["error"] is None 34 | assert response["id"] == 0 35 | assert "jsonrpc" not in response 36 | 37 | # Example add method 38 | payload = { 39 | "method": "add", 40 | "params": [1, 2], 41 | "jsonrpc": "2.0", 42 | "id": 1, 43 | } 44 | response = requests.post( 45 | url, data=json.dumps(payload), headers=headers).json() 46 | 47 | assert response["result"] == 3 48 | assert response["jsonrpc"] == "2.0" 49 | assert response["id"] == 1 50 | 51 | # Example foobar method 52 | payload = { 53 | "method": "foobar", 54 | "params": {"foo": "json", "bar": "-rpc"}, 55 | "jsonrpc": "2.0", 56 | "id": 3, 57 | } 58 | response = requests.post( 59 | url, data=json.dumps(payload), headers=headers).json() 60 | 61 | assert response["result"] == "json-rpc" 62 | assert response["jsonrpc"] == "2.0" 63 | assert response["id"] == 3 64 | 65 | # Example exception 66 | payload = { 67 | "method": "add", 68 | "params": [0], 69 | "jsonrpc": "2.0", 70 | "id": 4, 71 | } 72 | response = requests.post( 73 | url, data=json.dumps(payload), headers=headers).json() 74 | 75 | assert response["error"]["message"] == "Invalid params" 76 | assert response["error"]["code"] == -32602 77 | assert response["jsonrpc"] == "2.0" 78 | assert response["id"] == 4 79 | 80 | 81 | if __name__ == "__main__": 82 | main() 83 | -------------------------------------------------------------------------------- /jsonrpc/base.py: -------------------------------------------------------------------------------- 1 | from .utils import JSONSerializable 2 | 3 | 4 | class JSONRPCBaseRequest(JSONSerializable): 5 | 6 | """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 requests.""" 7 | 8 | def __init__(self, method=None, params=None, _id=None, 9 | is_notification=None): 10 | self.data = dict() 11 | self.method = method 12 | self.params = params 13 | self._id = _id 14 | self.is_notification = is_notification 15 | 16 | @property 17 | def data(self): 18 | return self._data 19 | 20 | @data.setter 21 | def data(self, value): 22 | if not isinstance(value, dict): 23 | raise ValueError("data should be dict") 24 | 25 | self._data = value 26 | 27 | @property 28 | def args(self): 29 | """ Method position arguments. 30 | 31 | :return tuple args: method position arguments. 32 | 33 | """ 34 | return tuple(self.params) if isinstance(self.params, list) else () 35 | 36 | @property 37 | def kwargs(self): 38 | """ Method named arguments. 39 | 40 | :return dict kwargs: method named arguments. 41 | 42 | """ 43 | return self.params if isinstance(self.params, dict) else {} 44 | 45 | @property 46 | def json(self): 47 | return self.serialize(self.data) 48 | 49 | 50 | class JSONRPCBaseResponse(JSONSerializable): 51 | 52 | """ Base class for JSON-RPC 1.0 and JSON-RPC 2.0 responses.""" 53 | 54 | def __init__(self, **kwargs): 55 | self.data = dict() 56 | 57 | try: 58 | self.result = kwargs['result'] 59 | except KeyError: 60 | pass 61 | 62 | try: 63 | self.error = kwargs['error'] 64 | except KeyError: 65 | pass 66 | 67 | self._id = kwargs.get('_id') 68 | 69 | if 'result' not in kwargs and 'error' not in kwargs: 70 | raise ValueError("Either result or error should be used") 71 | 72 | self.request = None # type: JSONRPCBaseRequest 73 | 74 | @property 75 | def data(self): 76 | return self._data 77 | 78 | @data.setter 79 | def data(self, value): 80 | if not isinstance(value, dict): 81 | raise ValueError("data should be dict") 82 | 83 | self._data = value 84 | 85 | @property 86 | def json(self): 87 | return self.serialize(self.data) 88 | -------------------------------------------------------------------------------- /docs/source/quickstart.rst: -------------------------------------------------------------------------------- 1 | Quickstart 2 | ========== 3 | 4 | Installation 5 | ------------ 6 | 7 | .. highlight:: bash 8 | 9 | :Requirements: **Python 2.6, 2.7**, **Python 3.x >= 3.2** or **PyPy** 10 | 11 | To install the latest released version of package:: 12 | 13 | pip install json-rpc 14 | 15 | Integration 16 | ----------- 17 | 18 | Package is transport agnostic, integration depends on you framework. As an example we have server with `Werkzeug `_ and client with `requests `_. 19 | 20 | Server 21 | 22 | .. code-block:: python 23 | 24 | from werkzeug.wrappers import Request, Response 25 | from werkzeug.serving import run_simple 26 | 27 | from jsonrpc import JSONRPCResponseManager, dispatcher 28 | 29 | 30 | @dispatcher.add_method 31 | def foobar(**kwargs): 32 | return kwargs["foo"] + kwargs["bar"] 33 | 34 | 35 | @Request.application 36 | def application(request): 37 | # Dispatcher is dictionary {: callable} 38 | dispatcher["echo"] = lambda s: s 39 | dispatcher["add"] = lambda a, b: a + b 40 | 41 | response = JSONRPCResponseManager.handle( 42 | request.data, dispatcher) 43 | return Response(response.json, mimetype='application/json') 44 | 45 | 46 | if __name__ == '__main__': 47 | run_simple('localhost', 4000, application) 48 | 49 | Client 50 | 51 | .. code-block:: python 52 | 53 | import requests 54 | import json 55 | 56 | 57 | def main(): 58 | url = "http://localhost:4000/jsonrpc" 59 | headers = {'content-type': 'application/json'} 60 | 61 | # Example echo method 62 | payload = { 63 | "method": "echo", 64 | "params": ["echome!"], 65 | "jsonrpc": "2.0", 66 | "id": 0, 67 | } 68 | response = requests.post( 69 | url, data=json.dumps(payload), headers=headers).json() 70 | 71 | assert response["result"] == "echome!" 72 | assert response["jsonrpc"] 73 | assert response["id"] == 0 74 | 75 | if __name__ == "__main__": 76 | main() 77 | 78 | Package ensures that request and response messages have correct format. 79 | Besides that it provides :class:`jsonrpc.manager.JSONRPCResponseManager` which handles server common cases, such as incorrect message format or invalid method parameters. 80 | Futher topics describe how to add methods to manager, how to handle custom exceptions and optional Django integration. 81 | -------------------------------------------------------------------------------- /jsonrpc/backend/flask.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | import copy 4 | import json 5 | import logging 6 | import time 7 | from uuid import uuid4 8 | 9 | from flask import Blueprint, request, Response 10 | 11 | from ..exceptions import JSONRPCInvalidRequestException 12 | from ..jsonrpc import JSONRPCRequest 13 | from ..manager import JSONRPCResponseManager 14 | from ..utils import DatetimeDecimalEncoder 15 | from ..dispatcher import Dispatcher 16 | 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | class JSONRPCAPI(object): 22 | def __init__(self, dispatcher=None, check_content_type=True): 23 | """ 24 | 25 | :param dispatcher: methods dispatcher 26 | :param check_content_type: if True - content-type must be 27 | "application/json" 28 | :return: 29 | 30 | """ 31 | self.dispatcher = dispatcher if dispatcher is not None \ 32 | else Dispatcher() 33 | self.check_content_type = check_content_type 34 | 35 | def as_blueprint(self, name=None): 36 | blueprint = Blueprint(name if name else str(uuid4()), __name__) 37 | blueprint.add_url_rule( 38 | '/', view_func=self.jsonrpc, methods=['POST']) 39 | blueprint.add_url_rule( 40 | '/map', view_func=self.jsonrpc_map, methods=['GET']) 41 | return blueprint 42 | 43 | def as_view(self): 44 | return self.jsonrpc 45 | 46 | def jsonrpc(self): 47 | request_str = self._get_request_str() 48 | try: 49 | jsonrpc_request = JSONRPCRequest.from_json(request_str) 50 | except (TypeError, ValueError, JSONRPCInvalidRequestException): 51 | response = JSONRPCResponseManager.handle( 52 | request_str, self.dispatcher) 53 | else: 54 | response = JSONRPCResponseManager.handle_request( 55 | jsonrpc_request, self.dispatcher) 56 | 57 | if response: 58 | response.serialize = self._serialize 59 | response = response.json 60 | 61 | return Response(response, content_type="application/json") 62 | 63 | def jsonrpc_map(self): 64 | """ Map of json-rpc available calls. 65 | 66 | :return str: 67 | 68 | """ 69 | result = "

JSON-RPC map

{0}
".format("\n\n".join([ 70 | "{0}: {1}".format(fname, f.__doc__) 71 | for fname, f in self.dispatcher.items() 72 | ])) 73 | return Response(result) 74 | 75 | def _get_request_str(self): 76 | if self.check_content_type or request.data: 77 | return request.data 78 | return list(request.form.keys())[0] 79 | 80 | @staticmethod 81 | def _serialize(s): 82 | return json.dumps(s, cls=DatetimeDecimalEncoder) 83 | 84 | 85 | api = JSONRPCAPI() 86 | -------------------------------------------------------------------------------- /changelog: -------------------------------------------------------------------------------- 1 | 2023-06-11 Kirill Pavlov 2 | 3 | * ADD: support for Django>=4.0 url template 4 | 5 | 2022-12-23 Kirill Pavlov 6 | 7 | * ADD: context arguments to dispatcher 8 | 9 | 2020-01-06 Kirill Pavlov 10 | 11 | * FIX: positional arguments support for Django backend 12 | 13 | 2019-10-17 Kirill Pavlov 14 | 15 | * ADD: python3.8 support 16 | 17 | 2019-01-12 Kirill Pavlov 18 | 19 | * ADD: Ability to override function name with decorator convention in 20 | dispatcher 21 | * REF: Improve function parameter introspection: use more stable 22 | approach for python3, allow both args and kwards parameters check at 23 | the same time. 24 | * TST: Switch from nose and nose2 to pytest 25 | * TST: Switch from Travis CI to CircleCI, test py26-py37 26 | * TST: Switch from coveralls to codecov service 27 | * DEL: Remove Flask logging (it broke batch requests) 28 | * DEL: Clean Makefile shortcuts, remove unused ones 29 | * DOC: Add opencollective badge 30 | 31 | 2018-08-26 Kirill Pavlov 32 | 33 | * Add license file to the dist/ 34 | 35 | 2016-01-31 Kirill Pavlov 36 | 37 | * Drop support of python 3.2. Pip does not support it, which leads to 38 | tests fail 39 | 40 | 2015-08-07 Kirill Pavlov 41 | 42 | * Allow custom empty dispatcher parameter for backend-specific api 43 | 44 | 2015-06-29 Kirill Pavlov 45 | 46 | * Flask backend support by Lev Orekhov 47 | (https://github.com/lorehov) 48 | 49 | 2015-06-03 Kirill Pavlov 50 | 51 | * Added support of method prefixes 52 | https://github.com/pavlov99/json-rpc/pull/31 53 | 54 | 2015-05-05 Kirill Pavlov 55 | 56 | * Add logger to django api client 57 | 58 | 2014-09-04 Kirill Pavlov 59 | 60 | * Add custom exception functionality by @julianhille 61 | 62 | 2014-05-25 Kirill Pavlov 63 | 64 | * Add python 2.6 support 65 | * Update server notification processing 66 | * Add functionality to dispatcher, it is possible to init it with 67 | class 68 | 69 | 2013-11-09 Kirill Pavlov 70 | 71 | * Add JSON-RPC 1.0 support. 72 | * Add dispatcher for functions. 73 | * Add notification support (separate notification and id=null for 74 | JSON-RPC 2.0 request). 75 | * Add custom json serializer (based on json) with datetime.Datetime 76 | and decimal.Decimal serialization support. 77 | * Move JSONRPC* classes to JSONRPC20*, as far as there is JSONRPC10*. 78 | * Add dispatcher and JSONRPCManager to jsonrpc/__init__, they are no 79 | longer in jsonrpc.jsonrpc module. 80 | 81 | 2013-10-13 Kirill Pavlov 82 | 83 | * Add examples of usage. 84 | * Init documentation. 85 | * Remove six from dependencies. 86 | 87 | 2013-10-08 Kirill Pavlov 88 | 89 | * Implement JSON-RPC 2.0 specification. 90 | -------------------------------------------------------------------------------- /jsonrpc/backend/django.py: -------------------------------------------------------------------------------- 1 | from __future__ import absolute_import 2 | 3 | from django.views.decorators.csrf import csrf_exempt 4 | 5 | try: 6 | from django.conf.urls import url # Django <4.0 7 | except ImportError: 8 | from django.urls import re_path as url # Django >=4.0 9 | 10 | from django.conf import settings 11 | from django.http import HttpResponse, HttpResponseNotAllowed 12 | import json 13 | import logging 14 | import time 15 | 16 | from ..exceptions import JSONRPCInvalidRequestException 17 | from ..jsonrpc import JSONRPCRequest 18 | from ..manager import JSONRPCResponseManager 19 | from ..utils import DatetimeDecimalEncoder 20 | from ..dispatcher import Dispatcher 21 | 22 | 23 | logger = logging.getLogger(__name__) 24 | 25 | 26 | def response_serialize(obj): 27 | """ Serializes response's data object to JSON. """ 28 | return json.dumps(obj, cls=DatetimeDecimalEncoder) 29 | 30 | 31 | class JSONRPCAPI(object): 32 | def __init__(self, dispatcher=None): 33 | self.dispatcher = dispatcher if dispatcher is not None \ 34 | else Dispatcher() 35 | 36 | @property 37 | def urls(self): 38 | urls = [ 39 | url(r'^$', self.jsonrpc, name='endpoint'), 40 | ] 41 | 42 | if getattr(settings, 'JSONRPC_MAP_VIEW_ENABLED', settings.DEBUG): 43 | urls.append( 44 | url(r'^map$', self.jsonrpc_map, name='map') 45 | ) 46 | 47 | return urls 48 | 49 | @csrf_exempt 50 | def jsonrpc(self, request): 51 | """ JSON-RPC 2.0 handler.""" 52 | 53 | def inject_request(jsonrpc_request): 54 | jsonrpc_request.params = jsonrpc_request.params or {} 55 | if isinstance(jsonrpc_request.params, dict): 56 | jsonrpc_request.params.update(request=request) 57 | if isinstance(jsonrpc_request.params, list): 58 | jsonrpc_request.params.insert(0, request) 59 | 60 | if request.method != "POST": 61 | return HttpResponseNotAllowed(["POST"]) 62 | 63 | request_str = request.body.decode('utf8') 64 | try: 65 | jsonrpc_request = JSONRPCRequest.from_json(request_str) 66 | except (TypeError, ValueError, JSONRPCInvalidRequestException): 67 | response = JSONRPCResponseManager.handle( 68 | request_str, self.dispatcher) 69 | else: 70 | requests = getattr(jsonrpc_request, 'requests', [jsonrpc_request]) 71 | for jsonrpc_req in requests: 72 | inject_request(jsonrpc_req) 73 | 74 | response = JSONRPCResponseManager.handle_request( 75 | jsonrpc_request, self.dispatcher) 76 | 77 | if response: 78 | response.serialize = response_serialize 79 | response = response.json 80 | 81 | return HttpResponse(response, content_type="application/json") 82 | 83 | def jsonrpc_map(self, request): 84 | """ Map of json-rpc available calls. 85 | 86 | :return str: 87 | 88 | """ 89 | result = "

JSON-RPC map

{0}
".format("\n\n".join([ 90 | "{0}: {1}".format(fname, f.__doc__) 91 | for fname, f in self.dispatcher.items() 92 | ])) 93 | return HttpResponse(result) 94 | 95 | 96 | api = JSONRPCAPI() 97 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [json-rpc@p99.io](mailto:json-rpc@p99.io). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant](https://www.contributor-covenant.org), version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_dispatcher.py: -------------------------------------------------------------------------------- 1 | from ..dispatcher import Dispatcher 2 | import sys 3 | if sys.version_info < (2, 7): 4 | import unittest2 as unittest 5 | else: 6 | import unittest 7 | 8 | 9 | class Math: 10 | 11 | def sum(self, a, b): 12 | return a + b 13 | 14 | def diff(self, a, b): 15 | return a - b 16 | 17 | 18 | class TestDispatcher(unittest.TestCase): 19 | 20 | """ Test Dispatcher functionality.""" 21 | 22 | def test_getter(self): 23 | d = Dispatcher() 24 | 25 | with self.assertRaises(KeyError): 26 | d["method"] 27 | 28 | d["add"] = lambda *args: sum(args) 29 | self.assertEqual(d["add"](1, 1), 2) 30 | 31 | def test_in(self): 32 | d = Dispatcher() 33 | d["method"] = lambda: "" 34 | self.assertIn("method", d) 35 | 36 | def test_add_method(self): 37 | d = Dispatcher() 38 | 39 | @d.add_method 40 | def add(x, y): 41 | return x + y 42 | 43 | self.assertIn("add", d) 44 | self.assertEqual(d["add"](1, 1), 2) 45 | 46 | def test_add_method_with_name(self): 47 | d = Dispatcher() 48 | 49 | @d.add_method(name="this.add") 50 | def add(x, y): 51 | return x + y 52 | 53 | self.assertNotIn("add", d) 54 | self.assertIn("this.add", d) 55 | self.assertEqual(d["this.add"](1, 1), 2) 56 | 57 | def test_add_method_with_context(self): 58 | d = Dispatcher() 59 | 60 | @d.add_method(context_arg="context") 61 | def x_plus_id(x, context): 62 | return x + context["id"] 63 | 64 | self.assertEqual(d.context_arg_for_method["x_plus_id"], "context") 65 | 66 | def test_add_class(self): 67 | d = Dispatcher() 68 | d.add_class(Math) 69 | 70 | self.assertIn("math.sum", d) 71 | self.assertIn("math.diff", d) 72 | self.assertEqual(d["math.sum"](3, 8), 11) 73 | self.assertEqual(d["math.diff"](6, 9), -3) 74 | 75 | def test_add_object(self): 76 | d = Dispatcher() 77 | d.add_object(Math()) 78 | 79 | self.assertIn("math.sum", d) 80 | self.assertIn("math.diff", d) 81 | self.assertEqual(d["math.sum"](5, 2), 7) 82 | self.assertEqual(d["math.diff"](15, 9), 6) 83 | 84 | def test_add_dict(self): 85 | d = Dispatcher() 86 | d.add_dict({"sum": lambda *args: sum(args)}, "util") 87 | 88 | self.assertIn("util.sum", d) 89 | self.assertEqual(d["util.sum"](13, -2), 11) 90 | 91 | def test_add_method_keep_function_definitions(self): 92 | 93 | d = Dispatcher() 94 | 95 | @d.add_method 96 | def one(x): 97 | return x 98 | 99 | self.assertIsNotNone(one) 100 | 101 | def test_del_method(self): 102 | d = Dispatcher() 103 | d["method"] = lambda: "" 104 | self.assertIn("method", d) 105 | 106 | del d["method"] 107 | self.assertNotIn("method", d) 108 | 109 | def test_to_dict(self): 110 | d = Dispatcher() 111 | 112 | def func(): 113 | return "" 114 | 115 | d["method"] = func 116 | self.assertEqual(dict(d), {"method": func}) 117 | 118 | def test_init_from_object_instance(self): 119 | 120 | class Dummy(): 121 | 122 | def one(self): 123 | pass 124 | 125 | def two(self): 126 | pass 127 | 128 | dummy = Dummy() 129 | 130 | d = Dispatcher(dummy) 131 | 132 | self.assertIn("one", d) 133 | self.assertIn("two", d) 134 | self.assertNotIn("__class__", d) 135 | 136 | def test_init_from_dictionary(self): 137 | 138 | dummy = { 139 | 'one': lambda x: x, 140 | 'two': lambda x: x, 141 | } 142 | 143 | d = Dispatcher(dummy) 144 | 145 | self.assertIn("one", d) 146 | self.assertIn("two", d) 147 | 148 | def test_dispatcher_representation(self): 149 | 150 | d = Dispatcher() 151 | self.assertEqual('{}', repr(d)) 152 | -------------------------------------------------------------------------------- /docs/source/exceptions.rst: -------------------------------------------------------------------------------- 1 | Exceptions 2 | ========== 3 | 4 | According to specification, error code should be in response message. Http 5 | server should respond with status code 200, even if there is an error. 6 | 7 | JSON-RPC Errors 8 | --------------- 9 | 10 | .. note:: Error is an object which represent any kind of erros in JSON-RPC specification. It is not python Exception and could not be raised. 11 | 12 | Errors (Error messages) are members of :class:`~jsonrpc.exceptions.JSONRPCError` class. Any custom error messages should be inherited from it. 13 | The class is responsible for specification following and creates response string based on error's attributes. 14 | 15 | JSON-RPC has several predefined errors, each of them has reserved code, which should not be used for custom errors. 16 | 17 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 18 | | Code | Message | Meaning | 19 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 20 | | -32700 | Parse error | Invalid JSON was received by the server.An error occurred on the server while parsing the JSON text. | 21 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 22 | | -32600 | Invalid Request | The JSON sent is not a valid Request object. | 23 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 24 | | -32601 | Method not found | The method does not exist / is not available. | 25 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 26 | | -32602 | Invalid params | Invalid method parameter(s). | 27 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 28 | | -32603 | Internal error | Internal JSON-RPC error. | 29 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 30 | | -32000 to -32099 | Server error | Reserved for implementation-defined server-errors. | 31 | +------------------+------------------+------------------------------------------------------------------------------------------------------+ 32 | 33 | :class:`~jsonrpc.manager.JSONRPCResponseManager` handles common errors. If you do not plan to implement own manager, you do not need to write custom errors. To controll error messages and codes, json-rpc has exceptions, covered in next paragraph. 34 | 35 | JSON-RPC Exceptions 36 | ------------------- 37 | 38 | .. note:: Exception here a json-rpc library object and not related to specification. They are inherited from python Exception and could be raised. 39 | 40 | JSON-RPC manager handles dispatcher method's exceptions, anything you raise would be catched. 41 | There are two ways to generate error message in manager: 42 | 43 | First is to simply raise exception in your method. Manager will catch it and return :class:`~jsonrpc.exceptions.JSONRPCServerError` message with description. Advantage of this mehtod is that everything is already implemented, just add method to dispatcher and manager will do the job. 44 | 45 | If you need custom message code or error management, you might need to raise exception, inherited from :class:`~jsonrpc.exceptions.JSONRPCDispatchException`. Make sure, your exception class has error code. 46 | 47 | .. versionadded:: 1.9.0 48 | Fix `Invalid params` error false generated if method raises TypeError. Now in this case manager introspects the code and returns proper exception. 49 | -------------------------------------------------------------------------------- /jsonrpc/utils.py: -------------------------------------------------------------------------------- 1 | """ Utility functions for package.""" 2 | from abc import ABCMeta, abstractmethod 3 | import datetime 4 | import decimal 5 | import inspect 6 | import json 7 | import sys 8 | 9 | from . import six 10 | 11 | 12 | class JSONSerializable(six.with_metaclass(ABCMeta, object)): 13 | 14 | """ Common functionality for json serializable objects.""" 15 | 16 | serialize = staticmethod(json.dumps) 17 | deserialize = staticmethod(json.loads) 18 | 19 | @abstractmethod 20 | def json(self): 21 | raise NotImplementedError() 22 | 23 | @classmethod 24 | def from_json(cls, json_str): 25 | data = cls.deserialize(json_str) 26 | 27 | if not isinstance(data, dict): 28 | raise ValueError("data should be dict") 29 | 30 | return cls(**data) 31 | 32 | 33 | class DatetimeDecimalEncoder(json.JSONEncoder): 34 | 35 | """ Encoder for datetime and decimal serialization. 36 | 37 | Usage: json.dumps(object, cls=DatetimeDecimalEncoder) 38 | NOTE: _iterencode does not work 39 | 40 | """ 41 | 42 | def default(self, o): 43 | """ Encode JSON. 44 | 45 | :return str: A JSON encoded string 46 | 47 | """ 48 | if isinstance(o, decimal.Decimal): 49 | return float(o) 50 | 51 | if isinstance(o, (datetime.datetime, datetime.date)): 52 | return o.isoformat() 53 | 54 | return json.JSONEncoder.default(self, o) 55 | 56 | 57 | def is_invalid_params_py2(func, *args, **kwargs): 58 | """ Check, whether function 'func' accepts parameters 'args', 'kwargs'. 59 | 60 | NOTE: Method is called after funct(*args, **kwargs) generated TypeError, 61 | it is aimed to destinguish TypeError because of invalid parameters from 62 | TypeError from inside the function. 63 | 64 | .. versionadded: 1.9.0 65 | 66 | """ 67 | funcargs, varargs, varkwargs, defaults = inspect.getargspec(func) 68 | 69 | unexpected = set(kwargs.keys()) - set(funcargs) 70 | if len(unexpected) > 0: 71 | return True 72 | 73 | params = [funcarg for funcarg in funcargs if funcarg not in kwargs] 74 | funcargs_required = funcargs[:-len(defaults)] \ 75 | if defaults is not None \ 76 | else funcargs 77 | params_required = [ 78 | funcarg for funcarg in funcargs_required 79 | if funcarg not in kwargs 80 | ] 81 | 82 | return not (len(params_required) <= len(args) <= len(params)) 83 | 84 | 85 | def is_invalid_params_py3(func, *args, **kwargs): 86 | """ 87 | Use inspect.signature instead of inspect.getargspec or 88 | inspect.getfullargspec (based on inspect.signature itself) as it provides 89 | more information about function parameters. 90 | 91 | .. versionadded: 1.11.2 92 | 93 | """ 94 | signature = inspect.signature(func) 95 | parameters = signature.parameters 96 | 97 | unexpected = set(kwargs.keys()) - set(parameters.keys()) 98 | if len(unexpected) > 0: 99 | return True 100 | 101 | params = [ 102 | parameter for name, parameter in parameters.items() 103 | if name not in kwargs 104 | ] 105 | params_required = [ 106 | param for param in params 107 | if param.default is param.empty 108 | ] 109 | 110 | return not (len(params_required) <= len(args) <= len(params)) 111 | 112 | 113 | def is_invalid_params(func, *args, **kwargs): 114 | """ 115 | Method: 116 | Validate pre-defined criteria, if any is True - function is invalid 117 | 0. func should be callable 118 | 1. kwargs should not have unexpected keywords 119 | 2. remove kwargs.keys from func.parameters 120 | 3. number of args should be <= remaining func.parameters 121 | 4. number of args should be >= remaining func.parameters less default 122 | """ 123 | # For builtin functions inspect.getargspec(funct) return error. If builtin 124 | # function generates TypeError, it is because of wrong parameters. 125 | if not inspect.isfunction(func): 126 | return True 127 | 128 | if sys.version_info >= (3, 3): 129 | return is_invalid_params_py3(func, *args, **kwargs) 130 | else: 131 | # NOTE: use Python2 method for Python 3.2 as well. Starting from Python 132 | # 3.3 it is recommended to use inspect.signature instead. 133 | # In Python 3.0 - 3.2 inspect.getfullargspec is preferred but these 134 | # versions are almost not supported. Users should consider upgrading. 135 | return is_invalid_params_py2(func, *args, **kwargs) 136 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_utils.py: -------------------------------------------------------------------------------- 1 | """ Test utility functionality.""" 2 | from ..utils import JSONSerializable, DatetimeDecimalEncoder, is_invalid_params 3 | 4 | import datetime 5 | import decimal 6 | import json 7 | import sys 8 | 9 | if sys.version_info < (3, 3): 10 | from mock import patch 11 | else: 12 | from unittest.mock import patch 13 | 14 | if sys.version_info < (2, 7): 15 | import unittest2 as unittest 16 | else: 17 | import unittest 18 | 19 | 20 | class TestJSONSerializable(unittest.TestCase): 21 | 22 | """ Test JSONSerializable functionality.""" 23 | 24 | def setUp(self): 25 | class A(JSONSerializable): 26 | @property 27 | def json(self): 28 | pass 29 | 30 | self._class = A 31 | 32 | def test_abstract_class(self): 33 | with self.assertRaises(TypeError): 34 | JSONSerializable() 35 | 36 | self._class() 37 | 38 | def test_definse_serialize_deserialize(self): 39 | """ Test classmethods of inherited class.""" 40 | self.assertEqual(self._class.serialize({}), "{}") 41 | self.assertEqual(self._class.deserialize("{}"), {}) 42 | 43 | def test_from_json(self): 44 | self.assertTrue(isinstance(self._class.from_json('{}'), self._class)) 45 | 46 | def test_from_json_incorrect(self): 47 | with self.assertRaises(ValueError): 48 | self._class.from_json('[]') 49 | 50 | 51 | class TestDatetimeDecimalEncoder(unittest.TestCase): 52 | 53 | """ Test DatetimeDecimalEncoder functionality.""" 54 | 55 | def test_date_encoder(self): 56 | obj = datetime.date.today() 57 | 58 | with self.assertRaises(TypeError): 59 | json.dumps(obj) 60 | 61 | self.assertEqual( 62 | json.dumps(obj, cls=DatetimeDecimalEncoder), 63 | '"{0}"'.format(obj.isoformat()), 64 | ) 65 | 66 | def test_datetime_encoder(self): 67 | obj = datetime.datetime.now() 68 | 69 | with self.assertRaises(TypeError): 70 | json.dumps(obj) 71 | 72 | self.assertEqual( 73 | json.dumps(obj, cls=DatetimeDecimalEncoder), 74 | '"{0}"'.format(obj.isoformat()), 75 | ) 76 | 77 | def test_decimal_encoder(self): 78 | obj = decimal.Decimal('0.1') 79 | 80 | with self.assertRaises(TypeError): 81 | json.dumps(obj) 82 | 83 | result = json.dumps(obj, cls=DatetimeDecimalEncoder) 84 | self.assertTrue(isinstance(result, str)) 85 | self.assertEqual(float(result), float(0.1)) 86 | 87 | def test_default(self): 88 | encoder = DatetimeDecimalEncoder() 89 | with patch.object(json.JSONEncoder, 'default') as json_default: 90 | encoder.default("") 91 | 92 | self.assertEqual(json_default.call_count, 1) 93 | 94 | 95 | class TestUtils(unittest.TestCase): 96 | 97 | """ Test utils functions.""" 98 | 99 | def test_is_invalid_params_builtin(self): 100 | self.assertTrue(is_invalid_params(sum, 0, 0)) 101 | # NOTE: builtin functions could not be recognized by inspect.isfunction 102 | # It would raise TypeError if parameters are incorrect already. 103 | # self.assertFalse(is_invalid_params(sum, [0, 0])) # <- fails 104 | 105 | def test_is_invalid_params_args(self): 106 | self.assertTrue(is_invalid_params(lambda a, b: None, 0)) 107 | self.assertTrue(is_invalid_params(lambda a, b: None, 0, 1, 2)) 108 | 109 | def test_is_invalid_params_kwargs(self): 110 | self.assertTrue(is_invalid_params(lambda a: None, **{})) 111 | self.assertTrue(is_invalid_params(lambda a: None, **{"a": 0, "b": 1})) 112 | 113 | def test_invalid_params_correct(self): 114 | self.assertFalse(is_invalid_params(lambda: None)) 115 | self.assertFalse(is_invalid_params(lambda a: None, 0)) 116 | self.assertFalse(is_invalid_params(lambda a, b=0: None, 0)) 117 | self.assertFalse(is_invalid_params(lambda a, b=0: None, 0, 0)) 118 | 119 | def test_is_invalid_params_mixed(self): 120 | self.assertFalse(is_invalid_params(lambda a, b: None, 0, **{"b": 1})) 121 | self.assertFalse(is_invalid_params( 122 | lambda a, b, c=0: None, 0, **{"b": 1})) 123 | 124 | def test_is_invalid_params_py2(self): 125 | with patch('jsonrpc.utils.sys') as mock_sys: 126 | mock_sys.version_info = (2, 7) 127 | with patch('jsonrpc.utils.is_invalid_params_py2') as mock_func: 128 | is_invalid_params(lambda a: None, 0) 129 | 130 | assert mock_func.call_count == 1 131 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_django/test_backend.py: -------------------------------------------------------------------------------- 1 | """ Test Django Backend.""" 2 | from __future__ import absolute_import 3 | import os 4 | 5 | try: 6 | from django.core.urlresolvers import RegexURLPattern 7 | from django.test import TestCase 8 | except ImportError: 9 | import unittest 10 | raise unittest.SkipTest('Django not found for testing') 11 | 12 | from ...backend.django import JSONRPCAPI, api 13 | import json 14 | 15 | 16 | class TestDjangoBackend(TestCase): 17 | @classmethod 18 | def setUpClass(cls): 19 | os.environ['DJANGO_SETTINGS_MODULE'] = \ 20 | 'jsonrpc.tests.test_backend_django.settings' 21 | super(TestDjangoBackend, cls).setUpClass() 22 | 23 | def test_urls(self): 24 | self.assertTrue(isinstance(api.urls, list)) 25 | for api_url in api.urls: 26 | self.assertTrue(isinstance(api_url, RegexURLPattern)) 27 | 28 | def test_client(self): 29 | @api.dispatcher.add_method 30 | def dummy(request): 31 | return "" 32 | 33 | json_data = { 34 | "id": "0", 35 | "jsonrpc": "2.0", 36 | "method": "dummy", 37 | } 38 | response = self.client.post( 39 | '', 40 | json.dumps(json_data), 41 | content_type='application/json', 42 | ) 43 | self.assertEqual(response.status_code, 200) 44 | data = json.loads(response.content.decode('utf8')) 45 | self.assertEqual(data['result'], '') 46 | 47 | def test_positional_args(self): 48 | @api.dispatcher.add_method 49 | def positional_args(request, name): 50 | return name 51 | 52 | json_data = { 53 | "id": "0", 54 | "jsonrpc": "2.0", 55 | "method": "positional_args", 56 | "params": ["echome!"], 57 | } 58 | response = self.client.post( 59 | '', 60 | json.dumps(json_data), 61 | content_type='application/json', 62 | ) 63 | self.assertEqual(response.status_code, 200) 64 | data = json.loads(response.content.decode('utf8')) 65 | self.assertEqual(data['result'], json_data['params'][0]) 66 | 67 | def test_method_not_allowed(self): 68 | response = self.client.get( 69 | '', 70 | content_type='application/json', 71 | ) 72 | self.assertEqual(response.status_code, 405, "Should allow only POST") 73 | 74 | def test_invalid_request(self): 75 | response = self.client.post( 76 | '', 77 | '{', 78 | content_type='application/json', 79 | ) 80 | self.assertEqual(response.status_code, 200) 81 | data = json.loads(response.content.decode('utf8')) 82 | self.assertEqual(data['error']['code'], -32700) 83 | self.assertEqual(data['error']['message'], 'Parse error') 84 | 85 | def test_resource_map(self): 86 | response = self.client.get('/map') 87 | self.assertEqual(response.status_code, 200) 88 | data = response.content.decode('utf8') 89 | self.assertIn("JSON-RPC map", data) 90 | 91 | def test_method_not_allowed_prefix(self): 92 | response = self.client.get( 93 | '/prefix/', 94 | content_type='application/json', 95 | ) 96 | self.assertEqual(response.status_code, 405) 97 | 98 | def test_resource_map_prefix(self): 99 | response = self.client.get('/prefix/map') 100 | self.assertEqual(response.status_code, 200) 101 | 102 | def test_empty_initial_dispatcher(self): 103 | class SubDispatcher(type(api.dispatcher)): 104 | pass 105 | 106 | custom_dispatcher = SubDispatcher() 107 | custom_api = JSONRPCAPI(custom_dispatcher) 108 | self.assertEqual(type(custom_api.dispatcher), SubDispatcher) 109 | self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher)) 110 | 111 | def test_batch_request(self): 112 | @api.dispatcher.add_method 113 | def upper(request, name): 114 | return name.upper() 115 | 116 | json_data = [{ 117 | "id": "0", 118 | "jsonrpc": "2.0", 119 | "method": "upper", 120 | "params": ["hello"], 121 | }, { 122 | "id": "1", 123 | "jsonrpc": "2.0", 124 | "method": "upper", 125 | "params": ["world"], 126 | }] 127 | response = self.client.post( 128 | '', 129 | json.dumps(json_data), 130 | content_type='application/json', 131 | ) 132 | self.assertEqual(response.status_code, 200) 133 | data = json.loads(response.content.decode('utf8')) 134 | self.assertEqual(len(data), len(json_data)) 135 | self.assertEqual(data[0]['result'], json_data[0]['params'][0].upper()) 136 | -------------------------------------------------------------------------------- /jsonrpc/jsonrpc1.py: -------------------------------------------------------------------------------- 1 | from . import six 2 | 3 | from .base import JSONRPCBaseRequest, JSONRPCBaseResponse 4 | from .exceptions import JSONRPCInvalidRequestException, JSONRPCError 5 | 6 | 7 | class JSONRPC10Request(JSONRPCBaseRequest): 8 | 9 | """ JSON-RPC 1.0 Request. 10 | 11 | A remote method is invoked by sending a request to a remote service. 12 | The request is a single object serialized using json. 13 | 14 | :param str method: The name of the method to be invoked. 15 | :param list params: An Array of objects to pass as arguments to the method. 16 | :param _id: This can be of any type. It is used to match the response with 17 | the request that it is replying to. 18 | :param bool is_notification: whether request notification or not. 19 | 20 | """ 21 | 22 | JSONRPC_VERSION = "1.0" 23 | REQUIRED_FIELDS = set(["method", "params", "id"]) 24 | POSSIBLE_FIELDS = set(["method", "params", "id"]) 25 | 26 | @property 27 | def data(self): 28 | data = dict((k, v) for k, v in self._data.items()) 29 | data["id"] = None if self.is_notification else data["id"] 30 | return data 31 | 32 | @data.setter 33 | def data(self, value): 34 | if not isinstance(value, dict): 35 | raise ValueError("data should be dict") 36 | 37 | self._data = value 38 | 39 | @property 40 | def method(self): 41 | return self._data.get("method") 42 | 43 | @method.setter 44 | def method(self, value): 45 | if not isinstance(value, six.string_types): 46 | raise ValueError("Method should be string") 47 | 48 | self._data["method"] = str(value) 49 | 50 | @property 51 | def params(self): 52 | return self._data.get("params") 53 | 54 | @params.setter 55 | def params(self, value): 56 | if not isinstance(value, (list, tuple)): 57 | raise ValueError("Incorrect params {0}".format(value)) 58 | 59 | self._data["params"] = list(value) 60 | 61 | @property 62 | def _id(self): 63 | return self._data.get("id") 64 | 65 | @_id.setter 66 | def _id(self, value): 67 | self._data["id"] = value 68 | 69 | @property 70 | def is_notification(self): 71 | return self._data["id"] is None or self._is_notification 72 | 73 | @is_notification.setter 74 | def is_notification(self, value): 75 | if value is None: 76 | value = self._id is None 77 | 78 | if self._id is None and not value: 79 | raise ValueError("Can not set attribute is_notification. " + 80 | "Request id should not be None") 81 | 82 | self._is_notification = value 83 | 84 | @classmethod 85 | def from_json(cls, json_str): 86 | data = cls.deserialize(json_str) 87 | return cls.from_data(data) 88 | 89 | @classmethod 90 | def from_data(cls, data): 91 | if not isinstance(data, dict): 92 | raise ValueError("data should be dict") 93 | 94 | if cls.REQUIRED_FIELDS <= set(data.keys()) <= cls.POSSIBLE_FIELDS: 95 | return cls( 96 | method=data["method"], params=data["params"], _id=data["id"] 97 | ) 98 | else: 99 | extra = set(data.keys()) - cls.POSSIBLE_FIELDS 100 | missed = cls.REQUIRED_FIELDS - set(data.keys()) 101 | msg = "Invalid request. Extra fields: {0}, Missed fields: {1}" 102 | raise JSONRPCInvalidRequestException(msg.format(extra, missed)) 103 | 104 | 105 | class JSONRPC10Response(JSONRPCBaseResponse): 106 | 107 | JSONRPC_VERSION = "1.0" 108 | 109 | @property 110 | def data(self): 111 | data = dict((k, v) for k, v in self._data.items()) 112 | return data 113 | 114 | @data.setter 115 | def data(self, value): 116 | if not isinstance(value, dict): 117 | raise ValueError("data should be dict") 118 | 119 | self._data = value 120 | 121 | @property 122 | def result(self): 123 | return self._data.get("result") 124 | 125 | @result.setter 126 | def result(self, value): 127 | if self.error: 128 | raise ValueError("Either result or error should be used") 129 | self._data["result"] = value 130 | 131 | @property 132 | def error(self): 133 | return self._data.get("error") 134 | 135 | @error.setter 136 | def error(self, value): 137 | self._data.pop('value', None) 138 | if value: 139 | self._data["error"] = value 140 | # Test error 141 | JSONRPCError(**value) 142 | 143 | @property 144 | def _id(self): 145 | return self._data.get("id") 146 | 147 | @_id.setter 148 | def _id(self, value): 149 | if value is None: 150 | raise ValueError("id could not be null for JSON-RPC1.0 Response") 151 | self._data["id"] = value 152 | -------------------------------------------------------------------------------- /jsonrpc/dispatcher.py: -------------------------------------------------------------------------------- 1 | """ Dispatcher is used to add methods (functions) to the server. 2 | 3 | For usage examples see :meth:`Dispatcher.add_method` 4 | 5 | """ 6 | import functools 7 | try: 8 | from collections.abc import MutableMapping 9 | except ImportError: 10 | from collections import MutableMapping 11 | 12 | 13 | class Dispatcher(MutableMapping): 14 | 15 | """ Dictionary like object which maps method_name to method.""" 16 | 17 | def __init__(self, prototype=None): 18 | """ Build method dispatcher. 19 | 20 | Parameters 21 | ---------- 22 | prototype : object or dict, optional 23 | Initial method mapping. 24 | 25 | Examples 26 | -------- 27 | 28 | Init object with method dictionary. 29 | 30 | >>> Dispatcher({"sum": lambda a, b: a + b}) 31 | None 32 | 33 | """ 34 | self.method_map = dict() 35 | self.context_arg_for_method = dict() 36 | 37 | if prototype is not None: 38 | self.build_method_map(prototype) 39 | 40 | def __getitem__(self, key): 41 | return self.method_map[key] 42 | 43 | def __setitem__(self, key, value): 44 | self.method_map[key] = value 45 | 46 | def __delitem__(self, key): 47 | del self.method_map[key] 48 | self.context_arg_for_method.pop(key, None) 49 | 50 | def __len__(self): 51 | return len(self.method_map) 52 | 53 | def __iter__(self): 54 | return iter(self.method_map) 55 | 56 | def __repr__(self): 57 | return repr(self.method_map) 58 | 59 | def add_class(self, cls): 60 | prefix = cls.__name__.lower() + '.' 61 | self.build_method_map(cls(), prefix) 62 | 63 | def add_object(self, obj): 64 | prefix = obj.__class__.__name__.lower() + '.' 65 | self.build_method_map(obj, prefix) 66 | 67 | def add_dict(self, dict, prefix=''): 68 | if prefix: 69 | prefix += '.' 70 | self.build_method_map(dict, prefix) 71 | 72 | def add_method(self, f=None, name=None, context_arg=None): 73 | """ Add a method to the dispatcher. 74 | 75 | Parameters 76 | ---------- 77 | f : callable 78 | Callable to be added. 79 | name : str, optional 80 | Name to register (the default is function **f** name) 81 | context_arg : str, optional 82 | Name to specify the function's argument which will receive 83 | context data 84 | 85 | Notes 86 | ----- 87 | When used as a decorator keeps callable object unmodified. 88 | 89 | Examples 90 | -------- 91 | 92 | Use as method 93 | 94 | >>> d = Dispatcher() 95 | >>> d.add_method(lambda a, b: a + b, name="sum") 96 | > 97 | 98 | Or use as decorator 99 | 100 | >>> d = Dispatcher() 101 | >>> @d.add_method 102 | def mymethod(*args, **kwargs): 103 | print(args, kwargs) 104 | 105 | Or use as a decorator with a different function name 106 | >>> d = Dispatcher() 107 | >>> @d.add_method(name="my.method") 108 | def mymethod(*args, **kwargs): 109 | print(args, kwargs) 110 | 111 | Or use as a decorator that specifies a context argument name (used by 112 | JSONRPCResponseManager to add optional context to the method call) 113 | >>> d = Dispatcher() 114 | >>> @d.add_method(context_arg="context") 115 | def mymethod(context): 116 | print(context) 117 | 118 | """ 119 | if (name or context_arg) and not f: 120 | return functools.partial(self.add_method, name=name, 121 | context_arg=context_arg) 122 | 123 | name = name or f.__name__ 124 | self.method_map[name] = f 125 | if context_arg: 126 | self.context_arg_for_method[name] = context_arg 127 | return f 128 | 129 | def build_method_map(self, prototype, prefix=''): 130 | """ Add prototype methods to the dispatcher. 131 | 132 | Parameters 133 | ---------- 134 | prototype : object or dict 135 | Initial method mapping. 136 | If given prototype is a dictionary then all callable objects will 137 | be added to dispatcher. 138 | If given prototype is an object then all public methods will 139 | be used. 140 | prefix: string, optional 141 | Prefix of methods 142 | 143 | """ 144 | if not isinstance(prototype, dict): 145 | prototype = dict((method, getattr(prototype, method)) 146 | for method in dir(prototype) 147 | if not method.startswith('_')) 148 | 149 | for attr, method in prototype.items(): 150 | if callable(method): 151 | self[prefix + attr] = method 152 | -------------------------------------------------------------------------------- /jsonrpc/exceptions.py: -------------------------------------------------------------------------------- 1 | """ JSON-RPC Exceptions.""" 2 | from . import six 3 | import json 4 | 5 | 6 | class JSONRPCError(object): 7 | 8 | """ Error for JSON-RPC communication. 9 | 10 | When a rpc call encounters an error, the Response Object MUST contain the 11 | error member with a value that is a Object with the following members: 12 | 13 | Parameters 14 | ---------- 15 | code: int 16 | A Number that indicates the error type that occurred. 17 | This MUST be an integer. 18 | The error codes from and including -32768 to -32000 are reserved for 19 | pre-defined errors. Any code within this range, but not defined 20 | explicitly below is reserved for future use. The error codes are nearly 21 | the same as those suggested for XML-RPC at the following 22 | url: http://xmlrpc-epi.sourceforge.net/specs/rfc.fault_codes.php 23 | 24 | message: str 25 | A String providing a short description of the error. 26 | The message SHOULD be limited to a concise single sentence. 27 | 28 | data: int or str or dict or list, optional 29 | A Primitive or Structured value that contains additional 30 | information about the error. 31 | This may be omitted. 32 | The value of this member is defined by the Server (e.g. detailed error 33 | information, nested errors etc.). 34 | 35 | """ 36 | 37 | serialize = staticmethod(json.dumps) 38 | deserialize = staticmethod(json.loads) 39 | 40 | def __init__(self, code=None, message=None, data=None): 41 | self._data = dict() 42 | self.code = getattr(self.__class__, "CODE", code) 43 | self.message = getattr(self.__class__, "MESSAGE", message) 44 | self.data = data 45 | 46 | def __get_code(self): 47 | return self._data["code"] 48 | 49 | def __set_code(self, value): 50 | if not isinstance(value, six.integer_types): 51 | raise ValueError("Error code should be integer") 52 | 53 | self._data["code"] = value 54 | 55 | code = property(__get_code, __set_code) 56 | 57 | def __get_message(self): 58 | return self._data["message"] 59 | 60 | def __set_message(self, value): 61 | if not isinstance(value, six.string_types): 62 | raise ValueError("Error message should be string") 63 | 64 | self._data["message"] = value 65 | 66 | message = property(__get_message, __set_message) 67 | 68 | def __get_data(self): 69 | return self._data.get("data") 70 | 71 | def __set_data(self, value): 72 | if value is not None: 73 | self._data["data"] = value 74 | 75 | data = property(__get_data, __set_data) 76 | 77 | @classmethod 78 | def from_json(cls, json_str): 79 | data = cls.deserialize(json_str) 80 | return cls( 81 | code=data["code"], message=data["message"], data=data.get("data")) 82 | 83 | @property 84 | def json(self): 85 | return self.serialize(self._data) 86 | 87 | 88 | class JSONRPCParseError(JSONRPCError): 89 | 90 | """ Parse Error. 91 | 92 | Invalid JSON was received by the server. 93 | An error occurred on the server while parsing the JSON text. 94 | 95 | """ 96 | 97 | CODE = -32700 98 | MESSAGE = "Parse error" 99 | 100 | 101 | class JSONRPCInvalidRequest(JSONRPCError): 102 | 103 | """ Invalid Request. 104 | 105 | The JSON sent is not a valid Request object. 106 | 107 | """ 108 | 109 | CODE = -32600 110 | MESSAGE = "Invalid Request" 111 | 112 | 113 | class JSONRPCMethodNotFound(JSONRPCError): 114 | 115 | """ Method not found. 116 | 117 | The method does not exist / is not available. 118 | 119 | """ 120 | 121 | CODE = -32601 122 | MESSAGE = "Method not found" 123 | 124 | 125 | class JSONRPCInvalidParams(JSONRPCError): 126 | 127 | """ Invalid params. 128 | 129 | Invalid method parameter(s). 130 | 131 | """ 132 | 133 | CODE = -32602 134 | MESSAGE = "Invalid params" 135 | 136 | 137 | class JSONRPCInternalError(JSONRPCError): 138 | 139 | """ Internal error. 140 | 141 | Internal JSON-RPC error. 142 | 143 | """ 144 | 145 | CODE = -32603 146 | MESSAGE = "Internal error" 147 | 148 | 149 | class JSONRPCServerError(JSONRPCError): 150 | 151 | """ Server error. 152 | 153 | Reserved for implementation-defined server-errors. 154 | 155 | """ 156 | 157 | CODE = -32000 158 | MESSAGE = "Server error" 159 | 160 | 161 | class JSONRPCException(Exception): 162 | 163 | """ JSON-RPC Exception.""" 164 | 165 | pass 166 | 167 | 168 | class JSONRPCInvalidRequestException(JSONRPCException): 169 | 170 | """ Request is not valid.""" 171 | 172 | pass 173 | 174 | 175 | class JSONRPCDispatchException(JSONRPCException): 176 | 177 | """ JSON-RPC Dispatch Exception. 178 | 179 | Should be thrown in dispatch methods. 180 | 181 | """ 182 | 183 | def __init__(self, code=None, message=None, data=None, *args, **kwargs): 184 | super(JSONRPCDispatchException, self).__init__(args, kwargs) 185 | self.error = JSONRPCError(code=code, data=data, message=message) 186 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_jsonrpc_errors.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | from ..exceptions import ( 5 | JSONRPCError, 6 | JSONRPCInternalError, 7 | JSONRPCInvalidParams, 8 | JSONRPCInvalidRequest, 9 | JSONRPCMethodNotFound, 10 | JSONRPCParseError, 11 | JSONRPCServerError, 12 | JSONRPCDispatchException, 13 | ) 14 | 15 | if sys.version_info < (2, 7): 16 | import unittest2 as unittest 17 | else: 18 | import unittest 19 | 20 | 21 | class TestJSONRPCError(unittest.TestCase): 22 | def setUp(self): 23 | self.error_params = { 24 | "code": 0, 25 | "message": "", 26 | } 27 | 28 | def test_correct_init(self): 29 | """ Test object is created.""" 30 | JSONRPCError(**self.error_params) 31 | 32 | def test_validation_incorrect_no_parameters(self): 33 | with self.assertRaises(ValueError): 34 | JSONRPCError() 35 | 36 | def test_code_validation_int(self): 37 | self.error_params.update({"code": 32000}) 38 | JSONRPCError(**self.error_params) 39 | 40 | def test_code_validation_no_code(self): 41 | del self.error_params["code"] 42 | with self.assertRaises(ValueError): 43 | JSONRPCError(**self.error_params) 44 | 45 | def test_code_validation_str(self): 46 | self.error_params.update({"code": "0"}) 47 | with self.assertRaises(ValueError): 48 | JSONRPCError(**self.error_params) 49 | 50 | def test_message_validation_str(self): 51 | self.error_params.update({"message": ""}) 52 | JSONRPCError(**self.error_params) 53 | 54 | def test_message_validation_none(self): 55 | del self.error_params["message"] 56 | with self.assertRaises(ValueError): 57 | JSONRPCError(**self.error_params) 58 | 59 | def test_message_validation_int(self): 60 | self.error_params.update({"message": 0}) 61 | with self.assertRaises(ValueError): 62 | JSONRPCError(**self.error_params) 63 | 64 | def test_data_validation_none(self): 65 | self.error_params.update({"data": None}) 66 | JSONRPCError(**self.error_params) 67 | 68 | def test_data_validation(self): 69 | self.error_params.update({"data": {}}) 70 | JSONRPCError(**self.error_params) 71 | 72 | self.error_params.update({"data": ""}) 73 | JSONRPCError(**self.error_params) 74 | 75 | def test_json(self): 76 | error = JSONRPCError(**self.error_params) 77 | self.assertEqual( 78 | json.loads(error.json), 79 | self.error_params, 80 | ) 81 | 82 | def test_from_json(self): 83 | str_json = json.dumps({ 84 | "code": 0, 85 | "message": "", 86 | "data": {}, 87 | }) 88 | 89 | request = JSONRPCError.from_json(str_json) 90 | self.assertTrue(isinstance(request, JSONRPCError)) 91 | self.assertEqual(request.code, 0) 92 | self.assertEqual(request.message, "") 93 | self.assertEqual(request.data, {}) 94 | 95 | 96 | class TestJSONRPCParseError(unittest.TestCase): 97 | def test_code_message(self): 98 | error = JSONRPCParseError() 99 | self.assertEqual(error.code, -32700) 100 | self.assertEqual(error.message, "Parse error") 101 | self.assertEqual(error.data, None) 102 | 103 | 104 | class TestJSONRPCServerError(unittest.TestCase): 105 | def test_code_message(self): 106 | error = JSONRPCServerError() 107 | self.assertEqual(error.code, -32000) 108 | self.assertEqual(error.message, "Server error") 109 | self.assertEqual(error.data, None) 110 | 111 | 112 | class TestJSONRPCInternalError(unittest.TestCase): 113 | def test_code_message(self): 114 | error = JSONRPCInternalError() 115 | self.assertEqual(error.code, -32603) 116 | self.assertEqual(error.message, "Internal error") 117 | self.assertEqual(error.data, None) 118 | 119 | 120 | class TestJSONRPCInvalidParams(unittest.TestCase): 121 | def test_code_message(self): 122 | error = JSONRPCInvalidParams() 123 | self.assertEqual(error.code, -32602) 124 | self.assertEqual(error.message, "Invalid params") 125 | self.assertEqual(error.data, None) 126 | 127 | 128 | class TestJSONRPCInvalidRequest(unittest.TestCase): 129 | def test_code_message(self): 130 | error = JSONRPCInvalidRequest() 131 | self.assertEqual(error.code, -32600) 132 | self.assertEqual(error.message, "Invalid Request") 133 | self.assertEqual(error.data, None) 134 | 135 | 136 | class TestJSONRPCMethodNotFound(unittest.TestCase): 137 | def test_code_message(self): 138 | error = JSONRPCMethodNotFound() 139 | self.assertEqual(error.code, -32601) 140 | self.assertEqual(error.message, "Method not found") 141 | self.assertEqual(error.data, None) 142 | 143 | 144 | class TestJSONRPCDispatchException(unittest.TestCase): 145 | def test_code_message(self): 146 | error = JSONRPCDispatchException(message="message", 147 | code=400, data={"param": 1}) 148 | self.assertEqual(error.error.code, 400) 149 | self.assertEqual(error.error.message, "message") 150 | self.assertEqual(error.error.data, {"param": 1}) 151 | -------------------------------------------------------------------------------- /jsonrpc/manager.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from .utils import is_invalid_params 4 | from .exceptions import ( 5 | JSONRPCInvalidParams, 6 | JSONRPCInvalidRequest, 7 | JSONRPCInvalidRequestException, 8 | JSONRPCMethodNotFound, 9 | JSONRPCParseError, 10 | JSONRPCServerError, 11 | JSONRPCDispatchException, 12 | ) 13 | from .jsonrpc1 import JSONRPC10Response 14 | from .jsonrpc2 import ( 15 | JSONRPC20BatchRequest, 16 | JSONRPC20BatchResponse, 17 | JSONRPC20Response, 18 | ) 19 | from .jsonrpc import JSONRPCRequest 20 | 21 | logger = logging.getLogger(__name__) 22 | 23 | 24 | class JSONRPCResponseManager(object): 25 | 26 | """ JSON-RPC response manager. 27 | 28 | Method brings syntactic sugar into library. Given dispatcher it handles 29 | request (both single and batch) and handles errors. 30 | Request could be handled in parallel, it is server responsibility. 31 | 32 | :param str request_str: json string. Will be converted into 33 | JSONRPC20Request, JSONRPC20BatchRequest or JSONRPC10Request 34 | 35 | :param dict dispatcher: dict. 36 | 37 | """ 38 | 39 | RESPONSE_CLASS_MAP = { 40 | "1.0": JSONRPC10Response, 41 | "2.0": JSONRPC20Response, 42 | } 43 | 44 | @classmethod 45 | def handle(cls, request_str, dispatcher, context=None): 46 | if isinstance(request_str, bytes): 47 | request_str = request_str.decode("utf-8") 48 | 49 | try: 50 | data = json.loads(request_str) 51 | except (TypeError, ValueError): 52 | return JSONRPC20Response(error=JSONRPCParseError()._data) 53 | 54 | try: 55 | request = JSONRPCRequest.from_data(data) 56 | except JSONRPCInvalidRequestException: 57 | return JSONRPC20Response(error=JSONRPCInvalidRequest()._data) 58 | 59 | return cls.handle_request(request, dispatcher, context) 60 | 61 | @classmethod 62 | def handle_request(cls, request, dispatcher, context=None): 63 | """ Handle request data. 64 | 65 | At this moment request has correct jsonrpc format. 66 | 67 | :param dict request: data parsed from request_str. 68 | :param jsonrpc.dispatcher.Dispatcher dispatcher: 69 | 70 | .. versionadded: 1.8.0 71 | 72 | """ 73 | rs = request if isinstance(request, JSONRPC20BatchRequest) \ 74 | else [request] 75 | responses = [r for r in cls._get_responses(rs, dispatcher, context) 76 | if r is not None] 77 | 78 | # notifications 79 | if not responses: 80 | return 81 | 82 | if isinstance(request, JSONRPC20BatchRequest): 83 | response = JSONRPC20BatchResponse(*responses) 84 | response.request = request 85 | return response 86 | else: 87 | return responses[0] 88 | 89 | @classmethod 90 | def _get_responses(cls, requests, dispatcher, context=None): 91 | """ Response to each single JSON-RPC Request. 92 | 93 | :return iterator(JSONRPC20Response): 94 | 95 | .. versionadded: 1.9.0 96 | TypeError inside the function is distinguished from Invalid Params. 97 | 98 | """ 99 | for request in requests: 100 | def make_response(**kwargs): 101 | response = cls.RESPONSE_CLASS_MAP[request.JSONRPC_VERSION]( 102 | _id=request._id, **kwargs) 103 | response.request = request 104 | return response 105 | 106 | output = None 107 | try: 108 | method = dispatcher[request.method] 109 | except KeyError: 110 | output = make_response(error=JSONRPCMethodNotFound()._data) 111 | else: 112 | try: 113 | kwargs = request.kwargs 114 | if context is not None: 115 | context_arg = dispatcher.context_arg_for_method.get( 116 | request.method) 117 | if context_arg: 118 | context["request"] = request 119 | kwargs[context_arg] = context 120 | result = method(*request.args, **kwargs) 121 | except JSONRPCDispatchException as e: 122 | output = make_response(error=e.error._data) 123 | except Exception as e: 124 | data = { 125 | "type": e.__class__.__name__, 126 | "args": e.args, 127 | "message": str(e), 128 | } 129 | 130 | logger.exception("API Exception: {0}".format(data)) 131 | 132 | if isinstance(e, TypeError) and is_invalid_params( 133 | method, *request.args, **request.kwargs): 134 | output = make_response( 135 | error=JSONRPCInvalidParams(data=data)._data) 136 | else: 137 | output = make_response( 138 | error=JSONRPCServerError(data=data)._data) 139 | else: 140 | output = make_response(result=result) 141 | finally: 142 | if not request.is_notification: 143 | yield output 144 | -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | set I18NSPHINXOPTS=%SPHINXOPTS% . 11 | if NOT "%PAPER%" == "" ( 12 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 13 | set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% 14 | ) 15 | 16 | if "%1" == "" goto help 17 | 18 | if "%1" == "help" ( 19 | :help 20 | echo.Please use `make ^` where ^ is one of 21 | echo. html to make standalone HTML files 22 | echo. dirhtml to make HTML files named index.html in directories 23 | echo. singlehtml to make a single large HTML file 24 | echo. pickle to make pickle files 25 | echo. json to make JSON files 26 | echo. htmlhelp to make HTML files and a HTML help project 27 | echo. qthelp to make HTML files and a qthelp project 28 | echo. devhelp to make HTML files and a Devhelp project 29 | echo. epub to make an epub 30 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 31 | echo. text to make text files 32 | echo. man to make manual pages 33 | echo. texinfo to make Texinfo files 34 | echo. gettext to make PO message catalogs 35 | echo. changes to make an overview over all changed/added/deprecated items 36 | echo. linkcheck to check all external links for integrity 37 | echo. doctest to run all doctests embedded in the documentation if enabled 38 | goto end 39 | ) 40 | 41 | if "%1" == "clean" ( 42 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 43 | del /q /s %BUILDDIR%\* 44 | goto end 45 | ) 46 | 47 | if "%1" == "html" ( 48 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 49 | if errorlevel 1 exit /b 1 50 | echo. 51 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 52 | goto end 53 | ) 54 | 55 | if "%1" == "dirhtml" ( 56 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 57 | if errorlevel 1 exit /b 1 58 | echo. 59 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 60 | goto end 61 | ) 62 | 63 | if "%1" == "singlehtml" ( 64 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 65 | if errorlevel 1 exit /b 1 66 | echo. 67 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 68 | goto end 69 | ) 70 | 71 | if "%1" == "pickle" ( 72 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 73 | if errorlevel 1 exit /b 1 74 | echo. 75 | echo.Build finished; now you can process the pickle files. 76 | goto end 77 | ) 78 | 79 | if "%1" == "json" ( 80 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 81 | if errorlevel 1 exit /b 1 82 | echo. 83 | echo.Build finished; now you can process the JSON files. 84 | goto end 85 | ) 86 | 87 | if "%1" == "htmlhelp" ( 88 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 89 | if errorlevel 1 exit /b 1 90 | echo. 91 | echo.Build finished; now you can run HTML Help Workshop with the ^ 92 | .hhp project file in %BUILDDIR%/htmlhelp. 93 | goto end 94 | ) 95 | 96 | if "%1" == "qthelp" ( 97 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 98 | if errorlevel 1 exit /b 1 99 | echo. 100 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 101 | .qhcp project file in %BUILDDIR%/qthelp, like this: 102 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\json-rpc.qhcp 103 | echo.To view the help file: 104 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\json-rpc.ghc 105 | goto end 106 | ) 107 | 108 | if "%1" == "devhelp" ( 109 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 110 | if errorlevel 1 exit /b 1 111 | echo. 112 | echo.Build finished. 113 | goto end 114 | ) 115 | 116 | if "%1" == "epub" ( 117 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 118 | if errorlevel 1 exit /b 1 119 | echo. 120 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 121 | goto end 122 | ) 123 | 124 | if "%1" == "latex" ( 125 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 126 | if errorlevel 1 exit /b 1 127 | echo. 128 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 129 | goto end 130 | ) 131 | 132 | if "%1" == "text" ( 133 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 134 | if errorlevel 1 exit /b 1 135 | echo. 136 | echo.Build finished. The text files are in %BUILDDIR%/text. 137 | goto end 138 | ) 139 | 140 | if "%1" == "man" ( 141 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 142 | if errorlevel 1 exit /b 1 143 | echo. 144 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 145 | goto end 146 | ) 147 | 148 | if "%1" == "texinfo" ( 149 | %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo 150 | if errorlevel 1 exit /b 1 151 | echo. 152 | echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. 153 | goto end 154 | ) 155 | 156 | if "%1" == "gettext" ( 157 | %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale 158 | if errorlevel 1 exit /b 1 159 | echo. 160 | echo.Build finished. The message catalogs are in %BUILDDIR%/locale. 161 | goto end 162 | ) 163 | 164 | if "%1" == "changes" ( 165 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 166 | if errorlevel 1 exit /b 1 167 | echo. 168 | echo.The overview file is in %BUILDDIR%/changes. 169 | goto end 170 | ) 171 | 172 | if "%1" == "linkcheck" ( 173 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 174 | if errorlevel 1 exit /b 1 175 | echo. 176 | echo.Link check complete; look for any errors in the above output ^ 177 | or in %BUILDDIR%/linkcheck/output.txt. 178 | goto end 179 | ) 180 | 181 | if "%1" == "doctest" ( 182 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 183 | if errorlevel 1 exit /b 1 184 | echo. 185 | echo.Testing of doctests in the sources finished, look at the ^ 186 | results in %BUILDDIR%/doctest/output.txt. 187 | goto end 188 | ) 189 | 190 | :end 191 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source 14 | # the i18n builder cannot share the environment and doctrees with the others 15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 16 | 17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 18 | 19 | help: 20 | @echo "Please use \`make ' where is one of" 21 | @echo " html to make standalone HTML files" 22 | @echo " dirhtml to make HTML files named index.html in directories" 23 | @echo " singlehtml to make a single large HTML file" 24 | @echo " pickle to make pickle files" 25 | @echo " json to make JSON files" 26 | @echo " htmlhelp to make HTML files and a HTML help project" 27 | @echo " qthelp to make HTML files and a qthelp project" 28 | @echo " devhelp to make HTML files and a Devhelp project" 29 | @echo " epub to make an epub" 30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 31 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 32 | @echo " text to make text files" 33 | @echo " man to make manual pages" 34 | @echo " texinfo to make Texinfo files" 35 | @echo " info to make Texinfo files and run them through makeinfo" 36 | @echo " gettext to make PO message catalogs" 37 | @echo " changes to make an overview of all changed/added/deprecated items" 38 | @echo " linkcheck to check all external links for integrity" 39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 40 | 41 | clean: 42 | -rm -rf $(BUILDDIR)/* 43 | 44 | html: 45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 48 | 49 | dirhtml: 50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 51 | @echo 52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 53 | 54 | singlehtml: 55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 56 | @echo 57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 58 | 59 | pickle: 60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 61 | @echo 62 | @echo "Build finished; now you can process the pickle files." 63 | 64 | json: 65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 66 | @echo 67 | @echo "Build finished; now you can process the JSON files." 68 | 69 | htmlhelp: 70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 71 | @echo 72 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 73 | ".hhp project file in $(BUILDDIR)/htmlhelp." 74 | 75 | qthelp: 76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 77 | @echo 78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/json-rpc.qhcp" 81 | @echo "To view the help file:" 82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/json-rpc.qhc" 83 | 84 | devhelp: 85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 86 | @echo 87 | @echo "Build finished." 88 | @echo "To view the help file:" 89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/json-rpc" 90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/json-rpc" 91 | @echo "# devhelp" 92 | 93 | epub: 94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 95 | @echo 96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 97 | 98 | latex: 99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 100 | @echo 101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 103 | "(use \`make latexpdf' here to do that automatically)." 104 | 105 | latexpdf: 106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 107 | @echo "Running LaTeX files through pdflatex..." 108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 110 | 111 | text: 112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 113 | @echo 114 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 115 | 116 | man: 117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 118 | @echo 119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 120 | 121 | texinfo: 122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 123 | @echo 124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 125 | @echo "Run \`make' in that directory to run these through makeinfo" \ 126 | "(use \`make info' here to do that automatically)." 127 | 128 | info: 129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 130 | @echo "Running Texinfo files through makeinfo..." 131 | make -C $(BUILDDIR)/texinfo info 132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 133 | 134 | gettext: 135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 136 | @echo 137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 138 | 139 | changes: 140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 141 | @echo 142 | @echo "The overview file is in $(BUILDDIR)/changes." 143 | 144 | linkcheck: 145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 146 | @echo 147 | @echo "Link check complete; look for any errors in the above output " \ 148 | "or in $(BUILDDIR)/linkcheck/output.txt." 149 | 150 | doctest: 151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 152 | @echo "Testing of doctests in the sources finished, look at the " \ 153 | "results in $(BUILDDIR)/doctest/output.txt." 154 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_backend_flask/test_backend.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | if sys.version_info < (3, 3): 5 | from mock import patch 6 | else: 7 | from unittest.mock import patch 8 | 9 | if sys.version_info < (2, 7): 10 | import unittest2 as unittest 11 | else: 12 | import unittest 13 | 14 | # Flask is supported only for python2 and python3.3+ 15 | if sys.version_info < (3, 0) or sys.version_info >= (3, 3): 16 | try: 17 | from flask import Flask 18 | except ImportError: 19 | raise unittest.SkipTest('Flask not found for testing') 20 | 21 | from ...backend.flask import JSONRPCAPI, api 22 | 23 | @api.dispatcher.add_method 24 | def dummy(): 25 | return "" 26 | 27 | 28 | @unittest.skipIf((3, 0) <= sys.version_info < (3, 3), 29 | 'Flask does not support python 3.0 - 3.2') 30 | class TestFlaskBackend(unittest.TestCase): 31 | REQUEST = json.dumps({ 32 | "id": "0", 33 | "jsonrpc": "2.0", 34 | "method": "dummy", 35 | }) 36 | 37 | def setUp(self): 38 | self.client = self._get_test_client(JSONRPCAPI()) 39 | 40 | def _get_test_client(self, api): 41 | @api.dispatcher.add_method 42 | def dummy(): 43 | return "" 44 | 45 | app = Flask(__name__) 46 | app.config["TESTING"] = True 47 | app.register_blueprint(api.as_blueprint()) 48 | return app.test_client() 49 | 50 | def test_client(self): 51 | response = self.client.post( 52 | '/', 53 | data=self.REQUEST, 54 | content_type='application/json', 55 | ) 56 | self.assertEqual(response.status_code, 200) 57 | data = json.loads(response.data.decode('utf8')) 58 | self.assertEqual(data['result'], '') 59 | 60 | def test_method_not_allowed(self): 61 | response = self.client.get( 62 | '/', 63 | content_type='application/json', 64 | ) 65 | self.assertEqual(response.status_code, 405, "Should allow only POST") 66 | 67 | def test_parse_error(self): 68 | response = self.client.post( 69 | '/', 70 | data='{', 71 | content_type='application/json', 72 | ) 73 | self.assertEqual(response.status_code, 200) 74 | data = json.loads(response.data.decode('utf8')) 75 | self.assertEqual(data['error']['code'], -32700) 76 | self.assertEqual(data['error']['message'], 'Parse error') 77 | 78 | def test_wrong_content_type(self): 79 | response = self.client.post( 80 | '/', 81 | data=self.REQUEST, 82 | content_type='application/x-www-form-urlencoded', 83 | ) 84 | self.assertEqual(response.status_code, 200) 85 | data = json.loads(response.data.decode('utf8')) 86 | self.assertEqual(data['error']['code'], -32700) 87 | self.assertEqual(data['error']['message'], 'Parse error') 88 | 89 | def test_invalid_request(self): 90 | response = self.client.post( 91 | '/', 92 | data='{"method": "dummy", "id": 1}', 93 | content_type='application/json', 94 | ) 95 | self.assertEqual(response.status_code, 200) 96 | data = json.loads(response.data.decode('utf8')) 97 | self.assertEqual(data['error']['code'], -32600) 98 | self.assertEqual(data['error']['message'], 'Invalid Request') 99 | 100 | def test_method_not_found(self): 101 | data = { 102 | "jsonrpc": "2.0", 103 | "method": "dummy2", 104 | "id": 1 105 | } 106 | response = self.client.post( 107 | '/', 108 | data=json.dumps(data), 109 | content_type='application/json', 110 | ) 111 | self.assertEqual(response.status_code, 200) 112 | data = json.loads(response.data.decode('utf8')) 113 | self.assertEqual(data['error']['code'], -32601) 114 | self.assertEqual(data['error']['message'], 'Method not found') 115 | 116 | def test_invalid_parameters(self): 117 | data = { 118 | "jsonrpc": "2.0", 119 | "method": "dummy", 120 | "params": [42], 121 | "id": 1 122 | } 123 | response = self.client.post( 124 | '/', 125 | data=json.dumps(data), 126 | content_type='application/json', 127 | ) 128 | self.assertEqual(response.status_code, 200) 129 | data = json.loads(response.data.decode('utf8')) 130 | self.assertEqual(data['error']['code'], -32602) 131 | self.assertEqual(data['error']['message'], 'Invalid params') 132 | 133 | def test_resource_map(self): 134 | response = self.client.get('/map') 135 | self.assertEqual(response.status_code, 200) 136 | self.assertTrue("JSON-RPC map" in response.data.decode('utf8')) 137 | 138 | def test_method_not_allowed_prefix(self): 139 | response = self.client.get( 140 | '/', 141 | content_type='application/json', 142 | ) 143 | self.assertEqual(response.status_code, 405) 144 | 145 | def test_resource_map_prefix(self): 146 | response = self.client.get('/map') 147 | self.assertEqual(response.status_code, 200) 148 | 149 | def test_as_view(self): 150 | api = JSONRPCAPI() 151 | with patch.object(api, 'jsonrpc') as mock_jsonrpc: 152 | self.assertIs(api.as_view(), mock_jsonrpc) 153 | 154 | def test_not_check_content_type(self): 155 | client = self._get_test_client(JSONRPCAPI(check_content_type=False)) 156 | response = client.post( 157 | '/', 158 | data=self.REQUEST, 159 | ) 160 | self.assertEqual(response.status_code, 200) 161 | data = json.loads(response.data.decode('utf8')) 162 | self.assertEqual(data['result'], '') 163 | 164 | def test_check_content_type(self): 165 | client = self._get_test_client(JSONRPCAPI(check_content_type=False)) 166 | response = client.post( 167 | '/', 168 | data=self.REQUEST, 169 | content_type="application/x-www-form-urlencoded" 170 | ) 171 | self.assertEqual(response.status_code, 200) 172 | data = json.loads(response.data.decode('utf8')) 173 | self.assertEqual(data['result'], '') 174 | 175 | def test_empty_initial_dispatcher(self): 176 | class SubDispatcher(type(api.dispatcher)): 177 | pass 178 | 179 | custom_dispatcher = SubDispatcher() 180 | custom_api = JSONRPCAPI(custom_dispatcher) 181 | self.assertEqual(type(custom_api.dispatcher), SubDispatcher) 182 | self.assertEqual(id(custom_api.dispatcher), id(custom_dispatcher)) 183 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | json-rpc 2 | ======== 3 | 4 | .. image:: https://circleci.com/gh/pavlov99/json-rpc/tree/master.svg?style=svg 5 | :target: https://circleci.com/gh/pavlov99/json-rpc/tree/master 6 | :alt: Build Status 7 | 8 | .. image:: https://codecov.io/gh/pavlov99/json-rpc/branch/master/graph/badge.svg 9 | :target: https://codecov.io/gh/pavlov99/json-rpc 10 | :alt: Coverage Status 11 | 12 | .. image:: https://readthedocs.org/projects/json-rpc/badge/?version=latest 13 | :target: http://json-rpc.readthedocs.io/en/latest/?badge=latest 14 | 15 | .. image:: https://img.shields.io/pypi/v/json-rpc.svg 16 | :target: https://pypi.org/project/json-rpc/ 17 | :alt: Latest PyPI version 18 | 19 | .. image:: https://img.shields.io/pypi/pyversions/json-rpc.svg 20 | :target: https://pypi.org/project/json-rpc/ 21 | :alt: Supported Python versions 22 | 23 | .. image:: https://badges.gitter.im/pavlov99/json-rpc.svg 24 | :target: https://gitter.im/pavlov99/json-rpc 25 | :alt: Gitter 26 | 27 | 28 | .. image:: https://opencollective.com/json-rpc/tiers/backer/badge.svg?label=backer&color=brightgreen 29 | :target: https://opencollective.com/json-rpc 30 | :alt: Bakers 31 | 32 | .. image:: https://opencollective.com/json-rpc/tiers/backer/badge.svg?label=sponsor&color=brightgreen 33 | :target: https://opencollective.com/json-rpc 34 | :alt: Sponsors 35 | 36 | `JSON-RPC2.0 `_ and `JSON-RPC1.0 `_ transport specification implementation. 37 | Supports Python 2.6+, Python 3.3+, PyPy. Has optional Django and Flask support. 200+ tests. 38 | 39 | Features 40 | -------- 41 | 42 | This implementation does not have any transport functionality realization, only protocol. 43 | Any client or server implementation is easy based on current code, but requires transport libraries, such as requests, gevent or zmq, see `examples `_. 44 | 45 | - Vanilla Python, no dependencies. 46 | - 200+ tests for multiple edge cases. 47 | - Optional backend support for Django, Flask. 48 | - json-rpc 1.1 and 2.0 support. 49 | 50 | Install 51 | ------- 52 | 53 | .. code-block:: python 54 | 55 | pip install json-rpc 56 | 57 | Tests 58 | ----- 59 | 60 | Quickstart 61 | ^^^^^^^^^^ 62 | This is an essential part of the library as there are a lot of edge cases in JSON-RPC standard. To manage a variety of supported python versions as well as optional backends json-rpc uses `tox`: 63 | 64 | .. code-block:: bash 65 | 66 | tox 67 | 68 | .. TIP:: 69 | During local development use your python version with tox runner. For example, if your are using Python 3.6 run `tox -e py36`. It is easier to develop functionality for specific version first and then expands it to all of the supported versions. 70 | 71 | Continuous integration 72 | ^^^^^^^^^^^^^^^^^^^^^^ 73 | This project uses `CircleCI `_ for continuous integration. All of the python supported versions are managed via `tox.ini` and `.circleci/config.yml` files. Master branch test status is displayed on the badge in the beginning of this document. 74 | 75 | Test matrix 76 | ^^^^^^^^^^^ 77 | json-rpc supports multiple python versions: 2.6+, 3.3+, pypy. This introduces difficulties with testing libraries and optional dependencies management. For example, python before version 3.3 does not support `mock` and there is a limited support for `unittest2`. Every dependency translates into *if-then* blocks in the source code and adds complexity to it. Hence, while cross-python support is a core feature of this library, cross-Django or cross-Flask support is limited. In general, json-rpc uses latest stable release which supports current python version. For example, python 2.6 is compatible with Django 1.6 and not compatible with any future versions. 78 | 79 | Below is a testing matrix: 80 | 81 | +--------+-------+-----------+--------+--------+ 82 | | Python | mock | unittest | Django | Flask | 83 | +========+=======+===========+========+========+ 84 | | 2.6 | 2.0.0 | unittest2 | 1.6 | 0.12.2 | 85 | +--------+-------+-----------+--------+--------+ 86 | | 2.7 | 2.0.0 | | 1.11 | 0.12.2 | 87 | +--------+-------+-----------+--------+--------+ 88 | | 3.3 | | | 1.11 | 0.12.2 | 89 | +--------+-------+-----------+--------+--------+ 90 | | 3.4 | | | 1.11 | 0.12.2 | 91 | +--------+-------+-----------+--------+--------+ 92 | | 3.5 | | | 1.11 | 0.12.2 | 93 | +--------+-------+-----------+--------+--------+ 94 | | 3.6 | | | 1.11 | 0.12.2 | 95 | +--------+-------+-----------+--------+--------+ 96 | | pypy | 2.0.0 | | 1.11 | 0.12.2 | 97 | +--------+-------+-----------+--------+--------+ 98 | | pypy3 | | | 1.11 | 0.12.2 | 99 | +--------+-------+-----------+--------+--------+ 100 | 101 | Quickstart 102 | ---------- 103 | Server (uses `Werkzeug `_) 104 | 105 | .. code-block:: python 106 | 107 | from werkzeug.wrappers import Request, Response 108 | from werkzeug.serving import run_simple 109 | 110 | from jsonrpc import JSONRPCResponseManager, dispatcher 111 | 112 | 113 | @dispatcher.add_method 114 | def foobar(**kwargs): 115 | return kwargs["foo"] + kwargs["bar"] 116 | 117 | 118 | @Request.application 119 | def application(request): 120 | # Dispatcher is dictionary {: callable} 121 | dispatcher["echo"] = lambda s: s 122 | dispatcher["add"] = lambda a, b: a + b 123 | 124 | response = JSONRPCResponseManager.handle( 125 | request.data, dispatcher) 126 | return Response(response.json, mimetype='application/json') 127 | 128 | 129 | if __name__ == '__main__': 130 | run_simple('localhost', 4000, application) 131 | 132 | Client (uses `requests `_) 133 | 134 | .. code-block:: python 135 | 136 | import requests 137 | import json 138 | 139 | 140 | def main(): 141 | url = "http://localhost:4000/jsonrpc" 142 | 143 | # Example echo method 144 | payload = { 145 | "method": "echo", 146 | "params": ["echome!"], 147 | "jsonrpc": "2.0", 148 | "id": 0, 149 | } 150 | response = requests.post(url, json=payload).json() 151 | 152 | assert response["result"] == "echome!" 153 | assert response["jsonrpc"] 154 | assert response["id"] == 0 155 | 156 | if __name__ == "__main__": 157 | main() 158 | 159 | Competitors 160 | ----------- 161 | There are `several libraries `_ implementing JSON-RPC protocol. List below represents python libraries, none of the supports python3. tinyrpc looks better than others. 162 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to json-rpc 2 | 3 | :+1::tada: First off all, thanks for taking the time to contribute! :tada::+1: 4 | 5 | The following is a set of guidelines for contributing to [json-rpc](https://github.com/pavlov99/json-rpc), which is hosted on GitHub. These are mostly guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request. 6 | 7 | #### Table Of Contents 8 | 9 | [Code of Conduct](#code-of-conduct) 10 | 11 | [I don't want to read this whole thing, I just have a question!!!](#i-dont-want-to-read-this-whole-thing-i-just-have-a-question) 12 | 13 | [How Can I Contribute?](#how-can-i-contribute) 14 | * [Reporting Bugs](#reporting-bugs) 15 | * [Suggesting Enhancements](#suggesting-enhancements) 16 | * [Pull Requests](#pull-requests) 17 | 18 | [Styleguides](#styleguides) 19 | * [Git Commit Messages](#git-commit-messages) 20 | 21 | ## Code of Conduct 22 | 23 | This project and everyone participating in it is governed by the [json-rpc Code of Conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [json-rpc@p99.io](mailto:json-rpc@p99.io). 24 | 25 | ## I don't want to read this whole thing I just have a question!!! 26 | 27 | > **Note:** Please don't file an issue to ask a question. You'll get faster results by using the resources below. 28 | 29 | We have a message board [Gitter](https://gitter.im/pavlov99/json-rpc) where the community chimes in with helpful advice if you have questions. 30 | 31 | ## How Can I Contribute? 32 | 33 | ### Reporting Bugs 34 | 35 | This section guides you through submitting a bug report for json-rpc. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:. 36 | 37 | When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](ISSUE_TEMPLATE.md), the information it asks for helps us resolve issues faster. 38 | 39 | > **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one. 40 | 41 | #### How Do I Submit A (Good) Bug Report? 42 | 43 | Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue on that repository and provide the following information by filling in [the template](ISSUE_TEMPLATE.md). Add a label 'bug' to the issue. 44 | 45 | Explain the problem and include additional details to help maintainers reproduce the problem: 46 | 47 | * **Use a clear and descriptive title** for the issue to identify the problem. 48 | * **Describe the exact steps which reproduce the problem** in as many details as possible. For example, start by explaining how you used json-rpc, e.g. which command exactly you used, which framework if aplicable. When listing steps, **don't just say what you did, but explain how you did it**. 49 | * **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). 50 | * **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior. 51 | * **Explain which behavior you expected to see instead and why.** 52 | * **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 53 | * **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below. 54 | 55 | ### Suggesting Enhancements 56 | 57 | This section guides you through submitting an enhancement suggestion for json-rpc, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:. 58 | 59 | When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](ISSUE_TEMPLATE.md), including the steps that you imagine you would take if the feature you're requesting existed. 60 | 61 | #### How Do I Submit A (Good) Enhancement Suggestion? 62 | 63 | Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). Create an issue and provide the following information: 64 | 65 | * **Use a clear and descriptive title** for the issue to identify the suggestion. 66 | * **Provide a step-by-step description of the suggested enhancement** in as many details as possible. 67 | * **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines). 68 | * **Describe the current behavior** and **explain which behavior you expected to see instead** and why. 69 | * **Include screenshots and animated GIFs** which help you demonstrate the steps. You can use [this tool](http://www.cockos.com/licecap/) to record GIFs on macOS and Windows, and [this tool](https://github.com/colinkeenan/silentcast) or [this tool](https://github.com/GNOME/byzanz) on Linux. 70 | 71 | ### Pull Requests 72 | 73 | * Fill in [the required template](PULL_REQUEST_TEMPLATE.md) 74 | * Do not include issue numbers in the PR title 75 | * Include screenshots and animated GIFs in your pull request whenever possible. 76 | * Document your code with [Napoleon style](https://sphinxcontrib-napoleon.readthedocs.io/en/latest/) docstrings. 77 | * Add tests and ensure test regression. Pull request would not be accepted if it breaks the build. 78 | * End all files with a newline 79 | * Squash commits to logical units. If you fix commit "A" with commit "B", squash them into one and open pull request again. 80 | * Add you name to the end of [AUTHORS](AUTHORS) list. It approximately follows chronological order. 81 | * Make sure you use the same email for your commits. 82 | 83 | ## Styleguides 84 | 85 | ### Git Commit Messages 86 | 87 | * Use the present tense ("Add feature" not "Added feature") 88 | * Use the imperative mood ("Move cursor to..." not "Moves cursor to...") 89 | * Limit the first line to 72 characters or less 90 | * Reference issues and pull requests liberally after the first line 91 | * Consider starting the commit message with an applicable emoji: 92 | * :art: `:art:` when improving the format/structure of the code 93 | * :racehorse: `:racehorse:` when improving performance 94 | * :non-potable_water: `:non-potable_water:` when plugging memory leaks 95 | * :memo: `:memo:` when writing docs 96 | * :bug: `:bug:` when fixing a bug 97 | * :fire: `:fire:` when removing code or files 98 | * :green_heart: `:green_heart:` when fixing the CI build 99 | * :white_check_mark: `:white_check_mark:` when adding tests 100 | * :lock: `:lock:` when dealing with security 101 | * :shirt: `:shirt:` when removing linter warnings 102 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_examples20.py: -------------------------------------------------------------------------------- 1 | """ Exmples of usage with tests. 2 | 3 | Tests in this file represent examples taken from JSON-RPC specification. 4 | http://www.jsonrpc.org/specification#examples 5 | 6 | """ 7 | import sys 8 | import json 9 | 10 | from ..manager import JSONRPCResponseManager 11 | from ..jsonrpc2 import JSONRPC20Request, JSONRPC20BatchRequest 12 | 13 | if sys.version_info < (2, 7): 14 | import unittest2 as unittest 15 | else: 16 | import unittest 17 | 18 | 19 | def isjsonequal(json1, json2): 20 | return json.loads(json1) == json.loads(json2) 21 | 22 | 23 | class TestJSONRPCExamples(unittest.TestCase): 24 | def setUp(self): 25 | self.dispatcher = { 26 | "subtract": lambda a, b: a - b, 27 | } 28 | 29 | def test_rpc_call_with_positional_parameters(self): 30 | req = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}' # noqa 31 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 32 | self.assertTrue(isjsonequal( 33 | response.json, 34 | '{"jsonrpc": "2.0", "result": 19, "id": 1}' 35 | )) 36 | 37 | req = '{"jsonrpc": "2.0", "method": "subtract", "params": [23, 42], "id": 2}' # noqa 38 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 39 | self.assertTrue(isjsonequal( 40 | response.json, 41 | '{"jsonrpc": "2.0", "result": -19, "id": 2}' 42 | )) 43 | 44 | def test_rpc_call_with_named_parameters(self): 45 | def subtract(minuend=None, subtrahend=None): 46 | return minuend - subtrahend 47 | 48 | dispatcher = { 49 | "subtract": subtract, 50 | "sum": lambda *args: sum(args), 51 | "get_data": lambda: ["hello", 5], 52 | } 53 | 54 | req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"subtrahend": 23, "minuend": 42}, "id": 3}' # noqa 55 | response = JSONRPCResponseManager.handle(req, dispatcher) 56 | self.assertTrue(isjsonequal( 57 | response.json, 58 | '{"jsonrpc": "2.0", "result": 19, "id": 3}' 59 | )) 60 | 61 | req = '{"jsonrpc": "2.0", "method": "subtract", "params": {"minuend": 42, "subtrahend": 23}, "id": 4}' # noqa 62 | response = JSONRPCResponseManager.handle(req, dispatcher) 63 | self.assertTrue(isjsonequal( 64 | response.json, 65 | '{"jsonrpc": "2.0", "result": 19, "id": 4}', 66 | )) 67 | 68 | def test_notification(self): 69 | req = '{"jsonrpc": "2.0", "method": "update", "params": [1,2,3,4,5]}' 70 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 71 | self.assertEqual(response, None) 72 | 73 | req = '{"jsonrpc": "2.0", "method": "foobar"}' 74 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 75 | self.assertEqual(response, None) 76 | 77 | def test_rpc_call_of_non_existent_method(self): 78 | req = '{"jsonrpc": "2.0", "method": "foobar", "id": "1"}' 79 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 80 | self.assertTrue(isjsonequal( 81 | response.json, 82 | '{"jsonrpc": "2.0", "error": {"code": -32601, "message": "Method not found"}, "id": "1"}' # noqa 83 | )) 84 | 85 | def test_rpc_call_with_invalid_json(self): 86 | req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' 87 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 88 | self.assertTrue(isjsonequal( 89 | response.json, 90 | '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa 91 | )) 92 | 93 | def test_rpc_call_with_invalid_request_object(self): 94 | req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' 95 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 96 | self.assertTrue(isjsonequal( 97 | response.json, 98 | '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa 99 | )) 100 | 101 | def test_rpc_call_batch_invalid_json(self): 102 | req = """[ 103 | {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, 104 | {"jsonrpc": "2.0", "method" 105 | ]""" 106 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 107 | self.assertTrue(isjsonequal( 108 | response.json, 109 | '{"jsonrpc": "2.0", "error": {"code": -32700, "message": "Parse error"}, "id": null}' # noqa 110 | )) 111 | 112 | def test_rpc_call_with_an_empty_array(self): 113 | req = '[]' 114 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 115 | self.assertTrue(isjsonequal( 116 | response.json, 117 | '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa 118 | )) 119 | 120 | def test_rpc_call_with_rpc_call_with_an_invalid_batch_but_not_empty(self): 121 | req = '[1]' 122 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 123 | self.assertTrue(isjsonequal( 124 | response.json, 125 | '{"jsonrpc": "2.0", "error": {"code": -32600, "message": "Invalid Request"}, "id": null}' # noqa 126 | )) 127 | 128 | def test_rpc_call_with_invalid_batch(self): 129 | req = '[1,2,3]' 130 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 131 | self.assertTrue( 132 | response, 133 | json.loads("""[ 134 | {"jsonrpc": "2.0", "error": {"code": -32600, 135 | "message": "Invalid Request"}, "id": null}, 136 | {"jsonrpc": "2.0", "error": {"code": -32600, 137 | "message": "Invalid Request"}, "id": null}, 138 | {"jsonrpc": "2.0", "error": {"code": -32600, 139 | "message": "Invalid Request"}, "id": null} 140 | ]""") 141 | ) 142 | 143 | def test_rpc_call_batch(self): 144 | req = """[ 145 | {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, 146 | {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, 147 | {"jsonrpc": "2.0", "method": "subtract", 148 | "params": [42,23], "id": "2"}, 149 | {"foo": "boo"}, 150 | {"jsonrpc": "2.0", "method": "foo.get", 151 | "params": {"name": "myself"}, "id": "5"}, 152 | {"jsonrpc": "2.0", "method": "get_data", "id": "9"} 153 | ]""" 154 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 155 | self.assertTrue( 156 | response, 157 | json.loads("""[ 158 | {"jsonrpc": "2.0", "result": 7, "id": "1"}, 159 | {"jsonrpc": "2.0", "result": 19, "id": "2"}, 160 | {"jsonrpc": "2.0", "error": {"code": -32600, 161 | "message": "Invalid Request"}, "id": null}, 162 | {"jsonrpc": "2.0", "error": {"code": -32601, 163 | "message": "Method not found"}, "id": "5"}, 164 | {"jsonrpc": "2.0", "result": ["hello", 5], "id": "9"} 165 | ]""") 166 | ) 167 | 168 | def test_rpc_call_batch_all_notifications(self): 169 | req = """[ 170 | {"jsonrpc": "2.0", "method": "notify_sum", "params": [1,2,4]}, 171 | {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]} 172 | ]""" 173 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 174 | self.assertEqual(response, None) 175 | 176 | def test_rpc_call_response_request(self): 177 | req = '{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": 1}' # noqa 178 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 179 | self.assertTrue(isinstance( 180 | response.request, 181 | JSONRPC20Request 182 | )) 183 | self.assertTrue(isjsonequal( 184 | response.request.json, 185 | req 186 | )) 187 | 188 | def test_rpc_call_response_request_batch(self): 189 | req = """[ 190 | {"jsonrpc": "2.0", "method": "sum", "params": [1,2,4], "id": "1"}, 191 | {"jsonrpc": "2.0", "method": "notify_hello", "params": [7]}, 192 | {"jsonrpc": "2.0", "method": "subtract", 193 | "params": [42,23], "id": "2"}, 194 | {"jsonrpc": "2.0", "method": "foo.get", 195 | "params": {"name": "myself"}, "id": "5"}, 196 | {"jsonrpc": "2.0", "method": "get_data", "id": "9"} 197 | ]""" 198 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 199 | self.assertTrue(isinstance( 200 | response.request, 201 | JSONRPC20BatchRequest 202 | )) 203 | self.assertTrue(isjsonequal( 204 | response.request.json, 205 | req 206 | )) 207 | -------------------------------------------------------------------------------- /docs/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # json-rpc documentation build configuration file, created by 4 | # sphinx-quickstart on Sun Oct 13 15:41:10 2013. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys 15 | import os 16 | 17 | # If extensions (or modules to document with autodoc) are in another directory, 18 | # add these directories to sys.path here. If the directory is relative to the 19 | # documentation root, use os.path.abspath to make it absolute, like shown here. 20 | sys.path.insert(0, os.path.abspath('../..')) 21 | 22 | from jsonrpc import version, PROJECT 23 | 24 | # -- General configuration ----------------------------------------------------- 25 | 26 | # If your documentation needs a minimal Sphinx version, state it here. 27 | #needs_sphinx = '1.0' 28 | 29 | # Add any Sphinx extension module names here, as strings. They can be extensions 30 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 31 | extensions = [ 32 | 'sphinx.ext.autodoc', 33 | 'sphinx.ext.napoleon', 34 | 'sphinx.ext.coverage', 35 | 'sphinx.ext.viewcode', 36 | ] 37 | 38 | # Add any paths that contain templates here, relative to this directory. 39 | templates_path = ['_templates'] 40 | 41 | # The suffix of source filenames. 42 | source_suffix = '.rst' 43 | 44 | # The encoding of source files. 45 | #source_encoding = 'utf-8-sig' 46 | 47 | # The master toctree document. 48 | master_doc = 'index' 49 | 50 | # General information about the project. 51 | project = PROJECT 52 | copyright = u'2013-2015, Kirill Pavlov' 53 | 54 | # The version info for the project you're documenting, acts as replacement for 55 | # |version| and |release|, also used in various other places throughout the 56 | # built documents. 57 | # 58 | # The short X.Y version. 59 | # The full version, including alpha/beta/rc tags. 60 | release = version 61 | 62 | # The language for content autogenerated by Sphinx. Refer to documentation 63 | # for a list of supported languages. 64 | #language = None 65 | 66 | # There are two options for replacing |today|: either, you set today to some 67 | # non-false value, then it is used: 68 | #today = '' 69 | # Else, today_fmt is used as the format for a strftime call. 70 | #today_fmt = '%B %d, %Y' 71 | 72 | # List of patterns, relative to source directory, that match files and 73 | # directories to ignore when looking for source files. 74 | exclude_patterns = ['_build'] 75 | 76 | # The reST default role (used for this markup: `text`) to use for all documents. 77 | #default_role = None 78 | 79 | # If true, '()' will be appended to :func: etc. cross-reference text. 80 | #add_function_parentheses = True 81 | 82 | # If true, the current module name will be prepended to all description 83 | # unit titles (such as .. function::). 84 | #add_module_names = True 85 | 86 | # If true, sectionauthor and moduleauthor directives will be shown in the 87 | # output. They are ignored by default. 88 | #show_authors = False 89 | 90 | # The name of the Pygments (syntax highlighting) style to use. 91 | pygments_style = 'sphinx' 92 | 93 | # A list of ignored prefixes for module index sorting. 94 | #modindex_common_prefix = [] 95 | 96 | 97 | # -- Options for HTML output --------------------------------------------------- 98 | 99 | # The theme to use for HTML and HTML Help pages. See the documentation for 100 | # a list of builtin themes. 101 | html_theme = 'sphinx_rtd_theme' 102 | 103 | # Theme options are theme-specific and customize the look and feel of a theme 104 | # further. For a list of options available for each theme, see the 105 | # documentation. 106 | #html_theme_options = {} 107 | 108 | # Add any paths that contain custom themes here, relative to this directory. 109 | import sphinx_rtd_theme 110 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] 111 | 112 | # The name for this set of Sphinx documents. If None, it defaults to 113 | # " v documentation". 114 | #html_title = None 115 | 116 | # A shorter title for the navigation bar. Default is the same as html_title. 117 | #html_short_title = None 118 | 119 | # The name of an image file (relative to this directory) to place at the top 120 | # of the sidebar. 121 | #html_logo = None 122 | 123 | # The name of an image file (within the static path) to use as favicon of the 124 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 125 | # pixels large. 126 | #html_favicon = None 127 | 128 | # Add any paths that contain custom static files (such as style sheets) here, 129 | # relative to this directory. They are copied after the builtin static files, 130 | # so a file named "default.css" will overwrite the builtin "default.css". 131 | html_static_path = ['_static'] 132 | 133 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 134 | # using the given strftime format. 135 | #html_last_updated_fmt = '%b %d, %Y' 136 | 137 | # If true, SmartyPants will be used to convert quotes and dashes to 138 | # typographically correct entities. 139 | #html_use_smartypants = True 140 | 141 | # Custom sidebar templates, maps document names to template names. 142 | #html_sidebars = {} 143 | 144 | # Additional templates that should be rendered to pages, maps page names to 145 | # template names. 146 | #html_additional_pages = {} 147 | 148 | # If false, no module index is generated. 149 | #html_domain_indices = True 150 | 151 | # If false, no index is generated. 152 | #html_use_index = True 153 | 154 | # If true, the index is split into individual pages for each letter. 155 | #html_split_index = False 156 | 157 | # If true, links to the reST sources are added to the pages. 158 | #html_show_sourcelink = True 159 | 160 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 161 | #html_show_sphinx = True 162 | 163 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 164 | #html_show_copyright = True 165 | 166 | # If true, an OpenSearch description file will be output, and all pages will 167 | # contain a tag referring to it. The value of this option must be the 168 | # base URL from which the finished HTML is served. 169 | #html_use_opensearch = '' 170 | 171 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 172 | #html_file_suffix = None 173 | 174 | # Output file base name for HTML help builder. 175 | htmlhelp_basename = 'json-rpcdoc' 176 | 177 | 178 | # -- Options for LaTeX output -------------------------------------------------- 179 | 180 | latex_elements = { 181 | # The paper size ('letterpaper' or 'a4paper'). 182 | #'papersize': 'letterpaper', 183 | 184 | # The font size ('10pt', '11pt' or '12pt'). 185 | #'pointsize': '10pt', 186 | 187 | # Additional stuff for the LaTeX preamble. 188 | #'preamble': '', 189 | } 190 | 191 | # Grouping the document tree into LaTeX files. List of tuples 192 | # (source start file, target name, title, author, documentclass [howto/manual]). 193 | latex_documents = [ 194 | ('index', 'json-rpc.tex', u'json-rpc Documentation', 195 | u'Kirill Pavlov', 'manual'), 196 | ] 197 | 198 | # The name of an image file (relative to this directory) to place at the top of 199 | # the title page. 200 | #latex_logo = None 201 | 202 | # For "manual" documents, if this is true, then toplevel headings are parts, 203 | # not chapters. 204 | #latex_use_parts = False 205 | 206 | # If true, show page references after internal links. 207 | #latex_show_pagerefs = False 208 | 209 | # If true, show URL addresses after external links. 210 | #latex_show_urls = False 211 | 212 | # Documents to append as an appendix to all manuals. 213 | #latex_appendices = [] 214 | 215 | # If false, no module index is generated. 216 | #latex_domain_indices = True 217 | 218 | 219 | # -- Options for manual page output -------------------------------------------- 220 | 221 | # One entry per manual page. List of tuples 222 | # (source start file, name, description, authors, manual section). 223 | man_pages = [ 224 | ('index', 'json-rpc', u'json-rpc Documentation', 225 | [u'Kirill Pavlov'], 1) 226 | ] 227 | 228 | # If true, show URL addresses after external links. 229 | #man_show_urls = False 230 | 231 | 232 | # -- Options for Texinfo output ------------------------------------------------ 233 | 234 | # Grouping the document tree into Texinfo files. List of tuples 235 | # (source start file, target name, title, author, 236 | # dir menu entry, description, category) 237 | texinfo_documents = [ 238 | ('index', 'json-rpc', u'json-rpc Documentation', 239 | u'Kirill Pavlov', 'json-rpc', 'One line description of project.', 240 | 'Miscellaneous'), 241 | ] 242 | 243 | # Documents to append as an appendix to all manuals. 244 | #texinfo_appendices = [] 245 | 246 | # If false, no module index is generated. 247 | #texinfo_domain_indices = True 248 | 249 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 250 | #texinfo_show_urls = 'footnote' 251 | 252 | # lint_ignore=E501 253 | -------------------------------------------------------------------------------- /jsonrpc/jsonrpc2.py: -------------------------------------------------------------------------------- 1 | from . import six 2 | import json 3 | 4 | from .exceptions import JSONRPCError, JSONRPCInvalidRequestException 5 | from .base import JSONRPCBaseRequest, JSONRPCBaseResponse 6 | 7 | 8 | class JSONRPC20Request(JSONRPCBaseRequest): 9 | 10 | """ A rpc call is represented by sending a Request object to a Server. 11 | 12 | :param str method: A String containing the name of the method to be 13 | invoked. Method names that begin with the word rpc followed by a 14 | period character (U+002E or ASCII 46) are reserved for rpc-internal 15 | methods and extensions and MUST NOT be used for anything else. 16 | 17 | :param params: A Structured value that holds the parameter values to be 18 | used during the invocation of the method. This member MAY be omitted. 19 | :type params: iterable or dict 20 | 21 | :param _id: An identifier established by the Client that MUST contain a 22 | String, Number, or NULL value if included. If it is not included it is 23 | assumed to be a notification. The value SHOULD normally not be Null 24 | [1] and Numbers SHOULD NOT contain fractional parts [2]. 25 | :type _id: str or int or None 26 | 27 | :param bool is_notification: Whether request is notification or not. If 28 | value is True, _id is not included to request. It allows to create 29 | requests with id = null. 30 | 31 | The Server MUST reply with the same value in the Response object if 32 | included. This member is used to correlate the context between the two 33 | objects. 34 | 35 | [1] The use of Null as a value for the id member in a Request object is 36 | discouraged, because this specification uses a value of Null for Responses 37 | with an unknown id. Also, because JSON-RPC 1.0 uses an id value of Null 38 | for Notifications this could cause confusion in handling. 39 | 40 | [2] Fractional parts may be problematic, since many decimal fractions 41 | cannot be represented exactly as binary fractions. 42 | 43 | """ 44 | 45 | JSONRPC_VERSION = "2.0" 46 | REQUIRED_FIELDS = set(["jsonrpc", "method"]) 47 | POSSIBLE_FIELDS = set(["jsonrpc", "method", "params", "id"]) 48 | 49 | @property 50 | def data(self): 51 | data = dict( 52 | (k, v) for k, v in self._data.items() 53 | if not (k == "id" and self.is_notification) 54 | ) 55 | data["jsonrpc"] = self.JSONRPC_VERSION 56 | return data 57 | 58 | @data.setter 59 | def data(self, value): 60 | if not isinstance(value, dict): 61 | raise ValueError("data should be dict") 62 | 63 | self._data = value 64 | 65 | @property 66 | def method(self): 67 | return self._data.get("method") 68 | 69 | @method.setter 70 | def method(self, value): 71 | if not isinstance(value, six.string_types): 72 | raise ValueError("Method should be string") 73 | 74 | if value.startswith("rpc."): 75 | raise ValueError( 76 | "Method names that begin with the word rpc followed by a " + 77 | "period character (U+002E or ASCII 46) are reserved for " + 78 | "rpc-internal methods and extensions and MUST NOT be used " + 79 | "for anything else.") 80 | 81 | self._data["method"] = str(value) 82 | 83 | @property 84 | def params(self): 85 | return self._data.get("params") 86 | 87 | @params.setter 88 | def params(self, value): 89 | if value is not None and not isinstance(value, (list, tuple, dict)): 90 | raise ValueError("Incorrect params {0}".format(value)) 91 | 92 | value = list(value) if isinstance(value, tuple) else value 93 | 94 | if value is not None: 95 | self._data["params"] = value 96 | 97 | @property 98 | def _id(self): 99 | return self._data.get("id") 100 | 101 | @_id.setter 102 | def _id(self, value): 103 | if value is not None and \ 104 | not isinstance(value, six.string_types + six.integer_types): 105 | raise ValueError("id should be string or integer") 106 | 107 | self._data["id"] = value 108 | 109 | @classmethod 110 | def from_json(cls, json_str): 111 | data = cls.deserialize(json_str) 112 | return cls.from_data(data) 113 | 114 | @classmethod 115 | def from_data(cls, data): 116 | is_batch = isinstance(data, list) 117 | data = data if is_batch else [data] 118 | 119 | if not data: 120 | raise JSONRPCInvalidRequestException("[] value is not accepted") 121 | 122 | if not all(isinstance(d, dict) for d in data): 123 | raise JSONRPCInvalidRequestException( 124 | "Each request should be an object (dict)") 125 | 126 | result = [] 127 | for d in data: 128 | if not cls.REQUIRED_FIELDS <= set(d.keys()) <= cls.POSSIBLE_FIELDS: 129 | extra = set(d.keys()) - cls.POSSIBLE_FIELDS 130 | missed = cls.REQUIRED_FIELDS - set(d.keys()) 131 | msg = "Invalid request. Extra fields: {0}, Missed fields: {1}" 132 | raise JSONRPCInvalidRequestException(msg.format(extra, missed)) 133 | 134 | try: 135 | result.append(JSONRPC20Request( 136 | method=d["method"], params=d.get("params"), 137 | _id=d.get("id"), is_notification="id" not in d, 138 | )) 139 | except ValueError as e: 140 | raise JSONRPCInvalidRequestException(str(e)) 141 | 142 | return JSONRPC20BatchRequest(*result) if is_batch else result[0] 143 | 144 | 145 | class JSONRPC20BatchRequest(object): 146 | 147 | """ Batch JSON-RPC 2.0 Request. 148 | 149 | :param JSONRPC20Request *requests: requests 150 | 151 | """ 152 | 153 | JSONRPC_VERSION = "2.0" 154 | 155 | def __init__(self, *requests): 156 | self.requests = requests 157 | 158 | @classmethod 159 | def from_json(cls, json_str): 160 | return JSONRPC20Request.from_json(json_str) 161 | 162 | @property 163 | def json(self): 164 | return json.dumps([r.data for r in self.requests]) 165 | 166 | def __iter__(self): 167 | return iter(self.requests) 168 | 169 | 170 | class JSONRPC20Response(JSONRPCBaseResponse): 171 | 172 | """ JSON-RPC response object to JSONRPC20Request. 173 | 174 | When a rpc call is made, the Server MUST reply with a Response, except for 175 | in the case of Notifications. The Response is expressed as a single JSON 176 | Object, with the following members: 177 | 178 | :param str jsonrpc: A String specifying the version of the JSON-RPC 179 | protocol. MUST be exactly "2.0". 180 | 181 | :param result: This member is REQUIRED on success. 182 | This member MUST NOT exist if there was an error invoking the method. 183 | The value of this member is determined by the method invoked on the 184 | Server. 185 | 186 | :param dict error: This member is REQUIRED on error. 187 | This member MUST NOT exist if there was no error triggered during 188 | invocation. The value for this member MUST be an Object. 189 | 190 | :param id: This member is REQUIRED. 191 | It MUST be the same as the value of the id member in the Request 192 | Object. If there was an error in detecting the id in the Request 193 | object (e.g. Parse error/Invalid Request), it MUST be Null. 194 | :type id: str or int or None 195 | 196 | Either the result member or error member MUST be included, but both 197 | members MUST NOT be included. 198 | 199 | """ 200 | 201 | JSONRPC_VERSION = "2.0" 202 | 203 | @property 204 | def data(self): 205 | data = dict((k, v) for k, v in self._data.items()) 206 | data["jsonrpc"] = self.JSONRPC_VERSION 207 | return data 208 | 209 | @data.setter 210 | def data(self, value): 211 | if not isinstance(value, dict): 212 | raise ValueError("data should be dict") 213 | self._data = value 214 | 215 | @property 216 | def result(self): 217 | return self._data.get("result") 218 | 219 | @result.setter 220 | def result(self, value): 221 | if self.error: 222 | raise ValueError("Either result or error should be used") 223 | self._data["result"] = value 224 | 225 | @property 226 | def error(self): 227 | return self._data.get("error") 228 | 229 | @error.setter 230 | def error(self, value): 231 | self._data.pop('value', None) 232 | if value: 233 | self._data["error"] = value 234 | # Test error 235 | JSONRPCError(**value) 236 | 237 | @property 238 | def _id(self): 239 | return self._data.get("id") 240 | 241 | @_id.setter 242 | def _id(self, value): 243 | if value is not None and \ 244 | not isinstance(value, six.string_types + six.integer_types): 245 | raise ValueError("id should be string or integer") 246 | 247 | self._data["id"] = value 248 | 249 | 250 | class JSONRPC20BatchResponse(object): 251 | 252 | JSONRPC_VERSION = "2.0" 253 | 254 | def __init__(self, *responses): 255 | self.responses = responses 256 | self.request = None # type: JSONRPC20BatchRequest 257 | 258 | @property 259 | def data(self): 260 | return [r.data for r in self.responses] 261 | 262 | @property 263 | def json(self): 264 | return json.dumps(self.data) 265 | 266 | def __iter__(self): 267 | return iter(self.responses) 268 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_manager.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from ..dispatcher import Dispatcher 4 | from ..manager import JSONRPCResponseManager 5 | from ..jsonrpc2 import ( 6 | JSONRPC20BatchRequest, 7 | JSONRPC20BatchResponse, 8 | JSONRPC20Request, 9 | JSONRPC20Response, 10 | ) 11 | from ..jsonrpc1 import JSONRPC10Request, JSONRPC10Response 12 | from ..exceptions import JSONRPCDispatchException 13 | 14 | if sys.version_info < (3, 3): 15 | from mock import MagicMock 16 | else: 17 | from unittest.mock import MagicMock 18 | 19 | if sys.version_info < (2, 7): 20 | import unittest2 as unittest 21 | else: 22 | import unittest 23 | 24 | 25 | class TestJSONRPCResponseManager(unittest.TestCase): 26 | def setUp(self): 27 | def raise_(e): 28 | raise e 29 | 30 | self.long_time_method = MagicMock() 31 | self.dispatcher = Dispatcher() 32 | self.dispatcher["add"] = sum 33 | self.dispatcher["multiply"] = lambda a, b: a * b 34 | self.dispatcher["list_len"] = len 35 | self.dispatcher["101_base"] = lambda **kwargs: int("101", **kwargs) 36 | self.dispatcher["error"] = lambda: raise_( 37 | KeyError("error_explanation")) 38 | self.dispatcher["type_error"] = lambda: raise_( 39 | TypeError("TypeError inside method")) 40 | self.dispatcher["long_time_method"] = self.long_time_method 41 | self.dispatcher["dispatch_error"] = lambda x: raise_( 42 | JSONRPCDispatchException(code=4000, message="error", 43 | data={"param": 1})) 44 | 45 | @self.dispatcher.add_method(context_arg="context") 46 | def return_json_rpc_id(context): 47 | return context["request"]._id 48 | 49 | def test_dispatch_error(self): 50 | request = JSONRPC20Request("dispatch_error", ["test"], _id=0) 51 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 52 | self.assertTrue(isinstance(response, JSONRPC20Response)) 53 | self.assertEqual(response.error["message"], "error") 54 | self.assertEqual(response.error["code"], 4000) 55 | self.assertEqual(response.error["data"], {"param": 1}) 56 | 57 | def test_returned_type_response(self): 58 | request = JSONRPC20Request("add", [[]], _id=0) 59 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 60 | self.assertTrue(isinstance(response, JSONRPC20Response)) 61 | 62 | def test_returned_type_butch_response(self): 63 | request = JSONRPC20BatchRequest( 64 | JSONRPC20Request("add", [[]], _id=0)) 65 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 66 | self.assertTrue(isinstance(response, JSONRPC20BatchResponse)) 67 | 68 | def test_returned_type_response_rpc10(self): 69 | request = JSONRPC10Request("add", [[]], _id=0) 70 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 71 | self.assertTrue(isinstance(response, JSONRPC10Response)) 72 | 73 | def test_parse_error(self): 74 | req = '{"jsonrpc": "2.0", "method": "foobar, "params": "bar", "baz]' 75 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 76 | self.assertTrue(isinstance(response, JSONRPC20Response)) 77 | self.assertEqual(response.error["message"], "Parse error") 78 | self.assertEqual(response.error["code"], -32700) 79 | 80 | def test_invalid_request(self): 81 | req = '{"jsonrpc": "2.0", "method": 1, "params": "bar"}' 82 | response = JSONRPCResponseManager.handle(req, self.dispatcher) 83 | self.assertTrue(isinstance(response, JSONRPC20Response)) 84 | self.assertEqual(response.error["message"], "Invalid Request") 85 | self.assertEqual(response.error["code"], -32600) 86 | 87 | def test_method_not_found(self): 88 | request = JSONRPC20Request("does_not_exist", [[]], _id=0) 89 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 90 | self.assertTrue(isinstance(response, JSONRPC20Response)) 91 | self.assertEqual(response.error["message"], "Method not found") 92 | self.assertEqual(response.error["code"], -32601) 93 | 94 | def test_invalid_params(self): 95 | request = JSONRPC20Request("add", {"a": 0}, _id=0) 96 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 97 | self.assertTrue(isinstance(response, JSONRPC20Response)) 98 | self.assertEqual(response.error["message"], "Invalid params") 99 | self.assertEqual(response.error["code"], -32602) 100 | self.assertIn(response.error["data"]["message"], [ 101 | 'sum() takes no keyword arguments', 102 | "sum() got an unexpected keyword argument 'a'", 103 | 'sum() takes at least 1 positional argument (0 given)', 104 | ]) 105 | 106 | def test_invalid_params_custom_function(self): 107 | request = JSONRPC20Request("multiply", [0], _id=0) 108 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 109 | self.assertTrue(isinstance(response, JSONRPC20Response)) 110 | self.assertEqual(response.error["message"], "Invalid params") 111 | self.assertEqual(response.error["code"], -32602) 112 | 113 | request = JSONRPC20Request("multiply", [0, 1, 2], _id=0) 114 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 115 | self.assertTrue(isinstance(response, JSONRPC20Response)) 116 | self.assertEqual(response.error["message"], "Invalid params") 117 | self.assertEqual(response.error["code"], -32602) 118 | 119 | request = JSONRPC20Request("multiply", {"a": 1}, _id=0) 120 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 121 | self.assertTrue(isinstance(response, JSONRPC20Response)) 122 | self.assertEqual(response.error["message"], "Invalid params") 123 | self.assertEqual(response.error["code"], -32602) 124 | 125 | request = JSONRPC20Request("multiply", {"a": 1, "b": 2, "c": 3}, _id=0) 126 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 127 | self.assertTrue(isinstance(response, JSONRPC20Response)) 128 | self.assertEqual(response.error["message"], "Invalid params") 129 | self.assertEqual(response.error["code"], -32602) 130 | 131 | def test_server_error(self): 132 | request = JSONRPC20Request("error", _id=0) 133 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 134 | self.assertTrue(isinstance(response, JSONRPC20Response)) 135 | self.assertEqual(response.error["message"], "Server error") 136 | self.assertEqual(response.error["code"], -32000) 137 | self.assertEqual(response.error["data"]['type'], "KeyError") 138 | self.assertEqual( 139 | response.error["data"]['args'], ('error_explanation',)) 140 | self.assertEqual( 141 | response.error["data"]['message'], "'error_explanation'") 142 | 143 | def test_notification_calls_method(self): 144 | request = JSONRPC20Request("long_time_method", is_notification=True) 145 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 146 | self.assertEqual(response, None) 147 | self.long_time_method.assert_called_once_with() 148 | 149 | def test_notification_does_not_return_error_does_not_exist(self): 150 | request = JSONRPC20Request("does_not_exist", is_notification=True) 151 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 152 | self.assertEqual(response, None) 153 | 154 | def test_notification_does_not_return_error_invalid_params(self): 155 | request = JSONRPC20Request("add", {"a": 0}, is_notification=True) 156 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 157 | self.assertEqual(response, None) 158 | 159 | def test_notification_does_not_return_error(self): 160 | request = JSONRPC20Request("error", is_notification=True) 161 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 162 | self.assertEqual(response, None) 163 | 164 | def test_type_error_inside_method(self): 165 | request = JSONRPC20Request("type_error", _id=0) 166 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 167 | self.assertTrue(isinstance(response, JSONRPC20Response)) 168 | self.assertEqual(response.error["message"], "Server error") 169 | self.assertEqual(response.error["code"], -32000) 170 | self.assertEqual(response.error["data"]['type'], "TypeError") 171 | self.assertEqual( 172 | response.error["data"]['args'], ('TypeError inside method',)) 173 | self.assertEqual( 174 | response.error["data"]['message'], 'TypeError inside method') 175 | 176 | def test_invalid_params_before_dispatcher_error(self): 177 | request = JSONRPC20Request( 178 | "dispatch_error", ["invalid", "params"], _id=0) 179 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher) 180 | self.assertTrue(isinstance(response, JSONRPC20Response)) 181 | self.assertEqual(response.error["message"], "Invalid params") 182 | self.assertEqual(response.error["code"], -32602) 183 | 184 | def test_setting_json_rpc_id_in_context(self): 185 | request = JSONRPC20Request("return_json_rpc_id", _id=42) 186 | response = JSONRPCResponseManager.handle(request.json, self.dispatcher, 187 | context={}) 188 | self.assertEqual(response.data["result"], 42) 189 | -------------------------------------------------------------------------------- /jsonrpc/tests/test_jsonrpc1.py: -------------------------------------------------------------------------------- 1 | import json 2 | import sys 3 | 4 | from ..exceptions import JSONRPCInvalidRequestException 5 | from ..jsonrpc1 import ( 6 | JSONRPC10Request, 7 | JSONRPC10Response, 8 | ) 9 | 10 | if sys.version_info < (2, 7): 11 | import unittest2 as unittest 12 | else: 13 | import unittest 14 | 15 | 16 | class TestJSONRPC10Request(unittest.TestCase): 17 | 18 | """ Test JSONRPC10Request functionality.""" 19 | 20 | def setUp(self): 21 | self.request_params = { 22 | "method": "add", 23 | "params": [1, 2], 24 | "_id": 1, 25 | } 26 | 27 | def test_correct_init(self): 28 | """ Test object is created.""" 29 | JSONRPC10Request(**self.request_params) 30 | 31 | def test_validation_incorrect_no_parameters(self): 32 | with self.assertRaises(ValueError): 33 | JSONRPC10Request() 34 | 35 | def test_method_validation_str(self): 36 | self.request_params.update({"method": "add"}) 37 | JSONRPC10Request(**self.request_params) 38 | 39 | def test_method_validation_not_str(self): 40 | self.request_params.update({"method": []}) 41 | with self.assertRaises(ValueError): 42 | JSONRPC10Request(**self.request_params) 43 | 44 | self.request_params.update({"method": {}}) 45 | with self.assertRaises(ValueError): 46 | JSONRPC10Request(**self.request_params) 47 | 48 | self.request_params.update({"method": None}) 49 | with self.assertRaises(ValueError): 50 | JSONRPC10Request(**self.request_params) 51 | 52 | def test_params_validation_list(self): 53 | self.request_params.update({"params": []}) 54 | JSONRPC10Request(**self.request_params) 55 | 56 | self.request_params.update({"params": [0]}) 57 | JSONRPC10Request(**self.request_params) 58 | 59 | def test_params_validation_tuple(self): 60 | self.request_params.update({"params": ()}) 61 | JSONRPC10Request(**self.request_params) 62 | 63 | self.request_params.update({"params": tuple([0])}) 64 | JSONRPC10Request(**self.request_params) 65 | 66 | def test_params_validation_dict(self): 67 | self.request_params.update({"params": {}}) 68 | with self.assertRaises(ValueError): 69 | JSONRPC10Request(**self.request_params) 70 | 71 | self.request_params.update({"params": {"a": 0}}) 72 | with self.assertRaises(ValueError): 73 | JSONRPC10Request(**self.request_params) 74 | 75 | def test_params_validation_none(self): 76 | self.request_params.update({"params": None}) 77 | with self.assertRaises(ValueError): 78 | JSONRPC10Request(**self.request_params) 79 | 80 | def test_params_validation_incorrect(self): 81 | self.request_params.update({"params": "str"}) 82 | with self.assertRaises(ValueError): 83 | JSONRPC10Request(**self.request_params) 84 | 85 | def test_request_args(self): 86 | self.assertEqual(JSONRPC10Request("add", []).args, ()) 87 | self.assertEqual(JSONRPC10Request("add", [1, 2]).args, (1, 2)) 88 | 89 | def test_id_validation_string(self): 90 | self.request_params.update({"_id": "id"}) 91 | JSONRPC10Request(**self.request_params) 92 | 93 | def test_id_validation_int(self): 94 | self.request_params.update({"_id": 0}) 95 | JSONRPC10Request(**self.request_params) 96 | 97 | def test_id_validation_null(self): 98 | self.request_params.update({"_id": "null"}) 99 | JSONRPC10Request(**self.request_params) 100 | 101 | def test_id_validation_none(self): 102 | self.request_params.update({"_id": None}) 103 | JSONRPC10Request(**self.request_params) 104 | 105 | def test_id_validation_float(self): 106 | self.request_params.update({"_id": 0.1}) 107 | JSONRPC10Request(**self.request_params) 108 | 109 | def test_id_validation_list_tuple(self): 110 | self.request_params.update({"_id": []}) 111 | JSONRPC10Request(**self.request_params) 112 | 113 | self.request_params.update({"_id": ()}) 114 | JSONRPC10Request(**self.request_params) 115 | 116 | def test_id_validation_default_id_none(self): 117 | del self.request_params["_id"] 118 | JSONRPC10Request(**self.request_params) 119 | 120 | def test_data_method_1(self): 121 | r = JSONRPC10Request("add", []) 122 | self.assertEqual(json.loads(r.json), r.data) 123 | self.assertEqual(r.data, { 124 | "method": "add", 125 | "params": [], 126 | "id": None, 127 | }) 128 | 129 | def test_data_method_2(self): 130 | r = JSONRPC10Request(method="add", params=[]) 131 | self.assertEqual(json.loads(r.json), r.data) 132 | self.assertEqual(r.data, { 133 | "method": "add", 134 | "params": [], 135 | "id": None, 136 | }) 137 | 138 | def test_data_params_1(self): 139 | r = JSONRPC10Request("add", params=[], _id=None) 140 | self.assertEqual(json.loads(r.json), r.data) 141 | self.assertEqual(r.data, { 142 | "method": "add", 143 | "params": [], 144 | "id": None, 145 | }) 146 | 147 | def test_data_params_2(self): 148 | r = JSONRPC10Request("add", ()) 149 | self.assertEqual(json.loads(r.json), r.data) 150 | self.assertEqual(r.data, { 151 | "method": "add", 152 | "params": [], 153 | "id": None, 154 | }) 155 | 156 | def test_data_params_3(self): 157 | r = JSONRPC10Request("add", (1, 2)) 158 | self.assertEqual(json.loads(r.json), r.data) 159 | self.assertEqual(r.data, { 160 | "method": "add", 161 | "params": [1, 2], 162 | "id": None, 163 | }) 164 | 165 | def test_data_id_1(self): 166 | r = JSONRPC10Request("add", [], _id="null") 167 | self.assertEqual(json.loads(r.json), r.data) 168 | self.assertEqual(r.data, { 169 | "method": "add", 170 | "params": [], 171 | "id": "null", 172 | }) 173 | 174 | def test_data_id_1_notification(self): 175 | r = JSONRPC10Request("add", [], _id="null", is_notification=True) 176 | self.assertEqual(json.loads(r.json), r.data) 177 | self.assertEqual(r.data, { 178 | "method": "add", 179 | "params": [], 180 | "id": None, 181 | }) 182 | 183 | def test_data_id_2(self): 184 | r = JSONRPC10Request("add", [], _id=None) 185 | self.assertEqual(json.loads(r.json), r.data) 186 | self.assertEqual(r.data, { 187 | "method": "add", 188 | "params": [], 189 | "id": None, 190 | }) 191 | 192 | def test_data_id_2_notification(self): 193 | r = JSONRPC10Request("add", [], _id=None, is_notification=True) 194 | self.assertEqual(json.loads(r.json), r.data) 195 | self.assertEqual(r.data, { 196 | "method": "add", 197 | "params": [], 198 | "id": None, 199 | }) 200 | 201 | def test_data_id_3(self): 202 | r = JSONRPC10Request("add", [], _id="id") 203 | self.assertEqual(json.loads(r.json), r.data) 204 | self.assertEqual(r.data, { 205 | "method": "add", 206 | "params": [], 207 | "id": "id", 208 | }) 209 | 210 | def test_data_id_3_notification(self): 211 | r = JSONRPC10Request("add", [], _id="id", is_notification=True) 212 | self.assertEqual(json.loads(r.json), r.data) 213 | self.assertEqual(r.data, { 214 | "method": "add", 215 | "params": [], 216 | "id": None, 217 | }) 218 | 219 | def test_data_id_4(self): 220 | r = JSONRPC10Request("add", [], _id=0) 221 | self.assertEqual(json.loads(r.json), r.data) 222 | self.assertEqual(r.data, { 223 | "method": "add", 224 | "params": [], 225 | "id": 0, 226 | }) 227 | 228 | def test_data_id_4_notification(self): 229 | r = JSONRPC10Request("add", [], _id=0, is_notification=True) 230 | self.assertEqual(json.loads(r.json), r.data) 231 | self.assertEqual(r.data, { 232 | "method": "add", 233 | "params": [], 234 | "id": None, 235 | }) 236 | 237 | def test_is_notification(self): 238 | r = JSONRPC10Request("add", []) 239 | self.assertTrue(r.is_notification) 240 | 241 | r = JSONRPC10Request("add", [], _id=None) 242 | self.assertTrue(r.is_notification) 243 | 244 | r = JSONRPC10Request("add", [], _id="null") 245 | self.assertFalse(r.is_notification) 246 | 247 | r = JSONRPC10Request("add", [], _id=0) 248 | self.assertFalse(r.is_notification) 249 | 250 | r = JSONRPC10Request("add", [], is_notification=True) 251 | self.assertTrue(r.is_notification) 252 | 253 | r = JSONRPC10Request("add", [], is_notification=True, _id=None) 254 | self.assertTrue(r.is_notification) 255 | 256 | r = JSONRPC10Request("add", [], is_notification=True, _id=0) 257 | self.assertTrue(r.is_notification) 258 | 259 | def test_set_unset_notification_keep_id(self): 260 | r = JSONRPC10Request("add", [], is_notification=True, _id=0) 261 | self.assertTrue(r.is_notification) 262 | self.assertEqual(r.data["id"], None) 263 | 264 | r.is_notification = False 265 | self.assertFalse(r.is_notification) 266 | self.assertEqual(r.data["id"], 0) 267 | 268 | def test_error_if_notification_true_but_id_none(self): 269 | r = JSONRPC10Request("add", [], is_notification=True, _id=None) 270 | with self.assertRaises(ValueError): 271 | r.is_notification = False 272 | 273 | def test_from_json_invalid_request_method(self): 274 | str_json = json.dumps({ 275 | "params": [1, 2], 276 | "id": 0, 277 | }) 278 | 279 | with self.assertRaises(JSONRPCInvalidRequestException): 280 | JSONRPC10Request.from_json(str_json) 281 | 282 | def test_from_json_invalid_request_params(self): 283 | str_json = json.dumps({ 284 | "method": "add", 285 | "id": 0, 286 | }) 287 | 288 | with self.assertRaises(JSONRPCInvalidRequestException): 289 | JSONRPC10Request.from_json(str_json) 290 | 291 | def test_from_json_invalid_request_id(self): 292 | str_json = json.dumps({ 293 | "method": "add", 294 | "params": [1, 2], 295 | }) 296 | 297 | with self.assertRaises(JSONRPCInvalidRequestException): 298 | JSONRPC10Request.from_json(str_json) 299 | 300 | def test_from_json_invalid_request_extra_data(self): 301 | str_json = json.dumps({ 302 | "method": "add", 303 | "params": [1, 2], 304 | "id": 0, 305 | "is_notification": True, 306 | }) 307 | 308 | with self.assertRaises(JSONRPCInvalidRequestException): 309 | JSONRPC10Request.from_json(str_json) 310 | 311 | def test_from_json_request(self): 312 | str_json = json.dumps({ 313 | "method": "add", 314 | "params": [1, 2], 315 | "id": 0, 316 | }) 317 | 318 | request = JSONRPC10Request.from_json(str_json) 319 | self.assertTrue(isinstance(request, JSONRPC10Request)) 320 | self.assertEqual(request.method, "add") 321 | self.assertEqual(request.params, [1, 2]) 322 | self.assertEqual(request._id, 0) 323 | self.assertFalse(request.is_notification) 324 | 325 | def test_from_json_request_notification(self): 326 | str_json = json.dumps({ 327 | "method": "add", 328 | "params": [1, 2], 329 | "id": None, 330 | }) 331 | 332 | request = JSONRPC10Request.from_json(str_json) 333 | self.assertTrue(isinstance(request, JSONRPC10Request)) 334 | self.assertEqual(request.method, "add") 335 | self.assertEqual(request.params, [1, 2]) 336 | self.assertEqual(request._id, None) 337 | self.assertTrue(request.is_notification) 338 | 339 | def test_from_json_string_not_dict(self): 340 | with self.assertRaises(ValueError): 341 | JSONRPC10Request.from_json("[]") 342 | 343 | with self.assertRaises(ValueError): 344 | JSONRPC10Request.from_json("0") 345 | 346 | def test_data_setter(self): 347 | request = JSONRPC10Request(**self.request_params) 348 | with self.assertRaises(ValueError): 349 | request.data = [] 350 | 351 | with self.assertRaises(ValueError): 352 | request.data = "" 353 | 354 | with self.assertRaises(ValueError): 355 | request.data = None 356 | 357 | 358 | class TestJSONRPC10Response(unittest.TestCase): 359 | 360 | """ Test JSONRPC10Response functionality.""" 361 | 362 | def setUp(self): 363 | self.response_success_params = { 364 | "result": "", 365 | "error": None, 366 | "_id": 1, 367 | } 368 | self.response_error_params = { 369 | "result": None, 370 | "error": { 371 | "code": 1, 372 | "message": "error", 373 | }, 374 | "_id": 1, 375 | } 376 | 377 | def test_correct_init(self): 378 | """ Test object is created.""" 379 | JSONRPC10Response(**self.response_success_params) 380 | JSONRPC10Response(**self.response_error_params) 381 | 382 | def test_validation_incorrect_no_parameters(self): 383 | with self.assertRaises(ValueError): 384 | JSONRPC10Response() 385 | 386 | def test_validation_success_incorrect(self): 387 | wrong_params = self.response_success_params 388 | del wrong_params["_id"] 389 | with self.assertRaises(ValueError): 390 | JSONRPC10Response(**wrong_params) 391 | 392 | def test_validation_error_incorrect(self): 393 | wrong_params = self.response_error_params 394 | del wrong_params["_id"] 395 | with self.assertRaises(ValueError): 396 | JSONRPC10Response(**wrong_params) 397 | 398 | def _test_validation_incorrect_result_and_error(self): 399 | # @todo: remove 400 | # It is OK because result is an mepty string, it is still result 401 | with self.assertRaises(ValueError): 402 | JSONRPC10Response(result="", error="", _id=0) 403 | 404 | response = JSONRPC10Response(error="", _id=0) 405 | with self.assertRaises(ValueError): 406 | response.result = "" 407 | 408 | def test_data(self): 409 | r = JSONRPC10Response(result="", _id=0) 410 | self.assertEqual(json.loads(r.json), r.data) 411 | self.assertEqual(r.data, { 412 | "result": "", 413 | "id": 0, 414 | }) 415 | 416 | def test_data_setter(self): 417 | response = JSONRPC10Response(**self.response_success_params) 418 | with self.assertRaises(ValueError): 419 | response.data = [] 420 | 421 | with self.assertRaises(ValueError): 422 | response.data = "" 423 | 424 | with self.assertRaises(ValueError): 425 | response.data = None 426 | 427 | def test_validation_id(self): 428 | response = JSONRPC10Response(**self.response_success_params) 429 | self.assertEqual(response._id, self.response_success_params["_id"]) 430 | -------------------------------------------------------------------------------- /jsonrpc/six.py: -------------------------------------------------------------------------------- 1 | """Utilities for writing code that runs on Python 2 and 3""" 2 | 3 | # Copyright (c) 2010-2013 Benjamin Peterson 4 | # 5 | # Permission is hereby granted, free of charge, to any person obtaining a copy 6 | # of this software and associated documentation files (the "Software"), to deal 7 | # in the Software without restriction, including without limitation the rights 8 | # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | # copies of the Software, and to permit persons to whom the Software is 10 | # furnished to do so, subject to the following conditions: 11 | # 12 | # The above copyright notice and this permission notice shall be included in all 13 | # copies or substantial portions of the Software. 14 | # 15 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | # SOFTWARE. 22 | 23 | import operator 24 | import sys 25 | import types 26 | 27 | __author__ = "Benjamin Peterson " 28 | __version__ = "1.4.1" 29 | 30 | 31 | # Useful for very coarse version differentiation. 32 | PY2 = sys.version_info[0] == 2 33 | PY3 = sys.version_info[0] == 3 34 | 35 | if PY3: 36 | string_types = str, 37 | integer_types = int, 38 | class_types = type, 39 | text_type = str 40 | binary_type = bytes 41 | 42 | MAXSIZE = sys.maxsize 43 | else: 44 | string_types = basestring, 45 | integer_types = (int, long) 46 | class_types = (type, types.ClassType) 47 | text_type = unicode 48 | binary_type = str 49 | 50 | if sys.platform.startswith("java"): 51 | # Jython always uses 32 bits. 52 | MAXSIZE = int((1 << 31) - 1) 53 | else: 54 | # It's possible to have sizeof(long) != sizeof(Py_ssize_t). 55 | class X(object): 56 | def __len__(self): 57 | return 1 << 31 58 | try: 59 | len(X()) 60 | except OverflowError: 61 | # 32-bit 62 | MAXSIZE = int((1 << 31) - 1) 63 | else: 64 | # 64-bit 65 | MAXSIZE = int((1 << 63) - 1) 66 | del X 67 | 68 | 69 | def _add_doc(func, doc): 70 | """Add documentation to a function.""" 71 | func.__doc__ = doc 72 | 73 | 74 | def _import_module(name): 75 | """Import module, returning the module after the last dot.""" 76 | __import__(name) 77 | return sys.modules[name] 78 | 79 | 80 | class _LazyDescr(object): 81 | 82 | def __init__(self, name): 83 | self.name = name 84 | 85 | def __get__(self, obj, tp): 86 | result = self._resolve() 87 | setattr(obj, self.name, result) 88 | # This is a bit ugly, but it avoids running this again. 89 | delattr(tp, self.name) 90 | return result 91 | 92 | 93 | class MovedModule(_LazyDescr): 94 | 95 | def __init__(self, name, old, new=None): 96 | super(MovedModule, self).__init__(name) 97 | if PY3: 98 | if new is None: 99 | new = name 100 | self.mod = new 101 | else: 102 | self.mod = old 103 | 104 | def _resolve(self): 105 | return _import_module(self.mod) 106 | 107 | 108 | class MovedAttribute(_LazyDescr): 109 | 110 | def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): 111 | super(MovedAttribute, self).__init__(name) 112 | if PY3: 113 | if new_mod is None: 114 | new_mod = name 115 | self.mod = new_mod 116 | if new_attr is None: 117 | if old_attr is None: 118 | new_attr = name 119 | else: 120 | new_attr = old_attr 121 | self.attr = new_attr 122 | else: 123 | self.mod = old_mod 124 | if old_attr is None: 125 | old_attr = name 126 | self.attr = old_attr 127 | 128 | def _resolve(self): 129 | module = _import_module(self.mod) 130 | return getattr(module, self.attr) 131 | 132 | 133 | 134 | class _MovedItems(types.ModuleType): 135 | """Lazy loading of moved objects""" 136 | 137 | 138 | _moved_attributes = [ 139 | MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), 140 | MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), 141 | MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), 142 | MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), 143 | MovedAttribute("map", "itertools", "builtins", "imap", "map"), 144 | MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), 145 | MovedAttribute("reload_module", "__builtin__", "imp", "reload"), 146 | MovedAttribute("reduce", "__builtin__", "functools"), 147 | MovedAttribute("StringIO", "StringIO", "io"), 148 | MovedAttribute("UserString", "UserString", "collections"), 149 | MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), 150 | MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), 151 | MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), 152 | 153 | MovedModule("builtins", "__builtin__"), 154 | MovedModule("configparser", "ConfigParser"), 155 | MovedModule("copyreg", "copy_reg"), 156 | MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), 157 | MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), 158 | MovedModule("http_cookies", "Cookie", "http.cookies"), 159 | MovedModule("html_entities", "htmlentitydefs", "html.entities"), 160 | MovedModule("html_parser", "HTMLParser", "html.parser"), 161 | MovedModule("http_client", "httplib", "http.client"), 162 | MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), 163 | MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), 164 | MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), 165 | MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), 166 | MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), 167 | MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), 168 | MovedModule("cPickle", "cPickle", "pickle"), 169 | MovedModule("queue", "Queue"), 170 | MovedModule("reprlib", "repr"), 171 | MovedModule("socketserver", "SocketServer"), 172 | MovedModule("_thread", "thread", "_thread"), 173 | MovedModule("tkinter", "Tkinter"), 174 | MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), 175 | MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), 176 | MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), 177 | MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), 178 | MovedModule("tkinter_tix", "Tix", "tkinter.tix"), 179 | MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), 180 | MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), 181 | MovedModule("tkinter_colorchooser", "tkColorChooser", 182 | "tkinter.colorchooser"), 183 | MovedModule("tkinter_commondialog", "tkCommonDialog", 184 | "tkinter.commondialog"), 185 | MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), 186 | MovedModule("tkinter_font", "tkFont", "tkinter.font"), 187 | MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), 188 | MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", 189 | "tkinter.simpledialog"), 190 | MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), 191 | MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), 192 | MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), 193 | MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), 194 | MovedModule("winreg", "_winreg"), 195 | ] 196 | for attr in _moved_attributes: 197 | setattr(_MovedItems, attr.name, attr) 198 | del attr 199 | 200 | moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") 201 | 202 | 203 | 204 | class Module_six_moves_urllib_parse(types.ModuleType): 205 | """Lazy loading of moved objects in six.moves.urllib_parse""" 206 | 207 | 208 | _urllib_parse_moved_attributes = [ 209 | MovedAttribute("ParseResult", "urlparse", "urllib.parse"), 210 | MovedAttribute("parse_qs", "urlparse", "urllib.parse"), 211 | MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), 212 | MovedAttribute("urldefrag", "urlparse", "urllib.parse"), 213 | MovedAttribute("urljoin", "urlparse", "urllib.parse"), 214 | MovedAttribute("urlparse", "urlparse", "urllib.parse"), 215 | MovedAttribute("urlsplit", "urlparse", "urllib.parse"), 216 | MovedAttribute("urlunparse", "urlparse", "urllib.parse"), 217 | MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), 218 | MovedAttribute("quote", "urllib", "urllib.parse"), 219 | MovedAttribute("quote_plus", "urllib", "urllib.parse"), 220 | MovedAttribute("unquote", "urllib", "urllib.parse"), 221 | MovedAttribute("unquote_plus", "urllib", "urllib.parse"), 222 | MovedAttribute("urlencode", "urllib", "urllib.parse"), 223 | ] 224 | for attr in _urllib_parse_moved_attributes: 225 | setattr(Module_six_moves_urllib_parse, attr.name, attr) 226 | del attr 227 | 228 | sys.modules[__name__ + ".moves.urllib_parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") 229 | sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib.parse") 230 | 231 | 232 | class Module_six_moves_urllib_error(types.ModuleType): 233 | """Lazy loading of moved objects in six.moves.urllib_error""" 234 | 235 | 236 | _urllib_error_moved_attributes = [ 237 | MovedAttribute("URLError", "urllib2", "urllib.error"), 238 | MovedAttribute("HTTPError", "urllib2", "urllib.error"), 239 | MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), 240 | ] 241 | for attr in _urllib_error_moved_attributes: 242 | setattr(Module_six_moves_urllib_error, attr.name, attr) 243 | del attr 244 | 245 | sys.modules[__name__ + ".moves.urllib_error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib_error") 246 | sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") 247 | 248 | 249 | class Module_six_moves_urllib_request(types.ModuleType): 250 | """Lazy loading of moved objects in six.moves.urllib_request""" 251 | 252 | 253 | _urllib_request_moved_attributes = [ 254 | MovedAttribute("urlopen", "urllib2", "urllib.request"), 255 | MovedAttribute("install_opener", "urllib2", "urllib.request"), 256 | MovedAttribute("build_opener", "urllib2", "urllib.request"), 257 | MovedAttribute("pathname2url", "urllib", "urllib.request"), 258 | MovedAttribute("url2pathname", "urllib", "urllib.request"), 259 | MovedAttribute("getproxies", "urllib", "urllib.request"), 260 | MovedAttribute("Request", "urllib2", "urllib.request"), 261 | MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), 262 | MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), 263 | MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), 264 | MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), 265 | MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), 266 | MovedAttribute("BaseHandler", "urllib2", "urllib.request"), 267 | MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), 268 | MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), 269 | MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), 270 | MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), 271 | MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), 272 | MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), 273 | MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), 274 | MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), 275 | MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), 276 | MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), 277 | MovedAttribute("FileHandler", "urllib2", "urllib.request"), 278 | MovedAttribute("FTPHandler", "urllib2", "urllib.request"), 279 | MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), 280 | MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), 281 | MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), 282 | MovedAttribute("urlretrieve", "urllib", "urllib.request"), 283 | MovedAttribute("urlcleanup", "urllib", "urllib.request"), 284 | MovedAttribute("URLopener", "urllib", "urllib.request"), 285 | MovedAttribute("FancyURLopener", "urllib", "urllib.request"), 286 | ] 287 | for attr in _urllib_request_moved_attributes: 288 | setattr(Module_six_moves_urllib_request, attr.name, attr) 289 | del attr 290 | 291 | sys.modules[__name__ + ".moves.urllib_request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib_request") 292 | sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") 293 | 294 | 295 | class Module_six_moves_urllib_response(types.ModuleType): 296 | """Lazy loading of moved objects in six.moves.urllib_response""" 297 | 298 | 299 | _urllib_response_moved_attributes = [ 300 | MovedAttribute("addbase", "urllib", "urllib.response"), 301 | MovedAttribute("addclosehook", "urllib", "urllib.response"), 302 | MovedAttribute("addinfo", "urllib", "urllib.response"), 303 | MovedAttribute("addinfourl", "urllib", "urllib.response"), 304 | ] 305 | for attr in _urllib_response_moved_attributes: 306 | setattr(Module_six_moves_urllib_response, attr.name, attr) 307 | del attr 308 | 309 | sys.modules[__name__ + ".moves.urllib_response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib_response") 310 | sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") 311 | 312 | 313 | class Module_six_moves_urllib_robotparser(types.ModuleType): 314 | """Lazy loading of moved objects in six.moves.urllib_robotparser""" 315 | 316 | 317 | _urllib_robotparser_moved_attributes = [ 318 | MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), 319 | ] 320 | for attr in _urllib_robotparser_moved_attributes: 321 | setattr(Module_six_moves_urllib_robotparser, attr.name, attr) 322 | del attr 323 | 324 | sys.modules[__name__ + ".moves.urllib_robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib_robotparser") 325 | sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") 326 | 327 | 328 | class Module_six_moves_urllib(types.ModuleType): 329 | """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" 330 | parse = sys.modules[__name__ + ".moves.urllib_parse"] 331 | error = sys.modules[__name__ + ".moves.urllib_error"] 332 | request = sys.modules[__name__ + ".moves.urllib_request"] 333 | response = sys.modules[__name__ + ".moves.urllib_response"] 334 | robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] 335 | 336 | 337 | sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") 338 | 339 | 340 | def add_move(move): 341 | """Add an item to six.moves.""" 342 | setattr(_MovedItems, move.name, move) 343 | 344 | 345 | def remove_move(name): 346 | """Remove item from six.moves.""" 347 | try: 348 | delattr(_MovedItems, name) 349 | except AttributeError: 350 | try: 351 | del moves.__dict__[name] 352 | except KeyError: 353 | raise AttributeError("no such move, %r" % (name,)) 354 | 355 | 356 | if PY3: 357 | _meth_func = "__func__" 358 | _meth_self = "__self__" 359 | 360 | _func_closure = "__closure__" 361 | _func_code = "__code__" 362 | _func_defaults = "__defaults__" 363 | _func_globals = "__globals__" 364 | 365 | _iterkeys = "keys" 366 | _itervalues = "values" 367 | _iteritems = "items" 368 | _iterlists = "lists" 369 | else: 370 | _meth_func = "im_func" 371 | _meth_self = "im_self" 372 | 373 | _func_closure = "func_closure" 374 | _func_code = "func_code" 375 | _func_defaults = "func_defaults" 376 | _func_globals = "func_globals" 377 | 378 | _iterkeys = "iterkeys" 379 | _itervalues = "itervalues" 380 | _iteritems = "iteritems" 381 | _iterlists = "iterlists" 382 | 383 | 384 | try: 385 | advance_iterator = next 386 | except NameError: 387 | def advance_iterator(it): 388 | return it.next() 389 | next = advance_iterator 390 | 391 | 392 | try: 393 | callable = callable 394 | except NameError: 395 | def callable(obj): 396 | return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) 397 | 398 | 399 | if PY3: 400 | def get_unbound_function(unbound): 401 | return unbound 402 | 403 | create_bound_method = types.MethodType 404 | 405 | Iterator = object 406 | else: 407 | def get_unbound_function(unbound): 408 | return unbound.im_func 409 | 410 | def create_bound_method(func, obj): 411 | return types.MethodType(func, obj, obj.__class__) 412 | 413 | class Iterator(object): 414 | 415 | def next(self): 416 | return type(self).__next__(self) 417 | 418 | callable = callable 419 | _add_doc(get_unbound_function, 420 | """Get the function out of a possibly unbound function""") 421 | 422 | 423 | get_method_function = operator.attrgetter(_meth_func) 424 | get_method_self = operator.attrgetter(_meth_self) 425 | get_function_closure = operator.attrgetter(_func_closure) 426 | get_function_code = operator.attrgetter(_func_code) 427 | get_function_defaults = operator.attrgetter(_func_defaults) 428 | get_function_globals = operator.attrgetter(_func_globals) 429 | 430 | 431 | def iterkeys(d, **kw): 432 | """Return an iterator over the keys of a dictionary.""" 433 | return iter(getattr(d, _iterkeys)(**kw)) 434 | 435 | def itervalues(d, **kw): 436 | """Return an iterator over the values of a dictionary.""" 437 | return iter(getattr(d, _itervalues)(**kw)) 438 | 439 | def iteritems(d, **kw): 440 | """Return an iterator over the (key, value) pairs of a dictionary.""" 441 | return iter(getattr(d, _iteritems)(**kw)) 442 | 443 | def iterlists(d, **kw): 444 | """Return an iterator over the (key, [values]) pairs of a dictionary.""" 445 | return iter(getattr(d, _iterlists)(**kw)) 446 | 447 | 448 | if PY3: 449 | def b(s): 450 | return s.encode("latin-1") 451 | def u(s): 452 | return s 453 | unichr = chr 454 | if sys.version_info[1] <= 1: 455 | def int2byte(i): 456 | return bytes((i,)) 457 | else: 458 | # This is about 2x faster than the implementation above on 3.2+ 459 | int2byte = operator.methodcaller("to_bytes", 1, "big") 460 | byte2int = operator.itemgetter(0) 461 | indexbytes = operator.getitem 462 | iterbytes = iter 463 | import io 464 | StringIO = io.StringIO 465 | BytesIO = io.BytesIO 466 | else: 467 | def b(s): 468 | return s 469 | def u(s): 470 | return unicode(s, "unicode_escape") 471 | unichr = unichr 472 | int2byte = chr 473 | def byte2int(bs): 474 | return ord(bs[0]) 475 | def indexbytes(buf, i): 476 | return ord(buf[i]) 477 | def iterbytes(buf): 478 | return (ord(byte) for byte in buf) 479 | import StringIO 480 | StringIO = BytesIO = StringIO.StringIO 481 | _add_doc(b, """Byte literal""") 482 | _add_doc(u, """Text literal""") 483 | 484 | 485 | if PY3: 486 | exec_ = getattr(moves.builtins, "exec") 487 | 488 | 489 | def reraise(tp, value, tb=None): 490 | if value.__traceback__ is not tb: 491 | raise value.with_traceback(tb) 492 | raise value 493 | 494 | else: 495 | def exec_(_code_, _globs_=None, _locs_=None): 496 | """Execute code in a namespace.""" 497 | if _globs_ is None: 498 | frame = sys._getframe(1) 499 | _globs_ = frame.f_globals 500 | if _locs_ is None: 501 | _locs_ = frame.f_locals 502 | del frame 503 | elif _locs_ is None: 504 | _locs_ = _globs_ 505 | exec("""exec _code_ in _globs_, _locs_""") 506 | 507 | 508 | exec_("""def reraise(tp, value, tb=None): 509 | raise tp, value, tb 510 | """) 511 | 512 | 513 | print_ = getattr(moves.builtins, "print", None) 514 | if print_ is None: 515 | def print_(*args, **kwargs): 516 | """The new-style print function for Python 2.4 and 2.5.""" 517 | fp = kwargs.pop("file", sys.stdout) 518 | if fp is None: 519 | return 520 | def write(data): 521 | if not isinstance(data, basestring): 522 | data = str(data) 523 | # If the file has an encoding, encode unicode with it. 524 | if (isinstance(fp, file) and 525 | isinstance(data, unicode) and 526 | fp.encoding is not None): 527 | errors = getattr(fp, "errors", None) 528 | if errors is None: 529 | errors = "strict" 530 | data = data.encode(fp.encoding, errors) 531 | fp.write(data) 532 | want_unicode = False 533 | sep = kwargs.pop("sep", None) 534 | if sep is not None: 535 | if isinstance(sep, unicode): 536 | want_unicode = True 537 | elif not isinstance(sep, str): 538 | raise TypeError("sep must be None or a string") 539 | end = kwargs.pop("end", None) 540 | if end is not None: 541 | if isinstance(end, unicode): 542 | want_unicode = True 543 | elif not isinstance(end, str): 544 | raise TypeError("end must be None or a string") 545 | if kwargs: 546 | raise TypeError("invalid keyword arguments to print()") 547 | if not want_unicode: 548 | for arg in args: 549 | if isinstance(arg, unicode): 550 | want_unicode = True 551 | break 552 | if want_unicode: 553 | newline = unicode("\n") 554 | space = unicode(" ") 555 | else: 556 | newline = "\n" 557 | space = " " 558 | if sep is None: 559 | sep = space 560 | if end is None: 561 | end = newline 562 | for i, arg in enumerate(args): 563 | if i: 564 | write(sep) 565 | write(arg) 566 | write(end) 567 | 568 | _add_doc(reraise, """Reraise an exception.""") 569 | 570 | 571 | def with_metaclass(meta, *bases): 572 | """Create a base class with a metaclass.""" 573 | return meta("NewBase", bases, {}) 574 | 575 | def add_metaclass(metaclass): 576 | """Class decorator for creating a class with a metaclass.""" 577 | def wrapper(cls): 578 | orig_vars = cls.__dict__.copy() 579 | orig_vars.pop('__dict__', None) 580 | orig_vars.pop('__weakref__', None) 581 | for slots_var in orig_vars.get('__slots__', ()): 582 | orig_vars.pop(slots_var) 583 | return metaclass(cls.__name__, cls.__bases__, orig_vars) 584 | return wrapper --------------------------------------------------------------------------------