# 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() 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!")
## ## 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)
# 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. # ############################################################################### import jinja2 from klein import Klein from twisted.internet.defer import inlineCallbacks, returnValue from autobahn.twisted.wamp import Application # This is our WAMP application ## wampapp = Application('com.example') @wampapp.register() def square(x): print("square() called with {}".format(x)) return x * x # This is our Web application ## webapp = Klein() webapp.visits = 0 webapp.templates = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
## See the License for the specific language governing permissions and ## limitations under the License. ## ############################################################################### from autobahn.twisted.wamp import Application import socket import uuid # Comme pour flask, l'objet app # est ce qui lie tous les éléments # de notre code ensemble. On lui donne # un nom, ici "demo" app = Application('io.crossbar.demo.videocontroller') # Bien que l'app va démarrer un serveur # pour nous, l'app est bien un CLIENT # du serveur WAMP. Le serveur démarré # automatiquement n'est qu'une facilité # pour le dev. En prod on utiliserait # crossbar. # Juste un conteneur pour y mettre notre IP app._data = {} # On déclare que cette fonction sera appelée # quand l'app se sera connectée au serveur WAMP. # Ceci permet de lancer du code juste après # le app.run() que l'on voit en bas du fichier. # '_' est une convention en Python pour dire
from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.sql import and_, or_ from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, sessionmaker from sqlalchemy import create_engine from uuid import uuid4 from hashlib import md5 from functools import wraps import string import pdb VALIDCHARSET = string.letters + string.digits + "-_ " SQLITEFILE = 'sqlite:///ctfmanager.db' PADURI = "http://pad.bi.tk" app = Application('ctfpad') Base = declarative_base() class CTF(Base): __tablename__ = 'ctf' id = Column(Integer, primary_key=True) name = Column(String(250), nullable=False) key = Column(String(250), nullable=False) class Task(Base): __tablename__ = 'tasks' id = Column(Integer, primary_key=True) ctf = relationship(CTF) ctf_id = Column(Integer, ForeignKey('ctf.id')) name = Column(String(250), nullable=False)
from autobahn.twisted.wamp import Application app = Application("butler") app._start = {} app._waiting = {} def _start_app(application_name, version): global app app._start[application_name] = version app.session.publish('butler.' + application_name + '.start') for key in app._waiting: if key not in app._start: application = app._waiting[key] _try_to_start_app( application['name'], application['version'], application['required_components']) def _add_to_waiting_list(application_name, version, required_components): global app if application_name in app._waiting: del app._waiting[application_name] app._waiting[application_name] = { 'name': application_name, 'version': version, 'required_components': required_components} def _try_to_start_app(application_name, version, required_components): global app if not required_components:
from autobahn.twisted.wamp import Application from twisted.internet.defer import inlineCallbacks SERVER = 'drc.blue-labs.org' # note, this prefix specification is actually pointless at the moment root = 'org.blue_labs.drchrono' app = Application(root) @app.signal('onjoined') 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')
channel_id = Column(Integer) user_id = Column(Integer,ForeignKey('users.id')) messages = Column(String) created = Column(String) #user = relationship("User", back_populates="msgs") # ed_user = User(email='fcarrizales@gmail') # session.add(ed_user) # session.commit() # This is our WAMP application ## wampapp = Application('com.example') # This is our Web application ## webapp = Klein() webapp.visits = 0 webapp.msgs = []; webapp.templates = jinja2.Environment(loader=jinja2.FileSystemLoader('templates')) def valid_user(user): messages = [] if not validators.email(user['email']): messages.append('Error email')
# coding: utf-8 from __future__ import unicode_literals from autobahn.twisted.wamp import Application import socket import uuid # Just like for flask, the app object # is what's bind all elements together. # We give it a name, here "demo". app = Application("demo") # While the app is going to start # a server for us, the app is a CLIENT # of the WAMP server. The server is # started automatically as a courtesy # for dev purpose. In production, we # would use crossbar. # Just a container to store the IP app._data = {} # We ask for this function to be called when the # app is connected to the WAMP server. This allow # us to run caode right after the app.run() call # you can see at the bottom of the file. '_' is # a convention in Python meaning "this name has # no importance, it's disposable code that we'll # use only once" @app.signal("onjoined")
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)
from autobahn.twisted.wamp import Application, ApplicationRunner from twisted.internet.defer import inlineCallbacks from twisted.internet import reactor # Environment detection: PRODUCTION/DEV ENV = os.environ.get('ENV') if ENV == 'PRODUCTION': SERVER = 'open1024.fr' else: SERVER = '127.0.0.1' # localhost print('=========================================') print('ENV:', ENV) print('SERVER:', SERVER) print('=========================================') app = Application() # app = ApplicationRunner(url='ws://{}:8080/ws'.format(SERVER), realm='realm1') @app.signal('onjoined') # @inlineCallbacks def called_on_joined(): # ==== Create & Use autobahn 'client_mode' channel # ==== to auto refresh web page on the 1st start app json_data = {'mode': 'CLEAR'} app.session.publish('client_mode', json_data) print('called_on_joined: publish', json_data) app.session.leave() # app.session.disconnect() # print("is_connected", app.session.is_connected()) # print("is_attached", app.session.is_attached())
#! /usr/bin/python # -*- coding: utf-8 -*- """ Wamp router """ from autobahn.twisted.wamp import Application from app import db from app import config from app.models import ListProduct from app.models import Product from app.models import UserList wamp = Application('me.hory') @wamp.signal('onjoined') def _(): """Executed during connection with client""" print 'session attached' @wamp.register() def add_to_list(product, liste): """Add a new product in liste on database""" print 'add to list' result = ListProduct.query.filter_by(list_id=liste, product_id=product).first() number = 1 if result is not None:
# -*- coding: utf-8 -*- from autobahn.twisted.wamp import Application import socket import uuid # Comme pour flask, l'objet app # est ce qui lie tous les éléments # de notre code ensemble. On lui donne # un nom, ici "demo" app = Application('demo') # Bien que l'app va démarrer un serveur # pour nous, l'app est bien un CLIENT # du serveur WAMP. Le serveur démarré # automatiquement n'est qu'une facilité # pour le dev. En prod on utiliserait # crossbar. # Juste un conteneur pour y mettre notre IP app._data = {} # On déclare que cette fonction sera appelée # quand l'app se sera connectée au serveur WAMP. # Ceci permet de lancer du code juste après # le app.run() que l'on voit en bas du fichier. # '_' est une convention en Python pour dire # "ce nom n'a aucune importance, c'est du code # jetable qu'un utilisera une seule fois". @app.signal('onjoined') def _():
## 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 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
# 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. # ############################################################################### import jinja2 from klein import Klein from twisted.internet.defer import inlineCallbacks, returnValue from autobahn.twisted.wamp import Application # This is our WAMP application ## wampapp = Application('com.example') @wampapp.register() def square(x): print("square() called with {}".format(x)) return x * x # This is our Web application ## webapp = Klein() webapp.visits = 0 webapp.templates = jinja2.Environment( loader=jinja2.FileSystemLoader('templates'))
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ############################################################################### from flask import Flask from crochet import setup, run_in_reactor, wait_for # this MUST be called _before_ any Autobahn or Twisted imports! setup() from autobahn.twisted.wamp import Application # noqa # our WAMP app # wapp = Application() # this is a synchronous wrapper around the asynchronous WAMP code # @wait_for(timeout=1) def publish(topic, *args, **kwargs): return wapp.session.publish(topic, *args, **kwargs) # our Flask app # app = Flask(__name__) app._visits = 0
# 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() 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 (filters.get('show_disk', True)): disks = {} for device in psutil.disk_partitions(): usage = psutil.disk_usage(device.mountpoint) disks[device.mountpoint] = '{used}/{total} ({percent}%)'.format( used=to_gib(usage.used), total=to_gib(usage.total), percent=usage.percent) results['disks'] = disks return results # On créé le client WAMP. app = Application('monitoring') # Ceci est l'IP publique de ma machine puisque # ce client doit pouvoir accéder à mon serveur # depuis l'extérieur. SERVER = '172.17.42.1' # D'abord on utilise une astuce pour connaître l'IP publique de cette # machine. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) # On attache un dictionnaire à l'app, ainsi # sa référence sera accessible partout. app._params = {'name': socket.gethostname(), 'ip': s.getsockname()[0]} s.close()
disks = {} for device in psutil.disk_partitions(): # skip mountpoint not actually mounted (like CD drives with no disk on Windows) if device.fstype != "": usage = psutil.disk_usage(device.mountpoint) disks[device.mountpoint] = '{used}/{total} ({percent}%)'.format( used=to_gib(usage.used), total=to_gib(usage.total), percent=usage.percent ) results['disks'] = disks return results # We create the WAMP client. app = Application('monitoring') # This is my machine's public IP since # this client must be able to reach my server # from the outside. You should change this value # to the IP of the machine you put Crossbar.io # and Django. SERVER = '127.0.0.1' # First, we use a trick to know the public IP for this # machine. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) # We attach a dict to the app, so that its # reference is accessible from anywhere. app._params = {'name': socket.gethostname(), 'ip': s.getsockname()[0]}
# # 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 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))
# 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 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
# 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 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
for device in psutil.disk_partitions(): # skip mountpoint not actually mounted (like CD drives with no disk on Windows) if device.fstype != "": usage = psutil.disk_usage(device.mountpoint) disks[ device.mountpoint] = '{used}/{total} ({percent}%)'.format( used=to_gib(usage.used), total=to_gib(usage.total), percent=usage.percent) results['disks'] = disks return results # We create the WAMP client. app = Application('monitoring') # This is my machine's public IP since # this client must be able to reach my server # from the outside. You should change this value # to the IP of the machine you put Crossbar.io # and Django. SERVER = '127.0.0.1' # First, we use a trick to know the public IP for this # machine. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) # We attach a dict to the app, so that its # reference is accessible from anywhere. app._params = {'name': socket.gethostname(), 'ip': s.getsockname()[0]}
# 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 os import environ 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))
# 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 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))
# 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 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 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))
def __init__(self, realm = "logging"): Application.__init__(self) self._realm = realm
# -*- coding: utf-8 -*- from autobahn.twisted.wamp import Application import socket import uuid # Comme pour flask, l'objet app # est ce qui lie tous les éléments # de notre code ensemble. On lui donne # un nom, ici "demo" app = Application('demo') # Bien que l'app va démarrer un serveur # pour nous, l'app est bien un CLIENT # du serveur WAMP. Le serveur démarré # automatiquement n'est qu'une facilité # pour le dev. En prod on utiliserait # crossbar. # Juste un conteneur pour y mettre notre IP app._data = {} # On déclare que cette fonction sera appelée # quand l'app se sera connectée au serveur WAMP. # Ceci permet de lancer du code juste après # le app.run() que l'on voit en bas du fichier. # '_' est une convention en Python pour dire # "ce nom n'a aucune importance, c'est du code # jetable qu'un utilisera une seule fois". @app.signal('onjoined')
GPIO_GROUP1 = 24 GPIO_GROUP2 = 26 GPIO_GROUP3 = 16 GPIO_GROUP4 = 22 GPIO_PWM = 12 PWM_FREQUENCY = 80 STATE_NORMAL = 0 STATE_DEMO = 1 value = 0 state = STATE_DEMO transition = False app = Application(u'cc.triplebottomline') @app.signal('onjoined') def onjoined(*args): print 'realm joined' global state print 'initialize start' # setup hardware pwm using wiringpi print 'hardware pwm setup' wiringpi.wiringPiSetupPhys() wiringpi.pinMode(GPIO_PWM, 2) # 2=hardware pwm wiringpi.pwmWrite(GPIO_PWM, 1024)
# 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. # ############################################################################### import jinja2 from klein import Klein from twisted.internet.defer import inlineCallbacks, returnValue from autobahn.twisted.wamp import Application # This is our WAMP application ## wampapp = Application(u'com.example') @wampapp.register() def square(x): print("square() called with {}".format(x)) return x * x # This is our Web application ## webapp = Klein() webapp.visits = 0 webapp.templates = jinja2.Environment(loader=jinja2.FileSystemLoader('templates'))
def __init__(self, realm="logging"): Application.__init__(self) self._realm = realm
from autobahn.twisted.wamp import Application from mpd import MPDClient from random import choice app = Application() autoaddstate = 1 deja_vu = [] def dir_to_list(dir): client = MPDClient() client.connect("localhost", 6600) client.use_unicode = True lst = client.lsinfo(""+dir) client.close() out = [x["file"] for x in lst if "file" in x.keys()] return out current_list = dir_to_list("Tuatha de Danann/Non-Album") print(current_list) def choose_from_list(lst): usable = [x for x in lst if (x not in deja_vu) and ("wma" not in x)] if len(usable) == 0: if len(deja_vu) == 0: sys.exit(3) else: for i in range(max(3, len(current_list)//20)):
if (filters.get('show_disk', True)): disks = {} for device in psutil.disk_partitions(): usage = psutil.disk_usage(device.mountpoint) disks[device.mountpoint] = '{used}/{total} ({percent}%)'.format( used=to_gib(usage.used), total=to_gib(usage.total), percent=usage.percent ) results['disks'] = disks return results # On créé le client WAMP. app = Application('monitoring') # Ceci est l'IP publique de ma machine puisque # ce client doit pouvoir accéder à mon serveur # depuis l'extérieur. SERVER = '172.17.42.1' # D'abord on utilise une astuce pour connaître l'IP publique de cette # machine. s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) # On attache un dictionnaire à l'app, ainsi # sa référence sera accessible partout. app._params = {'name': socket.gethostname(), 'ip': s.getsockname()[0]} s.close()