78 lines
2.0 KiB
Python
78 lines
2.0 KiB
Python
# -*- coding: utf-8 -*-
|
|
# bthlabs-jsonrpc-aiohttp | (c) 2022-present Tomek Wójcik | MIT License
|
|
import asyncio
|
|
import datetime
|
|
import logging
|
|
import os
|
|
import sys
|
|
|
|
from aiohttp import web
|
|
from bthlabs_jsonrpc_core import register_method
|
|
from bthlabs_jsonrpc_core.ext.jwt import ALGORITHMS, HMACKey, JWTCodec, KeyPair
|
|
|
|
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)
|
|
|
|
jsonrpc_logger = logging.getLogger('bthlabs_jsonrpc')
|
|
jsonrpc_logger.setLevel(logging.DEBUG)
|
|
jsonrpc_logger.addHandler(handler)
|
|
|
|
app_logger = logging.getLogger('bthlabs_jsonrpc_aiohttp_example.app')
|
|
|
|
|
|
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='jwt')
|
|
async def hello_example(request):
|
|
return 'Hello, Example!'
|
|
|
|
|
|
class JWTRPCView(JSONRPCView):
|
|
async def get_codec(self, request):
|
|
return JWTCodec(
|
|
KeyPair(
|
|
decode_key=HMACKey('thisisntasecrurekeydontuseitpls=', ALGORITHMS.HS256),
|
|
encode_key=HMACKey('thisisntasecrurekeydontuseitpls=', ALGORITHMS.HS256),
|
|
),
|
|
issuer='bthlabs_jsonrpc_aiohttp_example',
|
|
ttl=datetime.timedelta(seconds=3600),
|
|
)
|
|
|
|
|
|
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('/jwt/rpc', JWTRPCView(namespace='jwt')),
|
|
])
|
|
|
|
return app
|
|
|
|
|
|
app = create_app()
|