Tomek Pulkiewicz
Tomek Pulkiewicz

Reputation: 79

Python Websockets - Problem with await in class

Hi I'm writing an simple video chat app server and I run into a problem where I can't await a function send_to_all() in Room class. Im new to asyncio and I don't know how should I've done it.

I've tried using threading and using some sort of asyncio thing that i found online all of that didn't work

class Room:
     def __init__(self,_id,owner):
          self.owner = owner
          self.id = _id
          self.participants = []
          
          print("[DEBUG] New room has been created")
          
     async def send_msg_to_all(self, message):
          print("[DEBUG] Sending message")
          for participant in self.participants:
               await participant.conn.send(message)

After running code above I get RuntimeError

RuntimeWarning: coroutine 'Room.send_msg_to_all' was never awaited
  self.send_msg_to_all(str(serialized_partipants_info))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

Upvotes: 1

Views: 828

Answers (1)

aSaffary
aSaffary

Reputation: 863

according to docs you can't await just any normal functions:

We say that an object is an awaitable object if it can be used in an await expression. There are three main types of awaitable objects: coroutines, Tasks, and Futures

you have to use a library that is created with async capabilities something like asyncore. keep in mind that you can't await an already awaited async call. I didn't use asyncore package myself so you have to read about its usage. but in a general situation you have to define separate async functions and then gather them like this:

async def async_method1(*args):
  #do your thing

async def async_method1(*args):
  #do your thing

async def async_method1(*args):
  #do your thing

async def all_my_calls(*args):
  reslist = await asyncio.gather(
        async_method1(*args),
        async_method2(*args),
        async_method3(*args))
  # do stuff with your reslist


asyncio.run(all_my_calls(*args))

please keep in mind, depending on your logic, you might not need any input *args or output reslist. I just included them in my code so you'll know how to pass arguments and process the results if you need to.

EDIT:

as Tomek Pulkiewicz already mentioned in the comments asyncore is only used for normal sockets. if you want to use async web-sockets use asyncore-wsgi

Upvotes: 1

Related Questions