0

I'm trying to use aiohttp REST interface to dynamically add bots that establish Websocket connection to target server, i.e., when the user wants to create a WS bot, he/she could use curl -X POST <server>/bot to create a new bot and then the bot will connect to a specific target Websocket server. I'm trying to add the newly create WS connection into the main event loop which serves REST interface, but looks like doesn't work. I must miss something but I can't figure it out.

Below is the REST interface implementation:

botCenter = wsBotCenter()

@routes.post('/bot')
async def new_bot(request):
    await botCenter.new_bot()
    return web.Response(text="Ok\n")

app = web.Application()
app.on_startup.append(botCenter.start_loop)
app.add_routes(routes)
web.run_app(app, host='localhost', port=8080)

botCenter is a set contains all bots, it's implementation is like this:

class wsBotCenter(object):
    def __init__(self):
        self.id = 1
        self.botDict = {}
        self.url = "ws://localhost:9001"
        self.app = None

    async def start_loop(self, app):
        self.app = app

    async def new_bot(self):
        bot = wsBot(self.url)
        self.botDict[self.id] = bot
        self.app[f"bot_{self.id}"] = self.app.loop.create_task(bot.start)
        self.id += 1

Bot is implemented like below:

from aiohttp import ClientSession

class wsBot:
    def __init__(self, URL):
        self.url = URL
        self.session = ClientSession()

    async def start(self):
        await self.session.ws_connect(self.url)
        while True:
            msg = await self.session.receive()
            print(f"Rx {msg}")

I assume once I send curl -X POST <server>/bot, then there will be a coroutine created an added into the main event loop, then the coroutine starts establishing WS connection and receive the message.

However, I can not see a new WS connection is created even the new bot instance is created.

Could someone give me some advice? Thank you!

1 Answer 1

0

After replace bot.start with bot.start() then it works.

bot.start() is the coroutine.

Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.