How to send data through a client websocket in a aiohttp request handler

xav19

I'm building a simple HTTP web service, but I want to send information trough a websocket to another server.

For instance when the web service receive a request on /foo, it send on the websocket "request on /foo received".

I'm fairly new to async programming in Python. I choose aiohttp for this, but it's not a hard requirement.

I have some prior experience with websocket and autobahn and I tried at first to mix aiohtpp and autobahn. I even found an example with both but it used wamp and I just want websocket.

Then I tried without autobahn as aiohttp handle websocket.

My last attempt looks like that:

from aiohttp import web, ClientSession, WSMsgType

async def callback(msg):
    print(msg)

async def websocket(session):
    async with session.ws_connect('http://localhost:8000') as ws:
        app['ws'] = ws
        async for msg in ws:
            if msg.type == WSMsgType.TEXT:
                await callback(msg.data)
            elif msg.type == WSMsgType.CLOSED:
                break
            elif msg.type == WSMsgType.ERROR:
                break

async def hello(request):
    app.ws.send_str('{"hello": "world"}')
    return web.Response(text="Hello, world")

async def init(app):
    session = ClientSession()
    app['websocket_task'] = app.loop.create_task(websocket(session))

app = web.Application()
app.add_routes([web.get('/', hello)])
app.on_startup.append(init)
web.run_app(app, port=7000)

When requesting / it cashes with the following exception: AttributeError: 'Application' object has no attribute 'ws'

How can I mix http serving and writing on websocket as a client? Is it even possible ?

xav19

Sometimes a good night of sleep is all you need...

Basically I needed to initialize a resource and use it in the handlers. Exactly like you would do for a database connection.

I used this demo as an example and adapted it to my need. Here is what it looks like:

from aiohttp import web, ClientSession

class Handler:
    def __init__(self, ws):
        self._ws = ws

    async def hello(self):
        await self._ws.send_str('{"hello": "world"}')
        return web.Response(text="Hello, world")

async def init(app):
    session = ClientSession()
    ws = await session.ws_connect('http://localhost:8000')
    h = Handler(ws)
    app.add_routes([web.get('/', h.hello)])

app = web.Application()
app.on_startup.append(init)
web.run_app(app, port=7000)

I hope this can help other asyncio/aiohttp beginners.

Cheers

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to rewrite aiohttp websocket handler to sanic?

How to send an array of objects through a single websocket send request with ratchet?

How to send message to client through websocket using Spring

send aiohttp post request with headers through proxy connection

PHP read data from raw tcp socket and send them through WebSocket Client using 2 React Connector

How to send an erlang message to a websocket handler?

Send data through POST request

aiohttp Websocket client and HTTP server

How to send post form data through a http client?

Not able to send client Request through RSC cli

How can I send data through fetch API by GET request?

How to send an HTTPS request through an On-Prem Data Gateway?

How do I send cookies data through scrapy Request?

How to send image or binary data through HTTP POST request in C

How to deploy aiohttp websocket?

How to send enclose data in DELETE request in Jersey client?

How to send GET request to HTTP Client to retrieve data based on a parameter?

How to Send Data to a handler with AJAX

WebSocket send and receive data asynchronously (using NuGet websocket-client)

Send opencv Mat image through Qt websocket to HTML client

PHP WebSocket – How send message to specified client?

Websocket: How to encode a text to send to a client, in C

Send user credentials in aiohttp request

How to set up logging for aiohttp.client when making request with aiohttp.ClientSession()?

How to create Python secure websocket client request?

how to get parameters from websocket client request

No handler for message type websocket.group_send, how to fix?

How to send json data in request body through GET request to external API in Spring Boot application

How to access other client connections from a Go WebSocket handler?