Json rpc server python

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Damn simple, framework-agnostic JSON-RPC v2.0 server for Python

License

marcinn/json-rpc-server

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Читайте также:  Php операторы языка все

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

JSON-RPC Server for Python

This is a core implementation of JSON-RPC v2.0 server for Python.

pip install damn-simple-jsonrpc-server 

Calculator service example

Let’s make calculator service which supports add and subtract operations.

import jsonrpcserver as rpc calculator = rpc.Service() @calculator.method def add(x, y): return x+y @calculator.method('subtract') def sub(x, y): return x-y 

Well. it’s done. But where it is accessible? Nowhere! You can access it directly by calculator variable, but this is nonsense. This is an API for HTTP adapters, but not for humans.

Exposing JSON-RPC service via HTTP

Simplest way to expose calculator service is to use well-known HTTP framework. It may be a Django, for example:

from django.conf.urls import patterns, include, url from .calculator_service import calculator def calculator_service_view(request): return calculator.handle_request_body(request.body) urlpatterns = patterns('', url(r'^$', calculator_service_view, name='calculator'), )

But there is a simpler way! 🙂

If you need quickly expose your service using Django, just use damn simple JSON-RPC Django adaptor, which contains ready to use adaptor:

from django.conf.urls import patterns, include, url from calculator_service import calculator urlpatterns = patterns('', url(r'^$', 'jsonrpcdjango.serve', kwargs='service': calculator>, name='calculator'), )

That’s all. Nothing more, nothing less!

JSON-RPC Service class has very simple API based on str/unicode or request-like object. You may use one of the following methods available in Service class:

The handle_request_body method expects that input string will be a representation of a JSON-RPC Request object.

The handle_http_request method expects that request-like object will be passed as an argument. In that case request-like object must contain body attribute with string representation of JSON-RPC request.

Return value of handle_request_body and handle_http_request is always a str/unicode with a JSON-RPC Response object representation (success and error responses are returned same way, as described in http://www.jsonrpc.org/specification, but will contain result and error keys respectively).

Authentication, CSRF, other stuff.

Authentication and CSRF are HTTP-related topics. You may implement them in adaptors or just use tools from your favourite HTTP framework. For Django framework you may simply decorate whole service:

import jsonrpcdjango as rpc [. ] urlpatterns = patterns('', url(r'^$', login_required(rpc.serve), kwargs='service': calculator>, name='calculator'),

To enable or disable CSRF just use specific adaptor:

  • jsonrpcdjango.serve for CSRF-less handler
  • jsonrpcdjango.csrf_serve for CSRF-protected handler
  • or use disrectly Django’s decorators csrf_exempt , csrf_protect or enable CsrfViewMiddleware (read https://docs.djangoproject.com/en/dev/ref/csrf/ for details)

Currently there is no possibility to decorate specific methods of the service with jsonrpcdjango adaptor.

If you want add authorization to your method you should use similar solution as for authentication. For Django framework you may simply decorate whole service:

import jsonrpcdjango as rpc [. ] urlpatterns = patterns('', url(r'^$', permission_required('can_use_rpc')(rpc.serve), kwargs='service': calculator>, name='calculator'),

Currently there is no possibility to decorate specific methods of the service with jsonrpcdjango adaptor.

Accessing original HTTP request inside service methods

Sometimes you may need access to specific request data added somewhere in middleware stack. In that case you can register JSON-RPC method with additional argument takes_http_request=True . Original request object will be passed as first argument.

If you’re using Django as an HTTP framework and jsonrpcdjango adaptor, you can provide access to Django’s HttpRequest object inside service method without any hacks. Just declare takes_http_request=True at registering time. This will make your service dependend on Django, but will add more flexibility.

calculator = rpc.Service() [. ] @calculator.method(takes_http_request=True) def beast_add(request, x, y): if request.user.is_superuser: return x+y else: return 666

JSON-RPC is a protocor similar to XML-RPC, but simpler and very lightweight. There is no necessary to generate nor parse XML documents by using heavy librariers.

For more information please read JSON-RPC v2.0 specification: http://www.jsonrpc.org/specification

About

Damn simple, framework-agnostic JSON-RPC v2.0 server for Python

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A Python 2 and 3 asynchronous JSON RPC server

License

palantir/python-jsonrpc-server

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.rst

A Python 2.7 and 3.4+ server implementation of the JSON RPC 2.0 protocol. This library has been pulled out of the Python Language Server project.

Asynchronous request handling is supported using Python 3’s concurrent.futures module and the Python 2 concurrent.futures backport.

pip install -U python-jsonrpc-server

The examples directory contains two examples of running language servers over websockets. examples/langserver.py shows how to run a language server in-memory. examples/langserver_ext.py shows how to run a subprocess language server, in this case the Python Language Server.

Start by installing tornado and python-language-server

pip install python-language-server[all] tornado

Then running python examples/langserver.py or python examples/langserver_ext.py will host a websocket on ws://localhost:3000/python .

To setup a client, you can use the examples from Monaco Language Client.

This project is made available under the MIT License.

About

A Python 2 and 3 asynchronous JSON RPC server

Источник

jsonrpcserver Guide¶

This library allows you to act on remote procedure calls.

Methods¶

First build a list of methods that can be called remotely.

Use the methods.add decorator to register a method to the list:

from jsonrpcserver import methods @methods.add def ping(): return 'pong' 

Add as many methods as needed, then serve the methods:

>>> methods.serve_forever() * Listening on port 5000 

The built-in serve_forever() method is a cheap-and-nasty way of taking requests; ultimately you should use a more sophisticated server library (see examples in various frameworks).

For those, there’s a dispatch() method.

Dispatch¶

The dispatch function processes a JSON-RPC request and calls the appropriate method:

>>> response = methods.dispatch(») —>

The return value is a Response object.

Use str() to get a JSON-encoded string:

There’s also an HTTP status code if needed:

Context¶

If you need to pass some extra data to the methods, such as configuration settings, or the request object from the server framework, there’s a context param:

methods.dispatch(request, context='feature_enabled': True>) 

The methods should receive this value (it must be named context ):

@methods.add def ping(context): . 

Configuration¶

The following other options can be passed to dispatch

convert_camel_case

Attempts to clean up requests before processing, by changing the method and parameter names to snake case. Default is False.

If True, more information is included in error responses, such as an exception message. Default is False.

notification_errors

Notifications are not responded to in almost all cases, however if you prefer, notifications can receive error responses. Default is False.

schema_validation

Allows you to disable the validation of requests against the JSON-RPC schema. Default is True.

Validation¶

Methods can take arguments, positional or named (but not both, this is a limitation of JSON-RPC).

If an argument is unsatisfactory, raise InvalidParams :

from jsonrpcserver.exceptions import InvalidParams @methods.add def get_customer(**kwargs): if 'name' not in kwargs: raise InvalidParams('Name is required') 

The dispatcher will catch the exception and give the appropriate response:

>>> methods.dispatch('jsonrpc': '2.0', 'method': 'get', 'params': <>, 'id': 1>) , 'id': 1> 

To include the “Name is required” message in the response, pass debug=True to dispatch.

Async¶

Asyncio is supported Python 3.5+, allowing requests to be dispatched to coroutines.

Import methods from jsonrpcserver.aio :

from jsonrpcserver.aio import methods @methods.add async def ping(): return await some_long_running_task() 
response = await methods.dispatch(request) 

Disable logging¶

To disable the log entries:

import logging logging.getLogger("jsonrpcserver.dispatcher.request").setLevel(logging.WARNING) logging.getLogger("jsonrpcserver.dispatcher.response").setLevel(logging.WARNING) 

Exceptions¶

See the list of exceptions raised by jsonrpcserver here.

Источник

Quickstart¶

Package is transport agnostic, integration depends on you framework. As an example we have server with Werkzeug and client with requests.

from werkzeug.wrappers import Request, Response from werkzeug.serving import run_simple from jsonrpc import JSONRPCResponseManager, dispatcher @dispatcher.add_method def foobar(**kwargs): return kwargs["foo"] + kwargs["bar"] @Request.application def application(request): # Dispatcher is dictionary : callable> dispatcher["echo"] = lambda s: s dispatcher["add"] = lambda a, b: a + b response = JSONRPCResponseManager.handle( request.data, dispatcher) return Response(response.json, mimetype='application/json') if __name__ == '__main__': run_simple('localhost', 4000, application) 
import requests import json def main(): url = "http://localhost:4000/jsonrpc" headers = 'content-type': 'application/json'> # Example echo method payload =  "method": "echo", "params": ["echome!"], "jsonrpc": "2.0", "id": 0, > response = requests.post( url, data=json.dumps(payload), headers=headers).json() assert response["result"] == "echome!" assert response["jsonrpc"] assert response["id"] == 0 if __name__ == "__main__": main() 

Package ensures that request and response messages have correct format. Besides that it provides jsonrpc.manager.JSONRPCResponseManager which handles server common cases, such as incorrect message format or invalid method parameters. Futher topics describe how to add methods to manager, how to handle custom exceptions and optional Django integration.

© Copyright 2013-2015, Kirill Pavlov. Revision f1b4e5e9 .

Versions latest stable Downloads pdf htmlzip epub On Read the Docs Project Home Builds Free document hosting provided by Read the Docs.

Источник

Оцените статью