Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

629
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda