Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

626
Views
¿Cómo llamar a una función asíncrona contenida en una clase?

Según esta respuesta , quiero crear un cliente websoket asíncrono en una clase que se importaría desde otro archivo:

 #!/usr/bin/env python3 import sys, json import asyncio from websockets import connect class EchoWebsocket: def __await__(self): # see: https://stackoverflow.com/a/33420721/1113207 return self._async_init().__await__() async def _async_init(self): self._conn = connect('wss://ws.binaryws.com/websockets/v3') self.websocket = await self._conn.__aenter__() return self async def close(self): await self._conn.__aexit__(*sys.exc_info()) async def send(self, message): await self.websocket.send(message) async def receive(self): return await self.websocket.recv() class mtest: async def start(self): try: self.wws = await EchoWebsocket() finally: await self.wws.close() async def get_ticks(self): await self.wws.send(json.dumps({'ticks_history': 'R_50', 'end': 'latest', 'count': 1})) return await self.wws.receive() if __name__ == '__main__': a = mtest() loop = asyncio.get_event_loop() loop.run_until_complete(a.start())

Y lo importo en main.py , donde tengo lo siguiente:

 from testws import * a = mtest() print (a.get_ticks()) print ("this will be printed after the ticks")

Pero me recupera el siguiente error:

 root@ubupc1:/home/dinocob# python3 test.py <coroutine object hello.get_ticks at 0x7f13190a9200> test.py:42: RuntimeWarning: coroutine 'mtest.get_ticks' was never awaited print (a.get_ticks()) this will be printed after the ticks

¿Qué está pasando aquí? ¿Por qué no puedo acceder a mtest.get_ticks si tiene la palabra async al comienzo de def ?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Finalmente pude encontrar la manera correcta de hacerlo (gracias especiales a @dirn )

 #!/usr/bin/env python3 import sys, json import asyncio from websockets import connect class EchoWebsocket: async def __aenter__(self): self._conn = connect('wss://ws.binaryws.com/websockets/v3') self.websocket = await self._conn.__aenter__() return self async def __aexit__(self, *args, **kwargs): await self._conn.__aexit__(*args, **kwargs) async def send(self, message): await self.websocket.send(message) async def receive(self): return await self.websocket.recv() class mtest: def __init__(self): self.wws = EchoWebsocket() self.loop = asyncio.get_event_loop() def get_ticks(self): return self.loop.run_until_complete(self.__async__get_ticks()) async def __async__get_ticks(self): async with self.wws as echo: await echo.send(json.dumps({'ticks_history': 'R_50', 'end': 'latest', 'count': 1})) return await echo.receive()

Y esto en main.py:

 from testws import * a = mtest() foo = a.get_ticks() print (foo) print ("async works like a charm!") foo = a.get_ticks() print (foo)

Esta es la salida:

 root@ubupc1:/home/dinocob# python3 test.py {"count": 1, "end": "latest", "ticks_history": "R_50"} async works like a charm! {"count": 1, "end": "latest", "ticks_history": "R_50"}

¡Cualquier consejo para mejorarlo es bienvenido! ;)

over 4 years ago · Santiago Trujillo Report

0

Tu pregunta y respuesta son geniales! ¡Me ayudaron mucho!

Según su código, pude crear la siguiente clase, que se ajusta mejor a mi necesidad:

 import asyncio from websockets import connect class TestClient: def __init__(self, URL): self.URL = URL self.conn = None self.loop = asyncio.get_event_loop() async def send(self, message): if self.conn == None: self.conn = await connect(self.URL) await self.conn.send(message) async def receive(self): return await self.conn.recv() def ping(self): return self.loop.run_until_complete(self._ping()) async def _ping(self): await self.send("Hello World") return await self.receive() test = TestClient("wss://echo.websocket.org") print(test.ping())
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!