1. 安装依赖
# 服务端 pip install jsonrpcserver # 客户端 pip install jsonrpcclient
2. 服务端
2.1 基本使用案例
from jsonrpcserver import Success, method, serve @method def ping(): return Success("pong") if __name__ == "__main__": serve()
2.2 基于aiohttp案例
from aiohttp import web from jsonrpcserver import method, Result, Success, async_dispatch @method async def ping() -> Result: return Success("pong") async def handle(request): return web.Response( text=await async_dispatch(await request.text()), content_type="application/json" ) app = web.Application() app.router.add_post("/", handle) if __name__ == "__main__": web.run_app(app, port=5000)
2.3 基于django案例
from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from jsonrpcserver import method, Result, Success, dispatch @method def ping() -> Result: return Success("pong") @csrf_exempt def jsonrpc(request): return HttpResponse( dispatch(request.body.decode()), content_type="application/json" )
2.4 基于fastApi
from fastapi import FastAPI, Request, Response from jsonrpcserver import Result, Success, dispatch, method import uvicorn app = FastAPI() @method def ping() -> Result: return Success("pong") @app.post("/") async def index(request: Request): return Response(dispatch(await request.body())) if __name__ == "__main__": uvicorn.run(app, port=5000)
2.5 基于flask
from flask import Flask, Response, request from jsonrpcserver import method, Result, Success, dispatch app = Flask(__name__) @method def ping() -> Result: return Success("pong") @app.route("/", methods=["POST"]) def index(): print(request.get_data().decode()) return Response( dispatch(request.get_data().decode()), content_type="application/json" ) if __name__ == "__main__": app.run()
2.6 基于http
from http.server import BaseHTTPRequestHandler, HTTPServer from jsonrpcserver import method, Result, Success, dispatch @method def ping() -> Result: return Success("pong") class TestHttpServer(BaseHTTPRequestHandler): def do_POST(self): # Process request request = self.rfile.read(int(self.headers["Content-Length"])).decode() response = dispatch(request) # Return response self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(response.encode()) if __name__ == "__main__": HTTPServer(("localhost", 5000), TestHttpServer).serve_forever()
2.7 基于sanic
from sanic import Sanic from sanic.request import Request from sanic.response import json from jsonrpcserver import Result, Success, dispatch_to_serializable, method app = Sanic("JSON-RPC app") @method def ping() -> Result: return Success("pong") @app.route("/", methods=["POST"]) async def test(request: Request): return json(dispatch_to_serializable(request.body)) if __name__ == "__main__": app.run(port=5000)
2.8 基于socket
from flask import Flask from flask_socketio import SocketIO, send from jsonrpcserver import method, Result, Success, dispatch app = Flask(__name__) socketio = SocketIO(app) @method def ping() -> Result: return Success("pong") @socketio.on("message") def handle_message(request): if response := dispatch(request): send(response, json=True) if __name__ == "__main__": socketio.run(app, port=5000)
2.9 基于tornado
from jsonrpcserver import method, Result, Success, async_dispatch from tornado import ioloop, web @method async def ping() -> Result: return Success("pong") class MainHandler(web.RequestHandler): async def post(self) -> None: request = self.request.body.decode() if response := await async_dispatch(request): self.write(response) app = web.Application([(r"/", MainHandler)]) if __name__ == "__main__": app.listen(5000) ioloop.IOLoop.current().start()
2.10 基于websocket
import asyncio from jsonrpcserver import method, Success, Result, async_dispatch import websockets @method async def ping() -> Result: return Success("pong") async def main(websocket, path): if response := await async_dispatch(await websocket.recv()): await websocket.send(response) start_server = websockets.serve(main, "localhost", 5000) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
3. 客户端
from jsonrpcclient import request request("ping", params={"key": "val"})