Search code examples
restwamptornadowampserverautobahn

Pass data to 'onJoin' of a WAMP server from external file


I have a WAMP server on AWS with the following code

from os import environ
from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import LoopingCall
from autobahn import wamp
from autobahn.twisted.wamp import ApplicationSession, ApplicationRunner, ApplicationSessionFactory

class wampserver(ApplicationSession):

    @inlineCallbacks
    def onJoin(self, details):
        yield self.register(self)
        print("Server started")

        def heartbeat():
            self.publish(u'com.myapp.wampserver.heartbeat', 'heartbeat')
        LoopingCall(heartbeat).start(2)

        def contcmd():
            print 'container'
            #Get the value from Tornado server
            return self.publish(u'com.myapp.wampserver.contcmd', #pass the data (dict format))

if __name__ == '__main__':
    runner = ApplicationRunner(
        environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://localhost:8096/ws"),
        u"realm1",
    )
    runner.run(wampserver)

and a Twisted server with the following code,

import tornado.escape
import tornado.ioloop
import tornado.web
import json

def handleCmd(entries):
   #pass this Dict (entries) to WAMP server
   for entry in entries:
        print entries[entry]

class handleReq(tornado.web.RequestHandler):
    def get(self):
        self.write('Edge Computing Project')

    def post(self, **kwargs):
        print "received"

        # parse the received data
        print self.request.body
        data = json.loads(self.request.body)
        print data

        for entry in data:
            if entry == 'command':
                print 'command'
                handleCmd(data)
        self.write(data)


application = tornado.web.Application([
    (r"/handle_request", handleReq)
])

if __name__ == "__main__":
    application.listen(8090)
    tornado.ioloop.IOLoop.instance().start()

The twisted server will receive data from an external source in JSON format. This is parsed in 'POST'. This data has to be further transferred to WAMP server (inside onJoin). Both the WAMP and Tornado servers are running on AWS. The WAMP server then publishes this data to the subscribed users. I am not able to pass the data into onJoin. Is there anyway? Or should i use some kind of bridge to access REST API in WAMP? I mainly want to send the 'data' (in dict format) received through REST API, to all the subscribed users through WAMP.

Thank you for the help!


Solution

  • I was able to resolve this issue by using ApplicationSessionFactory(). This will use the existing ApplicationSession and can be called from outside the ApplicationSession function.