2

python-running-autobahnpython-asyncio-websocket-server-in-a-separate-subproce

can-an-asyncio-event-loop-run-in-the-background-without-suspending-the-python-in

Was trying to solve my issue with this two links above but i have not.

I have the following error : RuntimeError: There is no current event loop in thread 'Thread-1'.

Here the code sample (python 3):

from autobahn.asyncio.wamp import ApplicationSession
from autobahn.asyncio.wamp import ApplicationRunner
from asyncio import coroutine
import time
import threading


class PoloniexWebsocket(ApplicationSession):

    def onConnect(self):
        self.join(self.config.realm)

    @coroutine
    def onJoin(self, details):

        def on_ticker(*args):
            print(args)

        try:
            yield from self.subscribe(on_ticker, 'ticker')

        except Exception as e:
            print("Could not subscribe to topic:", e)


def poloniex_worker():
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)


def other_worker():
    while True:
        print('Thank you')
        time.sleep(2)


if __name__ == "__main__":
    polo_worker = threading.Thread(None, poloniex_worker, None, (), {})
    thank_worker = threading.Thread(None, other_worker, None, (), {})

    polo_worker.start()
    thank_worker.start()

    polo_worker.join()
    thank_worker.join()

So, my final goal is to have 2 threads launched at the start. Only one need to use ApplicationSession and ApplicationRunner. Thank you.

Community
  • 1
  • 1
Apex
  • 393
  • 1
  • 6
  • 17

1 Answers1

0

A separate thread must have it's own event loop. So if poloniex_worker needs to listen to a websocket, it needs its own event loop:

def poloniex_worker():
    asyncio.set_event_loop(asyncio.new_event_loop())
    runner = ApplicationRunner("wss://api.poloniex.com:443", "realm1")
    runner.run(PoloniexWebsocket)

But if you're on a Unix machine, you will face another error if you try to do this. Autobahn asyncio uses Unix signals, but those Unix signals only work in the main thread. You can simply turn off Unix signals if you don't plan on using them. To do that, you have to go to the file where ApplicationRunner is defined. That is wamp.py in python3.5 > site-packages > autobahn > asyncio on my machine. You can comment out the signal handling section of the code like so:

# try:
#     loop.add_signal_handler(signal.SIGTERM, loop.stop)
# except NotImplementedError:
#     # signals are not available on Windows
#     pass

All this is a lot of work. If you don't absolutely need to run your ApplicationSession in a separate thread from the main thread, it's better to just run the ApplicationSession in the main thread.