示例#1
0
def run_flask():
    root_dir = os.path.join(os.getcwd(), 'web')
    app = Flask(__name__, static_folder=root_dir)
    app.use_reloader = False
    app.debug = False
    app.config["SECRET_KEY"] = "OpenPoGoBot"
    socketio = SocketIO(app, logging=False, engineio_logger=False)

    logging_buffer = []

    @app.route("/")
    def index():
        return app.send_static_file("index.html")

    @app.route('/<path:path>')
    def static_proxy(path):
        return app.send_static_file(path)

    @manager.on("logging")
    def logging_event(event_name, output, color):
        line = {"output": output, "color": color}
        logging_buffer.append(line)
        socketio.emit("logging", [line], namespace="/event")

    @socketio.on("connect", namespace="/event")
    def connect():
        emit("logging", logging_buffer, namespace="/event")
        logger.log("Client connected", "yellow", fire_event=False)

    @socketio.on("disconnect", namespace="/event")
    def disconnect():
        logger.log("Client disconnected", "yellow", fire_event=False)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
示例#2
0
class PServer():
    __metaclass__ = Singleton

    def __init__(self):
        # Flask Elements
        self.IO_SPACE = "/io"

        # self.test = "[TEST1]"

        self.app = Flask(__name__)
        self.app.config['DEBUG'] = False
        self.app.config['SECRET_KEY'] = "supersecret";

        # self.socketio = SocketIO(self.app)
        self.socketio = SocketIO(self.app, async_mode='threading')

    # LIttle spleeper
    def sleep_state(voice):
        time.sleep(SLEEP_TIME)

        self.send("sleep")
        logger.debug("WORKS")

        voice.stop_all()
        self.is_sleeping = True

    def send(self, event, data=""):
        lock.acquire(True)
        self.socketio.emit(event, data, namespace="/io")
        lock.release()


    def start(self):
        print "[STARTING SERVERS]"
示例#3
0
def socket_emit(meta=None, event='others'):
    try:
        socketio = SocketIO(message_queue=current_app.config['SOCKETIO_REDIS_URL'])
        socketio.emit(event, meta, namespace='/deyunio')
    except Exception as e:
        logger.warning('error in loading sitestatus ' + str(e))
        return {'failed': e}
    return {("sent " + str(event)) : meta}
示例#4
0
def main(**kwargs):
    opt = parse_cmdline()
    app = Flask('supcast.wsapp')
    app.config['SECRET_KEY'] = 'TODO: some secret?'
    socketio = SocketIO(app, async_mode='eventlet')
    eventlet.spawn(redis_listener, socketio)
    supcast.config.set_redis_url(opt.redis)
    socketio.run(app, host=opt.host, port=opt.port, **kwargs)
示例#5
0
def new_server(viewer_queue, stop_page, port, secret_key):
    # create server
    app = Flask(__name__, static_url_path='/static')
    app.config['SECRET_KEY'] = secret_key
    # must be 'threading' for broadcast emitting
    socketio = SocketIO(app, async_mode='threading',
                        logger=False, engineio_logger=False)

    # rooting
    @app.route('/')
    def __index():
        logger.info('Render viewer page')
        return render_template('index.html', script="index.js")

    if stop_page:
        @app.route('/stop')
        def __stop():
            socketio.stop()
            logger.info('Server stop request')
            return 'This server is stopped'

    @socketio.on('connect', namespace=IO_NAMESPACE)
    def __on_viewer_connect():
        logger.info('New viewer connection is established')

    @socketio.on('disconnect', namespace=IO_NAMESPACE)
    def __on_viewer_disconnect():
        logger.info('Viewer connection is closed')

    @socketio.on('update', namespace=IO_NAMESPACE)
    def __on_update():
        logger.info('Image updating request is received')
        # get all of current data
        emit_data = buffering_thread.get_data_all()
        # emit all
        logger.debug('Emit for update all')
        emit('update', emit_data, namespace=IO_NAMESPACE)

    def update_event(tab, name, data):
        emit_data = [[tab, name, data]]  # single data
        # broadcast emit
        logger.debug('Broadcast emit for update (tab: %s, name: %s)' %
                     (str(tab), str(name)))
        socketio.emit('update', emit_data, namespace=IO_NAMESPACE)

    # create image updating thread
    if viewer_queue:
        logger.info('Start image buffering thread')
        buffering_thread = ImageBufferingThread(viewer_queue)
        buffering_thread.daemon = True
        buffering_thread.start()
        buffering_thread.register_update_event_func(update_event)

    # start server
    logger.info('Start server on port %d' % port)
    socketio.run(app, host='0.0.0.0', port=port, debug=False, log_output=False)
    logger.info('Stop server on port %d' % port)
示例#6
0
def main():
    global socketio
    
    signal.signal(signal.SIGINT, signal_handler)
    
    print('Flask-SocketIO running...')
    app = Flask(__name__)
#    c = SimpleCache()
#    c.clear()
    Bootstrap(app)
    app.debug = False    
    socketio = SocketIO(app)

    ser = myComm.mySerial()
    net = myComm.myNet()
    
    @app.before_first_request
    def initialize():
        print('Called only once, when the first request comes in')
        ser.onMsg = onSerialMsg
#        ser.connect('COM3')
        ser.connect('COM5')
#        ser.connect('/dev/ttyACM0')
        net.onMsg = onNetMsg
#        net.connect('192.168.1.91', 12345)
        net.connect('10.0.0.4', 12345)
    
    @app.route('/')
    def index():
        print('Rendering index.html')
        return render_template('index.html')
    
    @app.route('/2')
    def index2():
        return render_template('index2.html')

    @app.route('/3')
    def index3():
        return render_template('index3.html')

    @socketio.on('ledACtrl', namespace='/test')
    def ledACtrl(message):
        print(message['led'])
        if message['led']:
            ser.sendMsg('l1')
        else:
            ser.sendMsg('l0')
    
    @socketio.on('ledRCtrl', namespace='/test')
    def ledRCtrl(message):
        print(message['led'])
        if message['led']:
            net.sendMsg('l1')
        else:
            net.sendMsg('l0')

    socketio.run(app, host = '0.0.0.0', port = 5001)
示例#7
0
文件: cli.py 项目: frnsys/brood
def front(port, working_dir, redis_host):
    """start the frontend server"""
    import eventlet
    eventlet.monkey_patch() # for flask_socketio message queue support
    from flask_socketio import SocketIO
    static = os.path.abspath(os.path.join(working_dir, 'static'))
    templs = os.path.abspath(os.path.join(working_dir, 'templates'))
    app = front_app(static_folder=static, template_folder=templs)
    socketio = SocketIO(app, message_queue=redis_host)
    socketio.run(app, host='0.0.0.0', port=port) # doesn't seem to work if debug=True
示例#8
0
class RestaurantDayQueue(Queue):
    def __init__(self,room):
        self.room = room
        self.socketio = SocketIO(message_queue=REDIS_URL)
        super().__init__()
    def put(self, report, block=True, timeout=None):
        self.socketio.emit('day_report', report.get_report(),room=self.room)
        #print(report.get_report())
        super().put(report, block, timeout)
        self.socketio.sleep(0)
示例#9
0
def simulate(restaurant,sid):
    simsocket = SocketIO(message_queue=REDIS_URL)
    layout = json.loads(restaurant)
    print("making rdq here")
    rdq = RestaurantDayQueue(sid)
    print("rdq has been made")
    r = Restaurant("Sophie's Kitchen", layout["equipment"], layout["tables"], layout["staff"], day_log=rdq, verbose=False)
    r.simulate(days=int(layout["days"]))
    report = r.ledger.generate_final_report()
    simsocket.emit("sim_report", report, room=sid)
示例#10
0
def run_socket_server():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "OpenPoGoBotSocket"
    socketio = SocketIO(app, logging=False, engineio_logger=False, json=myjson)

    state = {}

    botevents.register_bot_events(socketio, state)
    uievents.register_ui_events(socketio, state)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
示例#11
0
class SocketsHandler(logging.Handler):
    def emit(self, record):
        if not hasattr(self, 'socketio'):
            self.socketio = SocketIO(message_queue='redis://localhost:6379')
        try:
            # format: 'CHAN:DATA'
            chan, datastr = record.getMessage().split(':', 1)
            self.socketio.emit(chan, json.loads(datastr), namespace='/simulation')
        except (KeyboardInterrupt, SystemExit):
            raise
        except:
            self.handleError(record)
示例#12
0
def self_test(x=16, y=16,url=None):
    x = int(x)
    y = int(y)
    res = x + y
    context = {"id": "test", "x": x, "y": y}
    result = "add((x){}, (y){})".format(context['x'], context['y'])
    goto = "{}".format(context['id'])
    time.sleep(10)
    meta = json.dumps({'result':result, 'goto':goto})
    #post(url, json=meta)
    socketio = SocketIO(message_queue='redis://localhost:6379/0')
    socketio.emit('connect', meta, namespace='/deyunio')
    return meta
示例#13
0
def main():
    app = flask.Flask('espelhos_sonoros')
    app.config.from_object('config.Config')

    socketio = SocketIO(app, async_mode='threading')
    db = SQLAlchemy(app)

    espelhos_sonoros(app, socketio, db)

    app.logger.info('Started server.')

    if not app.config['DEBUG']:
        SSLify(app)

    socketio.run(app, host=app.config['HOST'], port=app.config['PORT'])
示例#14
0
def run_socket_server():
    app = Flask(__name__)
    app.config["SECRET_KEY"] = "OpenPoGoBotSocket"
    socketio = SocketIO(app, logging=False, engineio_logger=False, json=myjson)

    @app.route("/")
    def redirect_online():
        return redirect("http://openpogoui.nicontoso.eu")

    state = {}

    botevents.register_bot_events(socketio, state)
    uievents.register_ui_events(socketio, state)

    socketio.run(app, host="0.0.0.0", port=8000, debug=False, use_reloader=False, log_output=False)
示例#15
0
class Server(threading.Thread):

    def __init__(self, jukebox):
        threading.Thread.__init__(self)
        self.jukebox = jukebox


    def run(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'secret!'
        self.socketio = SocketIO(self.app)

        @self.socketio.on('connect')
        def handle_connect():
            emit('newSong', self.jukebox.current_song_name)

        @self.socketio.on('playback')
        def handle_message(playback):
            if playback == "pause":
                self.jukebox.pause()
            elif playback == "play":
                self.jukebox.play()
            elif playback == "next":
                self.jukebox.play_next_song()
                return self.jukebox.current_song_name
            print(playback)

        @self.socketio.on('addToQueue')
        def handle_add_to_queue(song):
        	if self.jukebox.add_to_queue(song):
			return True
		else:
			return False

        @self.app.route("/")
        def index():
            return render_template("queue.html")

        @self.app.route("/playstyring")
	@requires_auth
        def control():
            return render_template("index.html")

        self.socketio.run(self.app, host='0.0.0.0', port=80)

    def new_song(self, song):
        with self.app.test_request_context('/'):
            self.socketio.send('newSong', song)
    def test_delayed_init(self):
        app = Flask(__name__)
        socketio = SocketIO(allow_upgrades=False, json=flask_json)

        @socketio.on('connect')
        def on_connect():
            send({'connected': 'foo'}, json=True)

        socketio.init_app(app, cookie='foo')
        self.assertFalse(socketio.server.eio.allow_upgrades)
        self.assertEqual(socketio.server.eio.cookie, 'foo')

        client = socketio.test_client(app)
        received = client.get_received()
        self.assertEqual(len(received), 1)
        self.assertEqual(received[0]['args'], {'connected': 'foo'})
示例#17
0
文件: api_server.py 项目: kytos/kyco
    def __init__(self, app_name, listen='0.0.0.0', port=8181,
                 napps_dir=None):
        """Start a Flask+SocketIO server.

        Args:
            app_name(string): String representing a App Name
            listen (string): host name used by api server instance
            port (int): Port number used by api server instance
            napps_dir(string): napps path directory
        """
        dirname = os.path.dirname(os.path.abspath(__file__))
        self.flask_dir = os.path.join(dirname, '../web-ui')
        self.log = logging.getLogger('api_server')

        self.listen = listen
        self.port = port

        self.app = Flask(app_name, root_path=self.flask_dir,
                         static_folder="dist", static_url_path="/dist")
        self.server = SocketIO(self.app, async_mode='threading')
        self._enable_websocket_rooms()
        # ENABLE CROSS ORIGIN RESOURCE SHARING
        CORS(self.app)

        # Disable trailing slash
        self.app.url_map.strict_slashes = False

        # Update web-ui if necessary
        self.update_web_ui(force=False)
        self.napps_dir = napps_dir
示例#18
0
def start_scan(ScanParameter,sid):#scan should be forked by self,emit be handed over to celery
    print('ws start_scan')
    print(ScanParameter)
    print(sid)
    print(request.sid)#should be same
    socketio = SocketIO(message_queue='amqp://')
    socketio.emit('array', [1,2,'hello',3], room=request.sid)
    # multiprocessing.Process #first use thread test ,easy for debug
    scan_async = multiprocessing.Process(
        target=StockModal.Scanner.Scaner_main,
        kwargs={'ScanParameter': ScanParameter,
                'sid': request.sid
                }
    )
    # scan_async.setDaemon(True)
    scan_async.daemon=True
    scan_async.start()
示例#19
0
    def collect_websocket_modules(self):
        self.socket_io = SocketIO(self.flask_app)
        self.websockets = []
        for event, handler in WEBSOCKET_HANDLERS.items():
            register = self.socket_io.on(event)
            self.websockets.append(register(handler))

        return self.websockets
示例#20
0
文件: webapp.py 项目: hsmptg/webapp
    def __init__(self):
        print("Started WebApp")

        #to disable RuntimeWarning: This channel is already in use
        GPIO.setwarnings(False)

        GPIO.setmode(GPIO.BCM)
        # para usar o LED da placa (GPIO 47), fazer:
        # sudo sh -c "echo gpio >/sys/class/leds/led0/trigger"
        # para repor o comportamento habitual, fazer
        # sudo sh -c "echo mmc0 >/sys/class/leds/led0/trigger"
        GPIO.setup(23, GPIO.OUT)
        GPIO.output(23, GPIO.LOW)
        GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        GPIO.add_event_detect(18, GPIO.BOTH, callback=self.onButton)

        app = Flask(__name__)
        Bootstrap(app)        
        app.config['DEBUG'] = False
        self.socketio = SocketIO(app)
        self.counter = -1
                
        @app.before_first_request
        def initialize():
            print('Called only once, when the first request comes in')
            
        @app.route('/')
        def index():
            print("render index.html")
            return render_template("index2.html", board = "Raspberry Pi")
        
        @self.socketio.on('connect', namespace='/test')
        def test_connect():
            self.counter += 1
            print("Counter= {0}".format(self.counter))
            print('Client connected')
        
        @self.socketio.on('disconnect', namespace='/test')
        def test_disconnect():
            self.counter -= 1
            print("Counter= {0}".format(self.counter))
            print('Client disconnected')
            
        @self.socketio.on('getVersion', namespace='/test')
        def getVersion():
            print('version')

        @self.socketio.on('ledRCtrl', namespace='/test')
        def ledRCtrl(message):
            print(message['led'])
            GPIO.output(23, GPIO.HIGH if message['led'] else GPIO.LOW)
            if GPIO.input(18):
                print('Input was HIGH')
            else:
                print('Input was LOW')

        self.socketio.run(app, host = '0.0.0.0', port = 5001)
示例#21
0
文件: app.py 项目: hsmptg/webledbut
    def __init__(self):
        print("Started webledbut")

        self.thread = None

        #to disable RuntimeWarning: This channel is already in use
        GPIO.setwarnings(False)

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(23, GPIO.OUT)
        GPIO.output(23, GPIO.LOW)
        GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)

        app = Flask(__name__)
        Bootstrap(app)
        app.config['DEBUG'] = False
        self.socketio = SocketIO(app, async_mode='eventlet')
        self.counter = 0

        print('Begin thread')
        if self.thread is None:
            print('create thread')
            thread = Thread(target=self.background_thread)
            thread.daemon = True
            thread.start()

        @app.before_first_request
        def initialize():
            print('Called only once, when the first request comes in')

        @app.route('/')
        def index():
            print("render index.html")
            return render_template("index.html", board="Raspberry Pi")

        @self.socketio.on('connect', namespace='/test')
        def test_connect():
            self.counter += 1
            print("Counter= {0}".format(self.counter))
            print('Client connected')

        @self.socketio.on('disconnect', namespace='/test')
        def test_disconnect():
            self.counter -= 1
            print("Counter= {0}".format(self.counter))
            print('Client disconnected')

        @self.socketio.on('getVersion', namespace='/test')
        def getversion():
            print('version')

        @self.socketio.on('ledRCtrl', namespace='/test')
        def ledrctrl(message):
            print(message['led'])
            GPIO.output(23, GPIO.HIGH if message['led'] else GPIO.LOW)

        self.socketio.run(app, host='0.0.0.0', port=5001)
示例#22
0
def entry_point():

    # Graceful shutdown when kill are received
    signal.signal(signal.SIGTERM, lambda sig, frame: shutdown())

    # Graceful shutdown when terminal session are closed
    signal.signal(signal.SIGHUP, lambda sig, frame: shutdown())

    main()

    try:

        _config = settings.get_config_file()

        app.config['SECRET_KEY'] = _config.get('server', 'cookie_secret_key')
        app.config['DEBUG'] = _config.getboolean('server', 'debug', fallback=True)

        from scrapy_eagle.dashboard.views import servers, processes, root, jobs, react_app

        app.register_blueprint(root.root, url_prefix='/')
        app.register_blueprint(react_app.react_app, url_prefix='/app')
        app.register_blueprint(servers.servers, url_prefix='/servers')
        app.register_blueprint(processes.processes, url_prefix='/processes')
        app.register_blueprint(jobs.jobs, url_prefix='/jobs')

        CORS(app)

        socketio = SocketIO(app, async_mode='gevent')

        start_periodics(socketio)

        # use_reloader: avoid Flask execute twice
        socketio.run(
            app=app,
            host=_config.get('server', 'host', fallback='0.0.0.0'),
            port=_config.getint('server', 'port', fallback=5000),
            use_reloader=False
        )

    except (KeyboardInterrupt, SystemExit):

        shutdown()
示例#23
0
    def __init__(self):
        # Flask Elements
        self.IO_SPACE = "/io"

        # self.test = "[TEST1]"

        self.app = Flask(__name__)
        self.app.config['DEBUG'] = False
        self.app.config['SECRET_KEY'] = "supersecret";

        # self.socketio = SocketIO(self.app)
        self.socketio = SocketIO(self.app, async_mode='threading')
示例#24
0
class CombatLogs:

    def __init__(self):
        with open("config/config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile, Loader=yaml.Loader)

        self.enabledScroll = True
        self.verboseEvent = True
        self.scrollSpeed = 0.4
        self.print_newline = True

        self.logLevel = 1
        self.logger = Logger()

        redis_str = 'redis://' + cfg['redis']['host'] + ':' + str(cfg['redis']['port']) + '/0'

        self.socketio = SocketIO(message_queue=redis_str)

    def set_logger(self, logger: Logger):
        self.logger = logger

    def scroll(self, winner, loser, damage, gain, room=None):

        if not self.enabledScroll:
            return

        event = {'winner': {'name': winner.name, 'hit_points': winner.hitPoints, 'skill_points': winner.fightSkill,
                            'skill': winner.skill},
                 'loser': {'name': loser.name, 'hit_points': loser.hitPoints, 'skill_points': loser.fightSkill,
                           'skill': loser.skill},
                 'damage': damage, 'gain': gain}

        self.publish_event(json.dumps(event), 0, 'fight scroll', '/fight', room)

        time.sleep(self.scrollSpeed)

    def log_event(self, key, text, level):

        if level < self.logLevel:
            self.logger.write(key, text)

    def print_event(self, text, level):
        if level < self.logLevel:
            print(text, end="", flush=True)
            if self.print_newline:
                print("\n", end="")

    def publish_event(self, text, level, stream='stream', namespace='', room=None):
        if level < self.logLevel:
            if not room:
                self.socketio.emit(stream, {'data': text}, namespace=namespace, broadcast=True)
            else:
                if type(room) is dict:
                    for key, value in room.items():
                        if value is not None:
                            self.socketio.emit(stream, {'data': text}, namespace=namespace, room=value)
                else:
                    self.socketio.emit(stream, {'data': text}, namespace=namespace, room=room)
def run():
    socketio = SocketIO(message_queue='redis://')
    testnet = BitShares(node="wss://node.testnet.bitshares.eu")
    chain = Blockchain(mode="head", bitshares_instance=testnet)
    print(chain.bitshares.rpc.url, flush=True)
    for block in chain.blocks():
        timestamp = int(datetime.strptime(block["timestamp"], '%Y-%m-%dT%H:%M:%S').timestamp())
        num_ops = sum([len(tx["operations"]) for tx in block["transactions"]])
        num_txs = len(block["transactions"])
        TestBlock(timestamp, block.get("block_num", None), num_txs, num_ops)
        notice = {
            "block": block.get("block_num", 0),
            "timestamp": timestamp,
            "num_transactions": num_txs,
            "num_operations": num_ops,
        }
        print(notice, flush=True)
        socketio.emit(
            'notice',
            notice,
            namespace=namespace,
            room=room,
            broadcast=True)
示例#26
0
    def run_socket_server(self):
        app = Flask(__name__)
        app.config["SECRET_KEY"] = "OpenPoGoBotSocket"
        socketio = SocketIO(app, logging=False, engineio_logger=False, json=myjson)

        @app.route("/")
        def redirect_online():
            return redirect("http://openpogoui.nicontoso.eu")

        state = {}

        BotEvents(self.bot, socketio, state, self.event_manager)
        UiEvents(self.bot, socketio, state, self.event_manager, self.logger)

        self.log("Starting socket server...")

        socketio.run(
            app,
            host=self.config['socket_server']['host'] or '0.0.0.0',
            port=self.config['socket_server']['port'] or 8080,
            debug=False,
            use_reloader=False,
            log_output=False
        )
示例#27
0
    def __init__(self):
        with open("config/config.yml", 'r') as ymlfile:
            cfg = yaml.load(ymlfile, Loader=yaml.Loader)

        self.enabledScroll = True
        self.verboseEvent = True
        self.scrollSpeed = 0.4
        self.print_newline = True

        self.logLevel = 1
        self.logger = Logger()

        redis_str = 'redis://' + cfg['redis']['host'] + ':' + str(cfg['redis']['port']) + '/0'

        self.socketio = SocketIO(message_queue=redis_str)
示例#28
0
class Listener():
    def __init__(self, generator_domain):
        self.generator_domain = generator_domain

    def find_generator_by_url(self, url):
        return generators.find_generator_by_url(url)

    def on(self, url, callback):
        generator = self.find_generator_by_url(url)
        generator.set_callback(callback)

    def emit(self, url, callback):
        generator = self.find_generator_by_url(url)
        #dictToSend = {'question':'what is the answer?', 'data':[1,2,3]}
        # res = requests.post(self.generator_domain+'/'+url, json=dictToSend)
        try:
            res = requests.post(self.generator_domain+'/'+url)
            callback(np.array(res.json()))
        except:
            callback({ "err": "post to dategenerator from listener failed!"})

    def run(self, app, debug, port, host):
        self.init_routers(app)
        self.socketio = SocketIO(app)
        return self.socketio.run(app, debug=debug, port=port, host=host)

    def init_routers(self, app):
        @app.route('/', defaults={'url': ''})
        @app.route('/<path:url>', methods=['GET', 'POST'])
        def catch_url_generator_request(url):
            if(request.method == 'POST'):
                generator = self.find_generator_by_url(url)
                if(generator is None):
                    return 'no url match with a datagenerator!'
                else:
                    generator.execute_callback(np.array(request.json))
                    return 'data transfered to client listener!'
            else:
                return generators.handle('listener', url)
示例#29
0
    def run(self):
        self.app = Flask(__name__)
        self.app.config['SECRET_KEY'] = 'secret!'
        self.socketio = SocketIO(self.app)

        @self.socketio.on('connect')
        def handle_connect():
            emit('newSong', self.jukebox.current_song_name)

        @self.socketio.on('playback')
        def handle_message(playback):
            if playback == "pause":
                self.jukebox.pause()
            elif playback == "play":
                self.jukebox.play()
            elif playback == "next":
                self.jukebox.play_next_song()
                return self.jukebox.current_song_name
            print(playback)

        @self.socketio.on('addToQueue')
        def handle_add_to_queue(song):
        	if self.jukebox.add_to_queue(song):
			return True
		else:
			return False

        @self.app.route("/")
        def index():
            return render_template("queue.html")

        @self.app.route("/playstyring")
        def control():
            return render_template("index.html")

        self.socketio.run(self.app, host='0.0.0.0', port=80)
示例#30
0
from flask import Flask
from flask_cors import CORS
from app.config import Config
from flask_socketio import SocketIO, emit

app = Flask(__name__)
CORS(app, supports_credentials=True)

app.config['CORS_HEADERS'] = 'application/json'
app.config['JWT_SECRET_KEY'] = Config.JWT_SECRET_KEY
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = Config.JWT_ACCESS_TOKEN_EXPIRES
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app, cors_allowed_origins='*')

from app import routes 
示例#31
0
DB = SQLAlchemy(APP)

# IMPORTANT: This must be AFTER creating db variable to prevent
# circular import issues
import models

DB.create_all()

CORS = CORS(APP, resources={r"/*": {"origins": "*"}})

CURRENT_USERS = []
IN_GAME = []
UPDATE_SCORE = False

SOCKETIO = SocketIO(APP,
                    cors_allowed_origins="*",
                    json=json,
                    manage_session=False)


@APP.route('/', defaults={"filename": "index.html"})
@APP.route('/<path:filename>')
def index(filename):
    """
    build game
    """
    return send_from_directory('./build', filename)


# When a client connects from this Socket connection, this function is run
@SOCKETIO.on('connect')
def on_connect():
示例#32
0
from models import Player, Match, Match_Type, db
from sqlalchemy import and_
import chess
import chess.syzygy

app = Flask(__name__)

# configuration
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = config['SQLALCHEMY_DATABASE_URI']
app.config['SECRET_KEY'] = config['SECRET_KEY']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

socketio = SocketIO(app, cors_allowed_origins="*")

# chess boards
BOARDS = {}


@socketio.on('join_match')
def start_match(data):
    if data['username'] == "" or data['username'] is None:
        emit('empty_username')
    else:
        player = Player.query.filter_by(username=data['username']).first()
        if not player:
            player = Player(data['username'])
            player.save()
        if data['match_type'] == 'friendly':
示例#33
0
文件: plot.py 项目: zzragida/poker_ai
import logging
import os
import threading

from flask import Flask, render_template
from flask_socketio import SocketIO, emit
from poker_ai.games.short_deck.state import ShortDeckPokerState

from backend import convert

logging.getLogger("werkzeug").setLevel(logging.ERROR)
logging.getLogger("socketio").setLevel(logging.ERROR)
logging.getLogger("engineio").setLevel(logging.ERROR)
app = Flask(__name__, static_folder="./dist/static", template_folder="./dist")
app.config["SECRET_KEY"] = "secret!"
socketio = SocketIO(app, logger=False, engineio_logger=False)


@app.route("/", defaults={"path": ""})
@app.route("/<path:path>")
def _catch_all(path):
    return render_template("index.html")


class PokerPlot:
    """"""
    def __init__(self):
        """Run the visualisation server at port 5000."""
        global app
        self._app = app
        os.environ["WERKZEUG_RUN_MAIN"] = "true"
示例#34
0
from datetime import datetime
from pytz import utc, timezone
from lxml import etree as et
from Akvo import Flow
import pandas as pd
import xmltodict
import requests as r
import logging
import threading
from flask import Flask, jsonify, render_template
from flask_socketio import SocketIO, emit

app = Flask(__name__)
socketio = SocketIO(app, async_mode='threading')

### GLOBAL VARIABLE
global runjob
runjob = "inactive"

global workInProgressLock
workInProgressLock = threading.Lock()

logging.basicConfig(level=logging.WARN)
user_ids = [
    '230', '236', '233', '222', '238', '228', '235', '217', '234', '11', '226',
    '231', '237', '239', '10'
]
cdate = datetime.strftime(datetime.today().date(), '%Y-%m-%d')

tokenURI = 'https://login.akvo.org/auth/realms/akvo/protocol/openid-connect/token'
instanceURI = 'greencoffee'
示例#35
0
文件: mock.py 项目: jlovec1024/luna

@app.route('/api/terminal/v2/sessions/<pk>/replay/')
def get_session_replay(pk):
    # return jsonify({
    #   'type': 'guacamole',
    #   'src': 'http://localhost/media/2018-05-07/5c205f0a-b5ae-405a-9444-c0d59262ec29.gz',
    #   'status': 'DONE'
    # })
    return jsonify({
        'type': 'json',
        'src': 'http://localhost/media/replay/2018-06-08/581a12ca-fa8f-4399-8800-f97935219ddf.replay.gz',
        'status': 'DONE',
    })


@app.route('/luna/i18n/<i18n>')
def i18n(i18n):
    return send_file('./i18n/' + i18n)


def read_file(filename, charset='utf-8'):
    with open(filename, 'rb') as f:
        return f.read().decode(charset)


if __name__ == '__main__':
    socketio = SocketIO(app, async_mode=async_mode)
    socketio.on_namespace(SSHws('/ssh'))
    socketio.run(app, port=5001)
import os
from flask import *
from flask_socketio import SocketIO, emit
import psycopg2
import psycopg2.extras
from collections import OrderedDict
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from db import *
import uuid
import string
import random

app = Flask(__name__)
socketio = SocketIO(app)

app.secret_key = os.urandom(24).encode('hex')

globalDict = {'accessCode': ''}

#Queries
loginQuery = "SELECT passwordid FROM login WHERE password = crypt(%s, password)"
updatePasswordQuery = "UPDATE login SET password=crypt(%s, gen_salt('bf')) WHERE passwordid = 1"

studentTable = "INSERT INTO students(email, firstName, lastName, hasCar, passengers) VALUES (%s, %s, %s, %s, %s)"
endorseTable = "INSERT INTO endorsements(endorsementName, studentemail) VALUES (%s, %s)"
meetingTable = "SELECT meetingid from meetinday where "
meetingAddon = "%s = %s"
meetingInsert = "INSERT INTO meetingdays(monday, tuesday, wednesday, thursday, friday) VALUES (%s, %s, %s, %s, %s) RETURNING meetingid"
prevPracTable = "INSERT INTO previousPractica(school,grade,course,studentEmail) VALUES (%s, %s, %s, %s)"
示例#37
0
GENERATED_SONG_DIR = './static/generated_music/'
SCRIPT_ROOT = BACKEND_BASE

backend = back.Backend(UPLOAD_DIR, CONFIG_DIR, GENERATED_SONG_DIR, SCRIPT_ROOT)

UPLOAD_FOLDER = UPLOAD_DIR
CONFIG_FOLDER = CONFIG_DIR
GENERATED_SONG_FOLDER = GENERATED_SONG_DIR
ALLOWED_EXTENSIONS = {'xml'}

# Setup flask
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
socketio = SocketIO(app)

if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)
if not os.path.exists(CONFIG_FOLDER):
    os.makedirs(CONFIG_FOLDER)
# if not os.path.exists(GENERATED_SONG_FOLDER):
#     os.makedirs(GENERATED_SONG_FOLDER)

# Internally, backend can deliver process
# events on multiple threads (with the
# qualification that there is only one
# thread per process), ideally somehow
# process events should be translated
# into notifications to the web browser.
# Do the events need to be synchronized?
示例#38
0
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
app.config['DEBUG'] = True
app.config['LOG_FILE'] = 'application.log'

if app.debug:
    import logging
    logging.basicConfig(level=logging.WARNING)
    from logging import FileHandler, Formatter
    file_handler = FileHandler(app.config['LOG_FILE'])
    app.logger.addHandler(file_handler)
    file_handler.setFormatter(
        Formatter('%(asctime)s %(levelname)s: %(message)s '
                  '[in %(pathname)s:%(lineno)d]'))
#turn the flask app into a socketio app
socketio = SocketIO(app, async_mode=None, logger=True, engineio_logger=True)


def generate_user_file(json):
    with fasteners.InterProcessLock("generate_user_file.lock"):
        try:
            check = json['message']
            command = ['./user-generator.sh', str(check)]
            process = subprocess.Popen(command, stdout=subprocess.PIPE)
            while True:
                line = process.stdout.readline()
                app.logger.info('in while loop: ',
                                str(line.decode("utf-8").rstrip()))
                if not line:
                    break
                #the real code does filtering here
示例#39
0
import time

from flask import Flask, jsonify
from flask_cors import CORS
from flask_socketio import SocketIO, emit

import eventlet
eventlet.monkey_patch()

import rq_dashboard

from quoter import Quoter

app = Flask(__name__)
app.secret_key = binascii.hexlify(os.urandom(24))
socketio = SocketIO(app, async_mode='eventlet', cors_allowed_origins="*", engineio_logger=True)

#setup rq dashboard
app.config.from_object(rq_dashboard.default_settings)
app.register_blueprint(rq_dashboard.blueprint, url_prefix="/rq")


@socketio.on('connect')
def test_connect():
    print('Client connected')
    emit('connect', 'Connected to Flask-SocketIO')

@socketio.on('disconnect')
def test_disconnect():
    print('Client disconnected')
示例#40
0
import os
import re

from flask import Flask, render_template, redirect, session, request
from flask_session import Session
from flask_socketio import SocketIO, emit, join_room, leave_room, rooms
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
socketio = SocketIO(app)

# Configure session to use filesystem
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)

# Configure database
engine = create_engine(os.getenv("DATABASE_URL"))
db = scoped_session(sessionmaker(bind=engine))


def pic_path(folder, id):
    """Takes a folder name and an ID (user or server ID's) and returns a path to a picture"""
    path = f"static/images/{folder}/{id}.jpg"

    # If the path exists
    if os.path.isfile(path):
        return path
示例#41
0
文件: app.py 项目: fomichevic/TD
import eventlet

eventlet.monkey_patch()

from flask_socketio import SocketIO
from flask import Flask, g, session, request, flash, render_template, redirect, abort, url_for
from flask_openid import OpenID
from config import off
from db import create_db, create_user, update_score, users_top, find_user, all_db, user_status



app = Flask(__name__)
app.config.from_object('config')
socketio = SocketIO(app, async_mode='eventlet')
oid = OpenID(app, 'tmp')


def login_required(func):
    def before_request(*args, **kwargs):
        if g.user is None:
            return redirect('login')
        return func(*args, **kwargs)
    before_request.__name__ = func.__name__
    return before_request


@app.route('/top')
@login_required
def top():
    default_start, default_amount = 0, 100
示例#42
0
app.config[
    'MAX_CONTENT_LENGTH'] = max_upload_size * 1000 * 1000 * 1000  # Max upload size.
app.jinja_env.auto_reload = True

app.register_blueprint(yt)
app.register_blueprint(trimmer)

# The database object (db) needs to be defined in main.py even though we're not using the database in main.py
# Otherwise you get the following error:
# "AssertionError: The sqlalchemy extension was not registered to the current application."
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

# For the chat section of the website.
socketio = SocketIO(app)
socketio.init_app(app, cors_allowed_origins="*")

SESSION_TYPE = 'filesystem'
app.config.from_object(__name__)
Session(app)


# When a file has been uploaded, a POST request is sent to the homepage.
@app.route("/", methods=["POST"])
def homepage():

    if request.form['request_type'] == 'log_convert_clicked':
        log_this('clicked on the convert button.')
        return ''
示例#43
0
from model import RequestItem, Image, db
from forms import GrabberForm
from sqlalchemy import event
from sqlalchemy.exc import IntegrityError
from grab import Grab
from spider import Spider

logger = logging.getLogger('grab')
logger.addHandler(logging.StreamHandler())
logger.setLevel(logging.DEBUG)

downloader = urllib.URLopener()

# initate flask app
app = Flask(__name__)
socketio = SocketIO(app, logger=True, engineio_logger=True, log_output=True)


@app.route('/', methods=['GET', 'POST'])
def index():
    form = GrabberForm()
    return render_template('form.html',
                           form=form,
                           requests=list(reversed(RequestItem.query.all())))


@app.route('/<int:request_id>', methods=['GET'])
def get_request_item(request_id):
    return render_template('request_item.html',
                           item=RequestItem.query.get(request_id))
示例#44
0
import math

# thread_lock = Lock()

import eventlet
eventlet.monkey_patch()

host = "0.0.0.0"


# --------------------- FLASK APP  ---------------------

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

socketio = SocketIO(app)

db_flicdeamon = sqlite3.connect('../bin/armv6l/flicd.sqlite.db')
db_flicpi =  sqlite3.connect('flicpi.db')

@app.route('/')
def index():

	history = get_session_history()
	# get_graph_history()

	return render_template('index.html', history = history)


def get_session_history():
	history = []
示例#45
0
import os
import requests
from datetime import datetime
from flask_socketio import SocketIO

from . import make_celery
from .constants import BOT_USER
from .utils import is_float

celery = make_celery()
socketio = SocketIO(message_queue=os.environ['MESSAGE_QUEUE'])


@celery.task()
def quote_stock(stock_code, namespace, room):
    stock_url = 'https://stooq.com/q/l/?s={}&f=sd2t2ohlcv&h&e=csv'.format(
        stock_code.strip().lower())
    r = requests.get(stock_url)

    # Parse csv response
    csv_text = r.text
    csv_rows = csv_text.splitlines()
    csv_values = csv_rows[1].split(',')
    stock_symbol = csv_values[0]
    stock_close = csv_values[6]

    if is_float(stock_close):
        message_text = '{} quote is ${} per share.'.format(
            stock_symbol, stock_close)
    else:
        message_text = 'Invalid stock code: {}'.format(stock_code)
示例#46
0
文件: main.py 项目: 1716654446/qeq
# @Site    :
# @File    : main.py
# @Software: PyCharm
from flask import Flask, render_template, request, jsonify, send_from_directory
from flask_cors import *
from flask_socketio import SocketIO, emit, disconnect
import os

app = Flask(__name__)
CORS(app, resource=r'/*')
app.config['SECRET_KEY'] = 'secret!'
app.config['UPLOAD_FOLDER'] = 'upload'
ALLOWED_EXTENSIONS = set(
    ['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])
basedir = os.path.abspath(os.path.dirname(__file__))
socketio = SocketIO(app)
user = {}


@app.route('/')
def index():
    return render_template('index.html')


@socketio.on('client_event')
def client_msg(msg):
    decode_msg(msg)
    name = msg["name"]
    data = msg['data']
    if (name == "" or data == ""):
        pass
示例#47
0
#import flask_socketio
from flask_socketio import SocketIO

from . import db
from . import projects
from . import experiments
#from . import run
from GANEX.dash import summary, data, hyperparam, trainsettings, runexp, plots, inference, benchmark

from . import config
from .events import init_events
#from . import events

# from GANEX.plots import dashplot

socketio = SocketIO(
    async_mode='threading')  # add websocket #'async_mode='threading'
'''
def register_dashapps(app):
    # add plotlydash apps
    dashapp1 = Dash( __name__,
                server=app,
                routes_pathname_prefix='/dash/'
            )

    dashapp1.layout = html.Div("My Dash app")

    dashapp2 = Dash( __name__,
                server=app,
                routes_pathname_prefix='/dash2/'
            )
示例#48
0
import motion
import uds
import coil_circuit
import led_pair

import mysql.connector
import threading
import json
import RPi.GPIO as GPIO

from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit

# Initialize new flask app and WebSockets (for real-time server communication)
app = Flask(__name__)
socketio = SocketIO(app, async_mode='threading')

# Connect to MySQL database
# Get JSON credentials to connect
credentials = json.load(open('credentials.json', 'r'))

# Use credentials to connect to database
database = mysql.connector.connect(host=credentials['host'],
                                   user=credentials['user'],
                                   passwd=credentials['password'],
                                   database=credentials['database'])

# Initialize the projectile motion modelling code
y0 = 2  # The initial vertical launch position of the coilgun, relative to the distance sensor's line of "sight"
dt = 0.000001  # An approximation for the dt (an infinitesimally small time step) used in figure B - converts rates of change to actual quantities
predictor = motion.MotionPredictor(
示例#49
0
from flask import Flask
from flask_socketio import SocketIO
app = Flask(__name__)
sio = SocketIO(app)

import web.controller
from flask import Flask, render_template, request, jsonify
from flask_socketio import SocketIO, emit
from sage.all import *
from threading import Thread
from time import sleep
import traceback

from braid_group import BraidSignGroup
import logging, hashlib, random, argparse, requests
import config, json
CLIENT = "http://127.0.0.1:5080"
LAB_SERVER = "http://127.0.0.1:5082"

app = Flask(__name__)
app.config['JSONIFY_PRETTYPRINT_REGULAR'] = False
socketio = SocketIO(app)

import sqlite3
bsg = BraidSignGroup(config.braid['n'], config.braid['p'], config.braid['l'])

session = {}


def init_session(email):
    if email not in session:
        session[email] = {'secret_knowledge': {}}


@app.route('/', methods=['GET'])
def index():
    db = sqlite3.connect('db.sqlite').cursor()
示例#51
0
import json
import secrets
from flask import Flask, request, jsonify
from flask_socketio import SocketIO
from server_helper.api_manager import Manager

key = secrets.token_urlsafe(16)

app = Flask(__name__)
app.config['SECRET_KEY'] = key
socket = SocketIO(app)
manager = Manager()


@app.route('/login', methods=['POST'])
def login():
    response = {'data': 'Error'}

    try:
        data = request.get_json()

        username = data['user']
        password = data['password']
        is_student = data['is_student']

        if manager.check_user(username, password, is_student):
            response['data'] = key
            status_code = 200

        else:
            status_code = 401
示例#52
0
from flask import Flask
from flask_migrate import Migrate
from flask_socketio import SocketIO
from flask_login import LoginManager
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from werkzeug.utils import import_string

from config import config


ENV = os.getenv("ENV", "local")
login_manager = LoginManager()
db = SQLAlchemy()
celery = Celery(__name__, broker=config[ENV].CELERY_BROKER_URL)
socketio = SocketIO()
migrate = Migrate()

logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)


def create_app(env="local", additional_settings={}, **kwargs):
    logger.info(f"Environment in __init__: {env}")

    app = Flask(__name__, instance_relative_config=True)

    app.config.from_object(config[env])
    app.config.update(additional_settings)

    db.init_app(app)
示例#53
0
from flask import Flask, render_template
from flask_socketio import SocketIO
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)


@app.route('/')
def index():
    return "hello"


@socketio.on('message')
def handMessage(msg):
    print('menssage' + msg)
    send(msg, broadcast=True)


if __name__ == '__main__':
    socketio.run(app, host='192.168.137.207', port=5000)
示例#54
0
文件: app.py 项目: NagaveenaH/Chatapp
from datetime import datetime
import random

from bson.json_util import dumps
from flask import Flask, render_template, request, redirect, url_for
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from flask_socketio import SocketIO, join_room, leave_room
from pymongo.errors import DuplicateKeyError

from db import get_Allmessages,get_user, save_user, save_room, add_room_members, get_rooms_for_user, get_room, is_room_member, get_room_members, is_room_admin, update_room, remove_room_members, save_message, get_messages

app = Flask(__name__)
app.secret_key = "sfdjkafnk"
socketio = SocketIO(app)
login_manager = LoginManager()
login_manager.login_view = 'login'
login_manager.init_app(app)



@app.route('/')
def home():
    rooms = []
    if current_user.is_authenticated:
        rooms = get_rooms_for_user(current_user.username)
    return render_template("index.html", rooms=rooms)


@app.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
示例#55
0
from flask import Flask, jsonify, render_template
from subprocess import call
from flask_socketio import SocketIO, send

app = Flask(__name__)
app.secret_key = "mysecret"

socket_io = SocketIO(app)


@app.route('/')
def hello_world():
    return "Hello Gaemigo Project Home Page!!"


@app.route('/chat')
def chatting():
    return render_template('chat2.html')


@app.route('/tetris')
def tetris():
    return render_template('tetris_network.html')


@socket_io.on("message")
def request(message):
    print("message : " + message)
    to_client = dict()
    if message == 'new_connect':
        to_client['message'] = "새로운 유저가 난입하였다!!"
示例#56
0
from flask import Flask, jsonify, request
from flask_socketio import SocketIO, send, emit
from flask_cors import CORS
from repositories.DataRepository import DataRepository
from datetime import datetime, date

# Start app
app = Flask(__name__)
app.config['SECRET_KEY'] = 'FSWD!321lOpç'

socketio = SocketIO(app, cors_allowed_origins="*")
CORS(app)

# Custom endpoint
endpoint = '/api/v1'


# ROUTES
@app.route('/')
def info():
    return jsonify(info='Please go to the endpoint ' + endpoint)


@app.route(endpoint + '/progress', methods=["GET"])
def progress():
    if request.method == 'GET':
        return jsonify(DataRepository.read_logging())


@app.route(endpoint + '/progress/today', methods=["DELETE"])
def progress_today():
        height, width, _ = img_np.shape
        print("WHAT???????", x, y, x_plus_w, y_plus_h)
        cv2.rectangle(img_np, (int(x*width), int(height*y)),
                      (int(x_plus_w*width), int(y_plus_h*height)), color, 2)
        # cv2.putText(img_np, label, (int(x*width), int(y*height)-5),
        #            cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
    if not cv2.imwrite(os.path.abspath('flask-computer-vision/public/temp.bmp'), img_np):
        print("huh?")
    return 'temp.bmp'


app = Flask(__name__, static_folder='public', static_url_path='')
cors = CORS(app)
app.config['CORS_HEADERS'] = 'application/json'
socketio = SocketIO(app)
imgr = RecognizeImage(boto3.client(
    aws_access_key_id=ACCESS_KEY,
    aws_secret_access_key=SECRET_KEY,
    region_name='us-east-1',
    service_name='rekognition'
))
lex_client = boto3.client(aws_access_key_id=ACCESS_KEY,
                          aws_secret_access_key=SECRET_KEY,
                          region_name='us-east-1',
                          service_name='lex-runtime')
valuer = ValueImage()
img_b64 = ""

import random
def get_info(image, token):
示例#58
0
from flask import Flask, render_template
from flask_pymongo import PyMongo
from flask_socketio import SocketIO, emit
from random import random
from time import sleep
from threading import Thread, Event

app = Flask(__name__)
app.config['SECRET_KEY'] = 'asdfg'
app.config['MONGO_URI'] = 'mongodb://localhost/RNoec2'
mongo = PyMongo(app)
socketio = SocketIO(app)

thread = Thread()
thread_stop_event = Event()
class RandomThread(Thread):
    def __init__(self):
        self.delay = 1
        super(RandomThread, self).__init__()
    def randomNumberGenerator(self):
        """
        Generate a random number every 1 second and emit to a socketio instance (broadcast)
        Ideally to be run in a separate thread?
        """
        #infinite loop of magical random numbers
        print("Making random numbers")
        while not thread_stop_event.isSet():
            number = round(random()*10, 3)
            print(number)
            socketio.emit('numberg', {'number': number}, namespace='/test')
            mongo.db.dbs.insert_one({'no': number})
示例#59
0
from flask import Flask, render_template, send_file, send_from_directory
from flask_socketio import SocketIO, emit

app = Flask(__name__, static_url_path='')
app.debug = True
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

@app.route('/')
def index():
    return send_file('index.html')

@app.route('/Viewer/<path:path>')
def send(path):
    print "send_page", path
    return send_from_directory('Viewer', path)

@app.route('/Cesium/<path:path>')
def send_page(path):
    print "send_page", path
    return send_from_directory('Cesium', path)

@socketio.on('my event')
def test_message(message):
    emit('my response', {'data': 'got it!'})

@socketio.on('chat')
def test_message(msg):
    print "message:", msg
    #emit('chat', {'data': 'got it!'})
示例#60
0
app.config['UPLOADED_APKS_DEST'] = INPUT_APK_DIR
apks = UploadSet('apks', ('apk',))
configure_uploads(app, (apks,))

app.config['CELERY_BROKER_URL'] = config.RABBITMQ_URL
app.config['CELERY_ROUTES'] = {
    'static_analysis_task': {'queue': 'static_queue'},
    'dynamic_analysis_task': {'queue': 'dynamic_queue'}}
app.config['CELERYD_PREFETCH_MULTIPLIER'] = 1
app.config['CELERY_ACKS_LATE'] = True



gevent.monkey.patch_all()
socketio = SocketIO(app, message_queue=config.RABBITMQ_URL)


def make_celery(app):
    celery = Celery(broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask