How to avoid ReactorNotRestartable in Autobahn Python

78 views Asked by At

I have a python based page which recieves data by POST, which is then forwarded to the Crossbar server using Autobahn (Wamp). It works well the first 1-2 times but when it's called again after that it throws ReactorNotRestartable.

Now, I need this to work whichever way possible, either by reusing this "Reactor" based on a conditional check or by stopping it properly after every run. (The first one would be preferable because it might reduce the execution time)

Thanks for your help!

Edit:

This is in a webpage (Django View) so it needs to run as many times as the page is loaded/data is sent to it via POST.

    from twisted.internet import reactor
    from twisted.internet.defer import inlineCallbacks
    from twisted.internet.endpoints import TCP4ClientEndpoint
    from twisted.application.internet import ClientService
    from autobahn.wamp.types import ComponentConfig
    from autobahn.twisted.wamp import ApplicationSession, WampWebSocketClientFactory
    
    class MyAppSession(ApplicationSession):
    
        def __init__(self, config):
            ApplicationSession.__init__(self, config)
    
        def onConnect(self):
            self.join(self.config.realm)
    
        def onChallenge(self, challenge):
            pass
    
        @inlineCallbacks
        def onJoin(self, details):
            yield self.call('receive_data', data=message)
            yield self.leave()
    
        def onLeave(self, details):
            self.disconnect()
    
        def onDisconnect(self):
            reactor.stop()
    
    message = "data from POST[]"

    session = MyAppSession(ComponentConfig('realm_1', {}))

    transport = WampWebSocketClientFactory(session, url='ws://127.0.0.1:8080')
    endpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 8080)
    
    service = ClientService(endpoint, transport)
    service.startService()
    reactor.run()

I figured out a probably hacky-and-not-so-good way by using multiprocessing and putting reactor.stop() inside onJoin() right after the function call. This way I don't have to bother with the "twisted running in the main thread" thing because its process gets killed as soon as my work is done.

Is there a better way?

0

There are 0 answers