|
1 | 1 | # Examples |
2 | 2 |
|
3 | | -## aiohttp |
4 | | - |
5 | | -```python |
6 | | -from aiohttp import web |
7 | | - |
8 | | -from jsonrpcserver import Result, Success, async_dispatch, method |
9 | | - |
10 | | - |
11 | | -@method |
12 | | -async def ping() -> Result: |
13 | | - """JSON-RPC method""" |
14 | | - return Success("pong") |
15 | | - |
16 | | - |
17 | | -async def handle(request: web.Request) -> web.Response: |
18 | | - """Handle aiohttp request""" |
19 | | - return web.Response( |
20 | | - text=await async_dispatch(await request.text()), content_type="application/json" |
21 | | - ) |
22 | | - |
23 | | - |
24 | | -app = web.Application() |
25 | | -app.router.add_post("/", handle) |
26 | | - |
27 | | -if __name__ == "__main__": |
28 | | - web.run_app(app, port=5000) |
29 | | -``` |
30 | | - |
31 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/aiohttp). |
32 | | - |
33 | | -## Django |
34 | | - |
35 | | -Create a `views.py`: |
36 | | - |
37 | | -```python |
38 | | -from django.http import HttpRequest, HttpResponse # type: ignore |
39 | | -from django.views.decorators.csrf import csrf_exempt # type: ignore |
40 | | - |
41 | | -from jsonrpcserver import Result, Success, dispatch, method |
42 | | - |
43 | | - |
44 | | -@method |
45 | | -def ping() -> Result: |
46 | | - """JSON-RPC method""" |
47 | | - return Success("pong") |
48 | | - |
49 | | - |
50 | | -@csrf_exempt # type: ignore |
51 | | -def jsonrpc(request: HttpRequest) -> HttpResponse: |
52 | | - """Handle Django request""" |
53 | | - return HttpResponse( |
54 | | - dispatch(request.body.decode()), content_type="application/json" |
55 | | - ) |
56 | | -``` |
57 | | - |
58 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/django). |
59 | | - |
60 | | -## FastAPI |
61 | | - |
62 | | -```python |
63 | | -import uvicorn |
64 | | -from fastapi import FastAPI, Request, Response |
65 | | - |
66 | | -from jsonrpcserver import Result, Success, dispatch, method |
67 | | - |
68 | | -app = FastAPI() |
69 | | - |
70 | | - |
71 | | -@method |
72 | | -def ping() -> Result: |
73 | | - """JSON-RPC method""" |
74 | | - return Success("pong") |
75 | | - |
76 | | - |
77 | | -@app.post("/") |
78 | | -async def index(request: Request) -> Response: |
79 | | - """Handle FastAPI request""" |
80 | | - return Response(dispatch(await request.body())) |
81 | | - |
82 | | - |
83 | | -if __name__ == "__main__": |
84 | | - uvicorn.run(app, port=5000) |
85 | | -``` |
86 | | - |
87 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/fastapi). |
88 | | - |
89 | | -## Flask |
90 | | - |
91 | | -```python |
92 | | -from flask import Flask, Response, request |
93 | | - |
94 | | -from jsonrpcserver import Result, Success, dispatch, method |
95 | | - |
96 | | -app = Flask(__name__) |
97 | | - |
98 | | - |
99 | | -@method |
100 | | -def ping() -> Result: |
101 | | - """JSON-RPC method""" |
102 | | - return Success("pong") |
103 | | - |
104 | | - |
105 | | -@app.route("/", methods=["POST"]) |
106 | | -def index() -> Response: |
107 | | - """Handle Flask request""" |
108 | | - return Response( |
109 | | - dispatch(request.get_data().decode()), content_type="application/json" |
110 | | - ) |
111 | | - |
112 | | - |
113 | | -if __name__ == "__main__": |
114 | | - app.run() |
115 | | -``` |
116 | | - |
117 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/flask). |
118 | | - |
119 | | -## http.server |
120 | | - |
121 | | -Using Python's built-in |
122 | | -[http.server](https://docs.python.org/3/library/http.server.html) module. |
123 | | - |
124 | | -```python |
125 | | -from http.server import BaseHTTPRequestHandler, HTTPServer |
126 | | - |
127 | | -from jsonrpcserver import Result, Success, dispatch, method |
128 | | - |
129 | | - |
130 | | -@method |
131 | | -def ping() -> Result: |
132 | | - """JSON-RPC method""" |
133 | | - return Success("pong") |
134 | | - |
135 | | - |
136 | | -class TestHttpServer(BaseHTTPRequestHandler): |
137 | | - """HTTPServer request handler""" |
138 | | - |
139 | | - def do_POST(self) -> None: # pylint: disable=invalid-name |
140 | | - """POST handler""" |
141 | | - # Process request |
142 | | - request = self.rfile.read(int(self.headers["Content-Length"])).decode() |
143 | | - response = dispatch(request) |
144 | | - # Return response |
145 | | - self.send_response(200) |
146 | | - self.send_header("Content-type", "application/json") |
147 | | - self.end_headers() |
148 | | - self.wfile.write(response.encode()) |
149 | | - |
150 | | - |
151 | | -if __name__ == "__main__": |
152 | | - HTTPServer(("localhost", 5000), TestHttpServer).serve_forever() |
153 | | -``` |
154 | | - |
155 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/httpserver). |
156 | | - |
157 | | -## jsonrpcserver |
158 | | - |
159 | | -Using jsonrpcserver's built-in `serve` method. |
160 | | - |
161 | | -```python |
162 | | -from jsonrpcserver import Result, Success, method, serve |
163 | | - |
164 | | - |
165 | | -@method |
166 | | -def ping() -> Result: |
167 | | - """JSON-RPC method""" |
168 | | - return Success("pong") |
169 | | - |
170 | | - |
171 | | -if __name__ == "__main__": |
172 | | - serve() |
173 | | -``` |
174 | | - |
175 | | -## Sanic |
176 | | - |
177 | | -```python |
178 | | -from sanic import Sanic |
179 | | -from sanic.request import Request |
180 | | -from sanic.response import HTTPResponse, json |
181 | | - |
182 | | -from jsonrpcserver import Result, Success, dispatch_to_serializable, method |
183 | | - |
184 | | -app = Sanic("JSON-RPC app") |
185 | | - |
186 | | - |
187 | | -@method |
188 | | -def ping() -> Result: |
189 | | - """JSON-RPC method""" |
190 | | - return Success("pong") |
191 | | - |
192 | | - |
193 | | -@app.route("/", methods=["POST"]) |
194 | | -async def test(request: Request) -> HTTPResponse: |
195 | | - """Handle Sanic request""" |
196 | | - return json(dispatch_to_serializable(request.body)) |
197 | | - |
198 | | - |
199 | | -if __name__ == "__main__": |
200 | | - app.run(port=5000) |
201 | | -``` |
202 | | - |
203 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/sanic). |
204 | | - |
205 | | -## Socket.IO |
206 | | - |
207 | | -```python |
208 | | -from flask import Flask, Request |
209 | | -from flask_socketio import SocketIO, send # type: ignore |
210 | | - |
211 | | -from jsonrpcserver import Result, Success, dispatch, method |
212 | | - |
213 | | -app = Flask(__name__) |
214 | | -socketio = SocketIO(app) |
215 | | - |
216 | | - |
217 | | -@method |
218 | | -def ping() -> Result: |
219 | | - """JSON-RPC method""" |
220 | | - return Success("pong") |
221 | | - |
222 | | - |
223 | | -@socketio.on("message") # type: ignore |
224 | | -def handle_message(request: Request) -> None: |
225 | | - """Handle SocketIO request""" |
226 | | - if response := dispatch(request): |
227 | | - send(response, json=True) |
228 | | - |
229 | | - |
230 | | -if __name__ == "__main__": |
231 | | - socketio.run(app, port=5000) |
232 | | -``` |
233 | | - |
234 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/flask-socketio). |
235 | | - |
236 | | -## Tornado |
237 | | - |
238 | | -```python |
239 | | -from typing import Awaitable, Optional |
240 | | - |
241 | | -from tornado import ioloop, web |
242 | | - |
243 | | -from jsonrpcserver import Result, Success, async_dispatch, method |
244 | | - |
245 | | - |
246 | | -@method |
247 | | -async def ping() -> Result: |
248 | | - """JSON-RPC method""" |
249 | | - return Success("pong") |
250 | | - |
251 | | - |
252 | | -class MainHandler(web.RequestHandler): |
253 | | - """Handle Tornado request""" |
254 | | - |
255 | | - async def post(self) -> None: |
256 | | - """Post""" |
257 | | - request = self.request.body.decode() |
258 | | - response = await async_dispatch(request) |
259 | | - if response: |
260 | | - self.write(response) |
261 | | - |
262 | | - def data_received(self, chunk: bytes) -> Optional[Awaitable[None]]: |
263 | | - pass |
264 | | - |
265 | | - |
266 | | -app = web.Application([(r"/", MainHandler)]) |
267 | | - |
268 | | -if __name__ == "__main__": |
269 | | - app.listen(5000) |
270 | | - ioloop.IOLoop.current().start() |
271 | | -``` |
272 | | - |
273 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/tornado). |
274 | | - |
275 | | -## Websockets |
276 | | - |
277 | | -```python |
278 | | -import asyncio |
279 | | - |
280 | | -from websockets.server import WebSocketServerProtocol, serve |
281 | | - |
282 | | -from jsonrpcserver import Result, Success, async_dispatch, method |
283 | | - |
284 | | - |
285 | | -@method |
286 | | -async def ping() -> Result: |
287 | | - """JSON-RPC method""" |
288 | | - return Success("pong") |
289 | | - |
290 | | - |
291 | | -async def main(websocket: WebSocketServerProtocol, _: str) -> None: |
292 | | - """Handle Websocket message""" |
293 | | - if response := await async_dispatch(await websocket.recv()): |
294 | | - await websocket.send(response) |
295 | | - |
296 | | - |
297 | | -start_server = serve(main, "localhost", 5000) |
298 | | -asyncio.get_event_loop().run_until_complete(start_server) |
299 | | -asyncio.get_event_loop().run_forever() |
300 | | -``` |
301 | | - |
302 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/websockets). |
303 | | - |
304 | | -## Werkzeug |
305 | | - |
306 | | -```python |
307 | | -from werkzeug.serving import run_simple |
308 | | -from werkzeug.wrappers import Request, Response |
309 | | - |
310 | | -from jsonrpcserver import Result, Success, dispatch, method |
311 | | - |
312 | | - |
313 | | -@method |
314 | | -def ping() -> Result: |
315 | | - """JSON-RPC method""" |
316 | | - return Success("pong") |
317 | | - |
318 | | - |
319 | | -@Request.application |
320 | | -def application(request: Request) -> Response: |
321 | | - """Handle Werkzeug request""" |
322 | | - return Response(dispatch(request.data.decode()), 200, mimetype="application/json") |
323 | | - |
324 | | - |
325 | | -if __name__ == "__main__": |
326 | | - run_simple("localhost", 5000, application) |
327 | | -``` |
328 | | - |
329 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/werkzeug). |
330 | | - |
331 | | -## ZeroMQ |
332 | | - |
333 | | -```python |
334 | | -import zmq |
335 | | - |
336 | | -from jsonrpcserver import Result, Success, dispatch, method |
337 | | - |
338 | | -socket = zmq.Context().socket(zmq.REP) |
339 | | - |
340 | | - |
341 | | -@method |
342 | | -def ping() -> Result: |
343 | | - """JSON-RPC method""" |
344 | | - return Success("pong") |
345 | | - |
346 | | - |
347 | | -if __name__ == "__main__": |
348 | | - socket.bind("tcp://*:5000") |
349 | | - while True: |
350 | | - request = socket.recv().decode() |
351 | | - socket.send_string(dispatch(request)) |
352 | | -``` |
353 | | - |
354 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/zeromq). |
355 | | - |
356 | | -## ZeroMQ (async) |
357 | | - |
358 | | -```python |
359 | | -import asyncio |
360 | | - |
361 | | -import aiozmq # type: ignore |
362 | | -import zmq |
363 | | - |
364 | | -from jsonrpcserver import Result, Success, async_dispatch, method |
365 | | - |
366 | | - |
367 | | -@method |
368 | | -async def ping() -> Result: |
369 | | - """JSON-RPC method""" |
370 | | - return Success("pong") |
371 | | - |
372 | | - |
373 | | -async def main() -> None: |
374 | | - """Handle AioZMQ request""" |
375 | | - rep = await aiozmq.create_zmq_stream(zmq.REP, bind="tcp://*:5000") |
376 | | - while True: |
377 | | - request = (await rep.read())[0].decode() |
378 | | - if response := (await async_dispatch(request)).encode(): |
379 | | - rep.write((response,)) |
380 | | - |
381 | | - |
382 | | -if __name__ == "__main__": |
383 | | - asyncio.set_event_loop_policy(aiozmq.ZmqEventLoopPolicy()) |
384 | | - asyncio.get_event_loop().run_until_complete(main()) |
385 | | -``` |
386 | | - |
387 | | -See [blog post](https://explodinglabs.github.io/jsonrpc/zeromq-async). |
| 3 | +Examples have moved to the [Community Wiki](https://github.com/explodinglabs/jsonrpcserver/wiki). |
0 commit comments