python - 将 Autobahn|Python 与 aiohttp 集成

标签 python autobahn aiohttp crossbar wamp-protocol

我正在尝试将 aiohttp 网络服务器集成到 Crossbar+Autobahn 系统架构中。

更详细地说,当aiohttp 服务器收到某个API 调用时,它必须向Crossbar 路由器发布消息。 我看过this example在官方 repo 协议(protocol)上,但我不知道如何将它集成到我的应用程序中。

理想情况下,我希望能够做到这一点

# class SampleTaskController(object):
async def handle_get_request(self, request: web.Request) -> web.Response:
    self.publisher.publish('com.myapp.topic1', 'Hello World!')
    return web.HTTPOk()

其中 selfSampleTaskController(object) 的实例,它定义了网络服务器的所有路由处理程序。

def main(argv):
    cfg_path = "./task_cfg.json"
    if len(argv) > 1:
        cfg_path = argv[0]

    logging.basicConfig(level=logging.DEBUG,
                        format=LOG_FORMAT)

    loop = zmq.asyncio.ZMQEventLoop()
    asyncio.set_event_loop(loop)

    app = web.Application(loop=loop)
    with open(cfg_path, 'r') as f:
        task_cfg = json.load(f)
        task_cfg['__cfg_path'] = cfg_path
        controller = SampleTaskController(task_cfg)
        controller.restore()
        app['controller'] = controller

        controller.setup_routes(app)

        app.on_startup.append(controller.on_startup)
        app.on_cleanup.append(controller.on_cleanup)
        web.run_app(app,
                    host=task_cfg['webserver_address'],
                    port=task_cfg['webserver_port'])

请注意,我使用的是 zmq.asyncio.ZMQEventLoop,因为服务器也在监听 zmq 套接字,该套接字是在 Controller 中配置的。 on_startup 方法。

我还尝试使用 wampy 将消息发布到 Crossbar,而不是使用高速公路,它工作正常,但高速公路订阅者无法正确解析消息。

# autobahn subscriber
class ClientSession(ApplicationSession):
    async def onJoin(self, details):

        self.log.info("Client session joined {details}", details=details)

        self.log.info("Connected:  {details}", details=details)

        self._ident = details.authid
        self._type = u'Python'

        self.log.info("Component ID is  {ident}", ident=self._ident)
        self.log.info("Component type is  {type}", type=self._type)

        # SUBSCRIBE

        def gen_on_something(thing):
            def on_something(counter, id, type):
                print('----------------------------')
                self.log.info("'on_{something}' event, counter value: {message}",something=thing, message=counter)
                self.log.info("from component {id} ({type})", id=id, type=type)
            return on_something

        await self.subscribe(gen_on_something('landscape'), 'landscape')
        await self.subscribe(gen_on_something('nature'), 'nature')

-

# wampy publisher
async def publish():
    router = Crossbar(config_path='./crossbar.json')
    logging.getLogger().debug(router.realm)
    logging.getLogger().debug(router.url)
    logging.getLogger().debug(router.port)

    client = Client(router=router)
    client.start()

    result = client.publish(topic="nature", message=0)
    logging.getLogger().debug(result)

使用此配置,订阅者接收发布的消息,但在解析消息时出现异常。

TypeError: on_something() got an unexpected keyword argument 'message'

最佳答案

最近我尝试同时使用aiohttp 和autobahn。我重新编写了 crossbar 文档中的示例(最初使用 twisted)并获得了以下代码:

import asyncio
import logging

from aiohttp import web
from aiohttp.web_exceptions import HTTPOk, HTTPInternalServerError
from autobahn.asyncio.component import Component

# Setup logging
logger = logging.getLogger(__name__)


class WebApplication(object):
    """
    A simple Web application that publishes an event every time the
    url "/" is visited.
    """

    count = 0

    def __init__(self, app, wamp_comp):
        self._app = app
        self._wamp = wamp_comp
        self._session = None  # "None" while we're disconnected from WAMP router

        # associate ourselves with WAMP session lifecycle
        self._wamp.on('join', self._initialize)
        self._wamp.on('leave', self._uninitialize)

        self._app.router.add_get('/', self._render_slash)

    def _initialize(self, session, details):
        logger.info("Connected to WAMP router (session: %s, details: %s)", session, details)
        self._session = session

    def _uninitialize(self, session, reason):
        logger.warning("Lost WAMP connection (session: %s, reason: %s)", session, reason)
        self._session = None

    async def _render_slash(self, request):
        if self._session is None:
            return HTTPInternalServerError(reason="No WAMP session")
        self.count += 1
        self._session.publish(u"com.myapp.request_served", self.count, count=self.count)
        return HTTPOk(text="Published to 'com.myapp.request_served'")


def main():
    REALM = "crossbardemo"
    BROKER_URI = "ws://wamp_broker:9091/ws"
    BIND_ADDR = "0.0.0.0"
    BIND_PORT = 8080

    logging.basicConfig(
        level='DEBUG',
        format='[%(asctime)s %(levelname)s %(name)s:%(lineno)d]: %(message)s')

    logger.info("Starting aiohttp backend at %s:%s...", BIND_ADDR, BIND_PORT)
    loop = asyncio.get_event_loop()

    component = Component(
        transports=BROKER_URI,
        realm=REALM,
    )
    component.start(loop=loop)

    # When not using run() we also must start logging ourselves.
    import txaio
    txaio.start_logging(level='info')

    app = web.Application(
        loop=loop)

    _ = WebApplication(app, component)

    web.run_app(app, host=BIND_ADDR, port=BIND_PORT)


if __name__ == '__main__':
    main()

关于python - 将 Autobahn|Python 与 aiohttp 集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45188506/

相关文章:

python - 谁在引用 Joe?用于析构函数/清理的 Pythonic 方法?

python - 按字母顺序对数据类型进行排序

python - 为什么这个python autobahn代码需要使用 'yield'关键字?

Python aiohttp(带有asyncio)发送请求非常慢

python - 尝试使用 send_config_set 时无法在 Netmiko 中进入配置模式

python - 为 TCP 服务器寄存器赋值的 pymodbus 语法是什么?

python - Websocket 握手状态 200 异常

javascript - 在 wamp ws 中使用 AutobahnJS 时的连接处理程序

python - Python3.x RuntimeError:事件循环已关闭

python-3.x - 将tornado与aiohttp(或其他基于asyncio的库)一起使用