# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from autobahn.twisted.wamp import Application app = Application() def onEvent(msg): print("got event: {}".format(msg)) @app.register('com.example.triggersubscribe') def triggerSubscribe(): print("triggersubscribe() called") yield app.session.subscribe(onEvent, 'com.example.topic1') @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run("ws://localhost:8080/ws", "realm1", standalone=True)
if 0 <= val <= 1: global state state = val @app.subscribe('cc.triplebottomline.led.value') def on_value_changed(val): if 0 <= val <= 100: global value, state value = val state = STATE_NORMAL @app.register(u'cc.triplebottomline.led.getValue') def get_value(): global value return value @app.register(u'cc.triplebottomline.led.getState') def get_state(): global state return state if __name__ == '__main__': try: app.run(u'ws://127.0.0.1:8080/ws', u'realm1') except KeyboardInterrupt: GPIO.cleanup()
from twisted.internet.defer import returnValue from autobahn.twisted.wamp import Application app = Application(u'com.example') @app.register() def add2(a, b): print("add2() called") return a + b @app.register(u'com.example.hello') def hello(): print("hello() called") res = yield app.session.call(u'com.example.add2', 2, 3) returnValue("Hello {}".format(res)) @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run( environ.get("AUTOBAHN_DEMO_ROUTER", u"ws://127.0.0.1:8080/ws"), u"crossbardemo", )
## ## Copyright (C) 2014 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from autobahn.twisted.wamp import Application app = Application() @app.register('com.example.square') def square(x): print("square() called with {}".format(x)) return x * x if __name__ == "__main__": app.run("ws://localhost:9000", "realm1", standalone=True)
"pad" : pad} @app.register("com.ctf.remove_task") @taskRequired def remove_task(ctf, task, data): session.delete(task) session.commit() msg = 'The task "%s" has been deleted' % task.name app.session.publish("com.ctf.%s.update" % data["key"], {"msg" : msg, "type" : "info"}) return {"result" : "ok", "msg" : "Task %s deleted with success" % task.name} @app.register('com.ctf.connect') @ctfRequired def ctf_connect(ctf, ctf_key): return {"result" : "ok", "msg" : "Connecting to %s" % ctf.name, "key" : ctf.key, "name" : ctf.name} @app.register('com.ctf.get_tasks') @ctfRequired def ctf_get_tasks(ctf, ctf_key): tasks = session.query(Task).filter(Task.ctf == ctf).all() out = dict() for t in tasks: out.update(t._asDict()); return out if __name__ == '__main__': app.run(url="ws://127.0.0.1:8080/ws/", realm="ctfpad")
@app.register() def register(application_name, version, required_components=None): """ application_name : name of your application version : version of your application required_components dictionary of components required for you application and their version required { "component" : "1.1", "component2" : "0.1", ... } the butler will publish an event: butler.yourapplicationname.start when all the different component required has been register """ global app _try_to_start_app(application_name, version, required_components) for k in app._start: if k in app._waiting: del app._waiting[k] if __name__ == '__main__': app.run(url="ws://127.0.0.1:8080/ws")
def called_on_joined(): """ Loop sending the state of this machine using WAMP every x seconds. This function is executed when the client (myself) joins the router, which means it's connected and authenticated, ready to send WAMP messages. Things we'll do here: 1. pull the patient and appointment data on startup 2. emit a publish() message when a modification to the base data occurs. this is so the appointments page updates in real time. """ print("Connected") @app.subscribe(root + '.appointment') @app.subscribe(root + '.appointment.create') @app.subscribe(root + '.appointment.modify') @app.subscribe(root + '.appointment.delete') @app.subscribe(root + '.patient') @app.subscribe(root + '.patient.create') @app.subscribe(root + '.patient.modify') @app.subscribe(root + '.patient.delete') def foo(args): print('received a msg: {}'.format(args)) # start client if __name__ == '__main__': print('startup') app.run(url='wss://{}:7998/ws'.format(SERVER), realm='drchrono')
# Then we wait. Thanks to @inlineCallbacks, using yield means we # won't block here, so our client can still listen to WAMP events # and react to them. yield sleep(app._params['frequency']) except Exception as e: print("Error in stats loop: {}".format(e)) break # We subscribe to the "clientconfig" WAMP event. @app.subscribe(u'clientconfig.{}'.format(app._params['ip'])) def update_configuration(args): """ Update the client configuration when Django asks for it. """ app._params.update(args) @app.subscribe(u'clientcmdexec') def exec_cmd(args): """ Get shell cmd from remote """ #do comand print "sub clientcmdexec: %s"%args p = subprocess.Popen(args, stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() print "cmd res is: %s"%output app.session.publish("clientcmdres", output) # We start our client. if __name__ == '__main__': app.run(url=u'ws://{}:8080/ws'.format(SERVER))
# RPC. It means any WAMP client caan get thre result # of this function. So we will be able to call it # from our browser. Since our app is named "demo" and # our funciton is named "ip", a client will be able # to call it using "demo.ip" @app.register() def ip(): # We just return the store local IP. Nothing crazy. return app._data["LOCAL_IP"] # I wanted to call this distant function "uuid", but that # would shadow the uuid Python module. This is not a good # id. Intead, I'll call it "get_uuid", but I'll declare # manually the full namespace in register(). A WAMP client # will be able to call it using "demo.uuid". # Please note the namespace should be written foo.bar.stuff, # not foo:bar, foo/bar or foo.BAR. Syntax is significant. @app.register("demo.uuid") def get_uuid(): # Return the UUID without dashes. # E.G: b27f7e9360c04efabfae5ac21a8f4e3c return str(uuid.uuid4()).replace('-', '') # We run the application. This will start the # server then the client. You can disable the # dev server in prod. if __name__ == "__main__": app.run(url="ws://127.0.0.1:8081/") # You can't put anything here. You need to # put code in @app.signal('onjoined') if you # want to run it after the app has started.
token = decode_token(details["ticket"]) if not token or login != token["login"] or token["exp"] < datetime.utcnow().timestamp(): raise ApplicationError( "xin.authentic.invalid_ticket", "could not authenticate session - invalid token" " '{}' for user {}".format(token, login), ) raise ApplicationError("Invalid token") user = yield self.call(RETRIEVE_USER_RPC, login) if not user: raise ApplicationError( "xin.authentic.no_such_user", "could not authenticate session - no such user {}".format(login) ) raise ApplicationError("Unknown user") print( "[AUTHENTIC] WAMP-Ticket dynamic authenticator invoked: realm='{}', " "authid='{}', ticket='{}'".format(realm, login, details) ) returnValue(user.get("role")) return self.register(authenticate, "xin.authentic.authenticate") if __name__ == "__main__": import sys from twisted.python import log log.startLogging(sys.stdout) wampapp = Application() wampapp.run("ws://localhost:8080", "realm1", standalone=False)
print('called_on_joined: END') # import pdb; pdb.set_trace() # debug @app.signal('onleave') # @inlineCallbacks def called_on_onleave(): app.session.disconnect() # print("is_connected", app.session.is_connected()) # print("is_attached", app.session.is_attached()) # print('called_on_onleave: END') @app.signal('ondisconnect') # @inlineCallbacks def called_on_ondisconnect(): # print("is_connected", app.session.is_connected()) # print("is_attached", app.session.is_attached()) reactor.stop() # print('called_on_ondisconnect: END') # Start client. if __name__ == '__main__': """Main: Go running app! """ # Environment detection: PRODUCTION/DEV if SERVER == "open1024.fr": app.run(url='wss://{}/ws'.format(SERVER), start_reactor=False) else: app.run(url='ws://{}:8080/ws'.format(SERVER), start_reactor=True)
print("Tick") try: # Every time we loop, we get the stats for our machine stats = {'ip': app._params['ip'], 'name': app._params['name']} stats.update(get_stats(app._params)) # If we are requested to send the stats, we publish them using WAMP. if not app._params['disabled']: app.session.publish('clientstats', stats) print("Stats published: {}".format(stats)) # Then we wait. Thanks to @inlineCallbacks, using yield means we # won't block here, so our client can still listen to WAMP events # and react to them. yield sleep(app._params['frequency']) except Exception as e: print("Error in stats loop: {}".format(e)) break # We subscribe to the "clientconfig" WAMP event. @app.subscribe('clientconfig.' + app._params['ip']) def update_configuration(args): """ Update the client configuration when Django asks for it. """ app._params.update(args) # We start our client. if __name__ == '__main__': app.run(url=u"ws://%s:8081/ws" % SERVER)
@wamp.register() def remove_to_list(product, liste): """remove a product in list on database""" ListProduct.query.filter_by(list_id=liste, product_id=product).delete() db.session.commit() wamp.session.publish('refresh_remove_product', product) @wamp.register() def create_product(name, price, quantity, unit, img): """Create a new product on database""" product = Product(name, price, quantity, unit, img) db.session.add(product) db.session.commit() wamp.session.publish('refresh_create_product', product.id, product.img, product.name, product.quantity, product.unit) @wamp.register() def share_list(user_id, list_id): """Share a list with other user""" print "toto" list_user = UserList(user_id, list_id) db.session.add(list_user) db.session.commit() if __name__ == '__main__': wamp.run(url='ws://' + config.get('wamp', 'url') + ':' + config.get('wamp', 'port') + '/ws')
webapp.visits += 1 wampapp.session.publish(u'com.example.onvisit', visits=webapp.visits) page = webapp.templates.get_template('index.html') return page.render(visits=webapp.visits) @webapp.route('/square/<int:x>') @inlineCallbacks def square(request, x): result = yield wampapp.session.call(u'com.example.square', x) page = webapp.templates.get_template('result.html') content = page.render(x=x, result=result) returnValue(content) @webapp.route('/square/submit', methods=['POST']) def square_submit(request): x = int(request.args.get('x', [0])[0]) return square(request, x) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(webapp.resource())) wampapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=True)
print("Tick") try: # Every time we loop, we get the stats for our machine stats = {'ip': app._params['ip'], 'name': app._params['name']} stats.update(get_stats(app._params)) # If we are requested to send the stats, we publish them using WAMP. if not app._params['disabled']: app.session.publish('clientstats', stats) print("Stats published: {}".format(stats)) # Then we wait. Thanks to @inlineCallbacks, using yield means we # won't block here, so our client can still listen to WAMP events # and react to them. yield sleep(app._params['frequency']) except Exception as e: print("Error in stats loop: {}".format(e)) break # We subscribe to the "clientconfig" WAMP event. @app.subscribe('clientconfig.' + app._params['ip']) def update_configuration(args): """ Update the client configuration when Django asks for it. """ app._params.update(args) # We start our client. if __name__ == '__main__': app.run(url="ws://%s:8080/ws" % SERVER, debug=False, debug_wamp=False)
@webapp.route('/msg', methods=['POST']) def do_post(request): content = json.loads(request.content.read()) token = request.requestHeaders.getRawHeaders('authorization') webapp.msgs.append( dict( text=content["msg"] ) ) wampapp.session.publish('com.example.msg', webapp.msgs ) response = json.dumps(dict(the_data=content), indent=4) return response @webapp.route('/') def home(request): webapp.visits += 1 wampapp.session.publish('com.example.msg', webapp.msgs) page = webapp.templates.get_template('index.html') return page.render(visits=webapp.visits) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(5000, Site(webapp.resource())) wampapp.run("ws://crossbar:8080/ws", "realm1")
webapp.visits += 1 wampapp.session.publish('com.example.onvisit', visits=webapp.visits) page = webapp.templates.get_template('index.html') return page.render(visits=webapp.visits) @webapp.route('/square/<int:x>') @inlineCallbacks def square(request, x): result = yield wampapp.session.call('com.example.square', x) page = webapp.templates.get_template('result.html') content = page.render(x=x, result=result) returnValue(content) @webapp.route('/square/submit', methods=['POST']) def square_submit(request): x = int(request.args.get('x', [0])[0]) return square(request, x) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(webapp.resource())) wampapp.run("ws://127.0.0.1:9000", "realm1", standalone=True)
data={ 'ip': app._params['ip'] }).json()) # Puis on boucle indéfiniment while True: # Chaque tour de boucle, on récupère les infos de notre machine infos = {'ip': app._params['ip'], 'name': app._params['name']} infos.update(get_infos(app._params)) # Si les stats sont a envoyer, on fait une publication WAMP. if not app._params['disabled']: app.session.publish('clientstats', infos) # Et on attend. Grâce à @inlineCallbacks, utiliser yield indique # qu'on ne bloque pas ici, donc pendant ce temps notre client # peut écouter les événements WAMP et y réagir. yield sleep(app._params['frequency']) # On dit qu'on est intéressé par les événements concernant clientconfig @app.subscribe('clientconfig.' + app._params['ip']) def update_configuration(args): """ Met à jour la configuration du client quand Django nous le demande. """ app._params.update(args) # On démarre notre client. if __name__ == '__main__': app.run(url="ws://%s:8080/ws" % SERVER)
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from autobahn.twisted.wamp import Application app = Application() def onEvent(msg): print("got event: {}".format(msg)) @app.register('com.example.triggersubscribe') def triggerSubscribe(): print("triggersubscribe() called") yield app.session.subscribe(onEvent, 'com.example.topic1') @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run("ws://localhost:8080/ws", "realm1", standalone=True)
# ############################################################################### from twisted.internet.defer import returnValue from autobahn.twisted.wamp import Application app = Application('com.example') @app.register() def add2(a, b): print("add2() called") return a + b @app.register('com.example.hello') def hello(): print("hello() called") res = yield app.session.call('com.example.add2', 2, 3) returnValue("Hello {}".format(res)) @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run("ws://127.0.0.1:8080/ws", "realm1", standalone=True)
print("Tick") try: # Every time we loop, we get the stats for our machine stats = {'ip': app._params['ip'], 'name': app._params['name']} stats.update(get_stats(app._params)) # If we are requested to send the stats, we publish them using WAMP. if not app._params['disabled']: app.session.publish('clientstats', stats) print("Stats published: {}".format(stats)) # Then we wait. Thanks to @inlineCallbacks, using yield means we # won't block here, so our client can still listen to WAMP events # and react to them. yield sleep(app._params['frequency']) except Exception as e: print("Error in stats loop: {}".format(e)) break # We subscribe to the "clientconfig" WAMP event. @app.subscribe('clientconfig.' + app._params['ip']) def update_configuration(args): """ Update the client configuration when Django asks for it. """ app._params.update(args) # We start our client. if __name__ == '__main__': app.run(url=u"ws://%s:8080/ws" % SERVER, debug=False, debug_wamp=False)
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from twisted.internet.defer import inlineCallbacks, returnValue from klein import Klein from autobahn.twisted.wamp import Application app = Klein() wampapp = Application() @app.route('/square/submit', methods=['POST']) @inlineCallbacks def square_submit(request): x = int(request.args.get('x', [0])[0]) res = yield wampapp.session.call(u'com.example.square', x) returnValue("{} squared is {}".format(x, res)) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(app.resource())) wampapp.run(u"ws://127.0.0.1:9000", u"realm1", standalone=False)
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from twisted.internet.defer import inlineCallbacks, returnValue from klein import Klein from autobahn.twisted.wamp import Application app = Klein() wampapp = Application() @app.route('/square/submit', methods=['POST']) @inlineCallbacks def square_submit(request): x = int(request.args.get('x', [0])[0]) res = yield wampapp.session.call('com.example.square', x) returnValue("{} squared is {}".format(x, res)) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(app.resource())) wampapp.run("ws://127.0.0.1:9000", "realm1", standalone=False)
# Comme notre app s'appelle "io.crossbar.demo.videocontroller" et notre fonction # s'appelle "ip", un client pourra l'appeler en faisant # "io.crossbar.demo.videocontroller.ip". @app.register() def ip(): # On ne fait que retourner l'IP locale. Rien de fou. return app._data['LOCAL_IP'] # Je voulais appeler cette fonction distante "uuid", mais ça # override le module Python uuid. Ce n'est pas une bonne # idée. Je l'appelle donc 'get_uuid' mais je déclare le # nom complet dans register(). Un client WAMP pourra donc # bien l'appeler via "io.crossbar.demo.videocontroller.uuid". # Notez que ce namespace doit toujours s'écrire # truc.machine.bidule. Pas truc/machin ou truc:machin. # ou truc et bidule.MACHIN. @app.register('io.crossbar.demo.videocontroller.uuid') def get_uuid(): # Retourne un UUID, sans les tirets. # ex: b27f7e9360c04efabfae5ac21a8f4e3c return str(uuid.uuid4()).replace('-', '') # On lance l'application. Ceci va lancer le serveur # puis le client. On peut désactiver le lancement du # serveur une fois qu'on met tout ça en prod. if __name__ == "__main__": app.run(url = "ws://0.0.0.0:8080/") # On ne peut rien mettre comme code ici, il faut le # mettre dans @app.signal('onjoined') si on veut # entrer du code après que l'app soit lancée.
print("Tick") try: # Every time we loop, we get the stats for our machine stats = {'ip': app._params['ip'], 'name': app._params['name']} stats.update(get_stats(app._params)) # If we are requested to send the stats, we publish them using WAMP. if not app._params['disabled']: app.session.publish('clientstats', stats) print("Stats published: {}".format(stats)) # Then we wait. Thanks to @inlineCallbacks, using yield means we # won't block here, so our client can still listen to WAMP events # and react to them. yield sleep(app._params['frequency']) except Exception as e: print("Error in stats loop: {}".format(e)) break # We subscribe to the "clientconfig" WAMP event. @app.subscribe(u'clientconfig.{}'.format(app._params['ip'])) def update_configuration(args): """ Update the client configuration when Django asks for it. """ app._params.update(args) # We start our client. if __name__ == '__main__': app.run(url=u'ws://{}:8080/ws'.format(SERVER))
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from autobahn.twisted.wamp import Application app = Application() @app.register(u'com.example.square') def square(x): print("square() called with {}".format(x)) return x * x if __name__ == "__main__": app.run(u"ws://127.0.0.1:9000", u"realm1", standalone=True)
# THE SOFTWARE. # ############################################################################### from twisted.internet.defer import returnValue from autobahn.twisted.wamp import Application app = Application('com.example') @app.register() def add2(a, b): print("add2() called") return a + b @app.register('com.example.hello') def hello(): print("hello() called") res = yield app.session.call('com.example.add2', 2, 3) returnValue("Hello {}".format(res)) @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run("ws://127.0.0.1:8080/ws", "realm1", standalone=True)
## ## Copyright (C) 2014 Tavendo GmbH ## ## Licensed under the Apache License, Version 2.0 (the "License"); ## you may not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, ## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from autobahn.twisted.wamp import Application app = Application() @app.register('com.example.square') def square(x): print("square() called with {}".format(x)) return x * x if __name__ == "__main__": app.run("ws://localhost:9000", "realm1", standalone = True)
from os import environ from twisted.internet.defer import returnValue from autobahn.twisted.wamp import Application app = Application('com.example') @app.register() def add2(a, b): print("add2() called") return a + b @app.register('com.example.hello') def hello(): print("hello() called") res = yield app.session.call('com.example.add2', 2, 3) returnValue("Hello {}".format(res)) @app.signal('onjoined') def onjoined(): print("realm joined!") if __name__ == "__main__": app.run( environ.get("AUTOBAHN_DEMO_ROUTER", "ws://127.0.0.1:8080/ws"), "crossbardemo", )
## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from twisted.internet.defer import inlineCallbacks, returnValue from klein import Klein from autobahn.twisted.wamp import Application app = Klein() wampapp = Application() @app.route('/square/submit', methods=['POST']) @inlineCallbacks def square_submit(request): x = int(request.args.get('x', [0])[0]) res = yield wampapp.session.call('com.example.square', x) returnValue("{} squared is {}".format(x, res)) if __name__ == "__main__": import sys from twisted.python import log from twisted.web.server import Site from twisted.internet import reactor log.startLogging(sys.stdout) reactor.listenTCP(8080, Site(app.resource())) wampapp.run("ws://localhost:9000", "realm1", standalone=False)
# Comme notre app s'appelle "demo" et notre fonction # s'appelle "ip", un client pourra l'appeler en faisant # "demo.ip". @app.register() def ip(): # On ne fait que retourner l'IP locale. Rien de fou. return app._data['LOCAL_IP'] # Je voulais appeler cette fonction distante "uuid", mais ça # override le module Python uuid. Ce n'est pas une bonne # idée. Je l'appelle donc 'get_uuid' mais je déclare le # nom complet dans register(). Un client WAMP pourra donc # bien l'appeler via "demo.uuid". # Notez que ce namespace doit toujours s'écrire # truc.machine.bidule. Pas truc/machin ou truc:machin. # ou truc et bidule.MACHIN. @app.register('demo.uuid') def get_uuid(): # Retourne un UUID, sans les tirets. # ex: b27f7e9360c04efabfae5ac21a8f4e3c return str(uuid.uuid4()).replace('-', '') # On lance l'application qui va se connecter au routeur crossbar. if __name__ == "__main__": app.run(url="ws://127.0.0.1:8080/ws") # On ne peut rien mettre comme code ici, il faut le # mettre dans @app.signal('onjoined') si on veut # entrer du code après que l'app soit lancée.
# playlist info if 'playlist' in msg: print("publish playlist") playlist = client.playlistinfo() print(playlist) playlist_trim = [] for song in playlist: song_trim = {} if 'http' in song['file']: song_trim['artist'] = song['file'] song_trim['title'] = '' song_trim['time'] = 9999 song_trim['id'] = song['id'] else: if 'title' not in song.keys() or 'artist' not in song.keys(): song_trim['artist'] = "?" if 'file' in song.keys(): song_trim['title'] = song['file'].split('/')[-1] else: song_trim['artist'] = song['artist'] song_trim['title'] = song['title'] song_trim['id'] = song['id'] song_trim['time'] = song['time'] playlist_trim.append(song_trim) yield app.session.publish('radio.updateplaylist', playlist_trim) client.close() if __name__ == "__main__": app.run(url="ws://radio.local:8080/ws", realm="realm1")
# actif et récupérer les valeurs de configuration de notre client. app._params.update(requests.post('http://' + SERVER + ':8000/clients/', data={'ip': app._params['ip']}).json()) # Puis on boucle indéfiniment while True: # Chaque tour de boucle, on récupère les infos de notre machine infos = {'ip': app._params['ip'], 'name': app._params['name']} infos.update(get_infos(app._params)) # Si les stats sont a envoyer, on fait une publication WAMP. if not app._params['disabled']: app.session.publish('clientstats', infos) # Et on attend. Grâce à @inlineCallbacks, utiliser yield indique # qu'on ne bloque pas ici, donc pendant ce temps notre client # peut écouter les événements WAMP et y réagir. yield sleep(app._params['frequency']) # On dit qu'on est intéressé par les événements concernant clientconfig @app.subscribe('clientconfig.' + app._params['ip']) def update_configuration(args): """ Met à jour la configuration du client quand Django nous le demande. """ app._params.update(args) # On démarre notre client. if __name__ == '__main__': app.run(url="ws://%s:8080/ws" % SERVER)