1
0
bthlabs-jsonrpc/packages/bthlabs-jsonrpc-aiohttp/example/example.py
Tomek Wójcik c75ea4ea9d Initial public releases
* `bthlabs-jsonrpc-aiohttp` v1.0.0
* `bthlabs-jsonrpc-core` v1.0.0
* `bthlabs-jsonrpc-django` v1.0.0
2022-06-04 10:41:53 +02:00

64 lines
1.5 KiB
Python

# -*- coding: utf-8 -*-
# django-jsonrpc-aiohttp | (c) 2022-present Tomek Wójcik | MIT License
import asyncio
import logging
import os
import sys
from aiohttp import web
from bthlabs_jsonrpc_core import register_method
from bthlabs_jsonrpc_aiohttp import JSONRPCView
logger = logging.getLogger('bthlabs_jsonrpc_aiohttp_example')
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'%(asctime)s %(name)s: %(levelname)s: %(message)s',
)
handler.setFormatter(formatter)
logger.addHandler(handler)
app_logger = logging.getLogger('bthlabs_jsonrpc_aiohttp_example.app')
jsonrpc_logger = logger = logging.getLogger('bthlabs_jsonrpc')
jsonrpc_logger.setLevel(logging.DEBUG)
jsonrpc_logger.addHandler(handler)
async def app_on_startup(app):
logger.info('BTHLabs JSONRPC aiohttp integration example')
logger.debug('My PID = {pid}'.format(pid=os.getpid()))
@register_method('hello')
async def hello(request):
return 'Hello, World!'
@register_method('async_test')
async def async_test(request, delay):
await asyncio.sleep(delay)
return 'It works!'
@register_method('hello', namespace='example')
async def hello_example(request):
return 'Hello, Example!'
def create_app(loop=None):
app = web.Application(logger=app_logger, loop=loop)
app.on_startup.append(app_on_startup)
app.add_routes([
web.post('/rpc', JSONRPCView()),
web.post('/example/rpc', JSONRPCView(namespace='example')),
])
return app
app = create_app()