class Server(): def __init__(self, port): self.port = port self.app = Flask(__name__, static_folder='assets/static', static_url_path='/static', template_folder='assets/templates') self.app.register_blueprint(routes) self.socketio = SocketIO(self.app) # Log to stdout. sh = logging.StreamHandler(sys.stdout) self.app.logger.addHandler(sh) @self.socketio.on('connect') def on_connect(): """ This seems necessary to get the SocketIO emitting working properly... """ pass def start(self): self.app.logger.debug('starting the nomadic server...') self.socketio.run(self.app, port=self.port) def refresh_clients(self): self.socketio.emit('refresh')
def ansible_server(send_queue, recv_queue): app = Flask(__name__) socketio = SocketIO(app) @socketio.on('message') def receive_message(msg): data = json.loads(msg) # Special channel for gamepad data if data['header']['msg_type'] == 'gamepad': mc.set('gamepad', data['content']) else: recv_queue.put_nowait(data) @socketio.on('connect') def on_connect(): print 'Connected to Dawn.' @socketio.on_error() def on_error(e): print e def send_process(send_queue): while True: try: msg = send_queue.get_nowait() socketio.emit('message', msg) time.sleep(.02) except Empty: time.sleep(.02) send_p = Thread(target=send_process, args=(send_queue,)) send_p.daemon = True send_p.start() socketio.run(app, host='0.0.0.0')
def main(): app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' db.init_app(app) init_login(app) init_admin_view(app, db) with app.app_context(): db.create_all() main_view = views.create_views() app.register_blueprint(url_prefix = '/', blueprint = main_view) socketio = SocketIO(app) socketio.run(app, '0.0.0.0', 8080)
def main(argv): global app, socketio, gpio_controller, rgb_controller handle_args(argv) gpio_controller = GPIOController(); rgb_controller = RGBController(gpio_controller) app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.debug = conf['server']['debug'] socketio = SocketIO(app) server_conf = conf['server'] socketio.run(app, use_reloader=server_conf['reload'], host=server_conf['host'], port=server_conf['port'])
def socketServer(): app = Flask(__name__) socketio = SocketIO(app) @socketio.on('appConnected') def app_connected(json): print('received json: ' + str(json)) @socketio.on('connect', namespace="/main") def startSocket(): print "test message2" @app.route('/') def load(): return render_template("betaIndex.html") @app.route('/launch') def loadLaunch(): return render_template("testLaunch.html") if __name__ == "__main__": socketio.run(app, "localhost", 80)
def __init__(self, ns, launcher_cmd_q=None): self.ns = ns self.launcher_cmd_q = launcher_cmd_q self.app = Flask(__name__) self.socketio = SocketIO(self.app, logger=True) # Logging info stream_handler = logging.StreamHandler() stream_handler.setLevel(logging.INFO) self.app.logger.addHandler(stream_handler) self.app.add_url_rule("/", "index", self.index) self.app.add_url_rule("/command", "command", self.command, methods=["POST"]) # Debugging screen self.app.add_url_rule("/debug/camera", "camera", self.camera) self.app.add_url_rule("/debug/wheels", "wheels", self.wheels) # Note: This is nested within __init__ on purpose @self.socketio.on('front_camera') def front_camera(sid): frame = self.ns.front_camera_frame frame64 = base64.b64encode(frame) data = { 'id': 0, 'raw': 'data:image/jpeg;base64,' + frame64, 'timestamp': time.time() } emit('front_frame', data) @self.socketio.on('back_camera') def back_camera(sid): frame = self.ns.back_camera_frame frame64 = base64.b64encode(frame) data = { 'id': 0, 'raw': 'data:image/jpeg;base64,' + frame64, 'timestamp': time.time() } emit('back_frame', data) @self.socketio.on('wheels') def wheels(sid): data = { 'target_steering': self.ns.target_steering, 'target_throttle': self.ns.target_throttle, } emit('wheels_data', data)
def __init__(self, port): self.port = port self.app = Flask(__name__, static_folder='assets/static', static_url_path='/static', template_folder='assets/templates') self.app.register_blueprint(routes) self.socketio = SocketIO(self.app) # Log to stdout. sh = logging.StreamHandler(sys.stdout) self.app.logger.addHandler(sh) @self.socketio.on('connect') def on_connect(): """ This seems necessary to get the SocketIO emitting working properly... """ pass
from flask.ext.socketio import SocketIO, emit import os import sys import signal import mosquitto import json import subprocess from configobj import ConfigObj from pyfina import pyfina pyfina = pyfina("data/") app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) mqtt_thread = None conffile = "/home/trystan/Desktop/pi/emonview/emonview.conf" settings = ConfigObj(conffile, file_error=True) username = settings["emonview"]["username"] password = settings["emonview"]["password"] @app.route('/') def index(): session['valid'] = session.get('valid', 0) if session['valid']: return render_template('index.html') else: return render_template('login.html')
from flask.ext.socketio import SocketIO socketio = SocketIO() from flask.ext.socketio import emit, send, join_room, leave_room from .authenticators import authenticated_socket from flask.ext.security import current_user from .models import Segment, Snippet, Story """ EVENTS: CLIENT EMITS: join ---- { 'story_id': 1 } SERVER EMITS welcome ------- { 'current_segment_id': 12 } SERVER BROADCASTS: user_joined ----------- {
from gevent import monkey monkey.patch_all() from flask import Flask, render_template, make_response from flask.ext.socketio import SocketIO, emit from threading import Thread import RPi.GPIO as GPIO import signal import sys app = Flask(__name__) app.config['SECRET_KEY'] = 'secret_pass' app.config['DEBUG'] = False socketio = SocketIO(app) GPIO.setmode(GPIO.BCM) pins = { 'light': { 'light-room-1': [[{'pinNumber': 17, 'state': 0}], {'overallState': 0}], 'light-room-2': [[{'pinNumber': 27, 'state': 0}], {'overallState': 0}], 'light-room-3': [[{'pinNumber': 22, 'state': 0}], {'overallState': 0}] }, 'temperature': { 'temp-room-1': [[], {'overallState': 15}], 'temp-room-2': [[], {'overallState': 20}], 'temp-room-3': [[], {'overallState': 25}] }
from flask import Flask, render_template from flask.ext.socketio import SocketIO,emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) messages=[] @app.route('/') def index(): return app.send_static_file('index.html') @socketio.on('connect',namespace='/chat') def makeConnection(): print "Connected" for message in messages: print message emit('message',message) @socketio.on('message',namespace='/chat') def new_message(message,name): tmp={'text':message,'name':name} print ('\n\n'+ tmp['name']+' said: '+tmp['text']+'\n\n') messages.append(tmp) emit('message',tmp,broadcast=True) if __name__ == '__main__': socketio.run(app, debug=True)
eventlet.monkey_patch() import flask from flask.ext.socketio import SocketIO, emit from six.moves import range from simulation.turn_manager import world_state_provider from simulation import map_generator from simulation.avatar.avatar_manager import AvatarManager from simulation.game_state import GameState from simulation.turn_manager import TurnManager from simulation.worker_manager import WORKER_MANAGERS app = flask.Flask(__name__) socketio = SocketIO() worker_manager = None def to_cell_type(cell): if not cell.habitable: return 1 if cell.generates_score: return 2 return 0 def player_dict(avatar): # TODO: implement better colour functionality: will eventually fall off end of numbers colour = "#%06x" % (avatar.player_id * 4999)
LOG_FILE = 'logs/WebApp.log' # Initialises system variables, this object is the heart of the application HomeSurveillance = SurveillanceSystem.SurveillanceSystem() # Threads used to continuously push data to the client alarmStateThread = threading.Thread() facesUpdateThread = threading.Thread() monitoringThread = threading.Thread() alarmStateThread.daemon = False facesUpdateThread.daemon = False monitoringThread.daemon = False # Flask setup app = Flask('SurveillanceWebServer') app.config['SECRET_KEY'] = os.urandom(24) # Used for session management socketio = SocketIO(app) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'uploads/imgs' configure_uploads(app, photos) @app.route('/', methods=['GET','POST']) def login(): error = None if request.method == 'POST': session.pop('user',None) # Drops session everytime user tries to login if request.form['username'] != 'admin' or request.form['password'] != 'admin': error = 'Invalid username or password. Please try again' else: session['user'] = request.form['username'] return redirect(url_for('home'))
#!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask, render_template, session from flask.ext.socketio import SocketIO, emit import json import uuid import random app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) userid = [] def getId(): global userid temp = random.randint(0, 10000) while temp in userid: temp = random.randint(0, 10000) userid.append(temp) return "User" + str(temp) @app.route('/<path:path>') def static_proxy(path): # send_static_file will guess the correct MIME type print path return app.send_static_file(path)
# 'create_date' : { # 'type' : 'date', # 'format' : 'yyyy-MM-dd HH:mm:ss' # }, # 'coordinates' : { # 'type' : 'geo_point' # } # } # } # } # } # elastic.indices.create(index = 'tweet_test', ignore = 400, body = mapping) application = Flask(__name__) socketio = SocketIO(application) @application.route('/') def get_index_page(): return render_template('index.html') @socketio.on('connect', namespace='/test') def test_connect(): print 'conntected!' send_thread = Send_Thread() send_thread.start() @socketio.on('range_search', namespace='/test') def search_range(data): print data
import flask import model import random import string import logging from flask.ext.socketio import SocketIO, emit from flask import request from control.router import router from model.redis_db import redis_manager from model.pps import PPS app = flask.Flask(__name__) app.debug = True app.register_blueprint(router, url_prefix='') sio = SocketIO(app) redis_manager.flushall() @sio.on('insert', namespace='/insert') def insert(message): print 'hello inset' ch = int(message['char']) pos = int(message['pos']) user = message['userName'] pps = PPS(user=user) if int(message['char']) == 8: pps.delete(pos) elif int(message['char']) != 8: print 'insertinggggg' pps.insert(ch, pos)
from .config import config_value # noqa from digits import utils # noqa from digits.utils import filesystem as fs # noqa from digits.utils.store import StoreCache # noqa import digits.scheduler # noqa # Create Flask, Scheduler and SocketIO objects app = flask.Flask(__name__) app.config['DEBUG'] = True # Disable CSRF checking in WTForms app.config['WTF_CSRF_ENABLED'] = False # This is still necessary for SocketIO app.config['SECRET_KEY'] = codecs.encode(os.urandom(12), 'hex_codec') app.url_map.redirect_defaults = False socketio = SocketIO(app, async_mode='gevent') app.config['store_cache'] = StoreCache() app.config['store_url_list'] = config_value('model_store')['url_list'] scheduler = digits.scheduler.Scheduler(config_value('gpu_list'), True) # Register filters and views app.jinja_env.globals['server_name'] = config_value('server_name') app.jinja_env.globals['server_version'] = digits.__version__ app.jinja_env.globals['caffe_version'] = config_value('caffe')['version'] app.jinja_env.globals['caffe_flavor'] = config_value('caffe')['flavor'] app.jinja_env.globals['dir_hash'] = fs.dir_hash( os.path.join(os.path.dirname(digits.__file__), 'static')) app.jinja_env.filters['print_time'] = utils.time_filters.print_time app.jinja_env.filters['print_time_diff'] = utils.time_filters.print_time_diff app.jinja_env.filters['print_time_since'] = utils.time_filters.print_time_since
# Start with a basic flask app webpage. from flask.ext.socketio import SocketIO, emit from flask import Flask, render_template, url_for, copy_current_request_context from random import random from time import sleep from threading import Thread, Event __author__ = 'slynn' app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.config['DEBUG'] = True #turn the flask app into a socketio app socketio = SocketIO(app) #random number Generator Thread 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? """
from gevent import monkey monkey.patch_all() import cgi import redis from flask import Flask, request, render_template from flask.ext.socketio import SocketIO app = Flask(__name__) db = redis.StrictRedis('localhost', 6379, 0) socketio = SocketIO(app) @app.route('/') def main(): c = db.get('user_count') return render_template("main.html", connected=c) @app.route('/pymeetups/') def pymeetups(): return render_template("pymeetups.html") @socketio.on('connect', namespace="/sfpy") def ws_conn(): c = db.incr('user_count') socketio.emit('msg', {'count': c}, namespace="/sfpy") @socketio.on('disconnect', namespace="/sfpy")
def __init__(self, __name__): Thread.__init__(self) self.app = Flask(__name__) self.app.config['SECRET_KEY'] = 'secret!' self.app.config['DEBUG'] = False self.socketio = SocketIO(self.app)
from commons.config import Config from commons.flask_lsm_auth import LSM import logging import sys import io import time import StringIO import time from ship.logger import ShipLogger from commons.log_emitter import LogEmitter config = Config() webserver_config = config.get('webserver') app = flask.Flask("shipui") app.config['SECRET_KEY'] = webserver_config.get('websockets_secret_key') socketio = SocketIO(app) app.register_blueprint(api_app, url_prefix='/api') app.register_blueprint(deploy_app, url_prefix='/deploy') app.register_blueprint(conf_app, url_prefix='/conf') app.register_blueprint(properties_app, url_prefix='/properties') @app.route("/", methods=["GET"]) def index(): return flask.redirect("/deploy") @app.route("/logout", methods=["GET"]) def logout(): lsm.logout(flask.request.url_root) return lsm.compose_response()
#!/usr/bin/env python from flask import Flask, render_template from flask.ext.socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) #event_name = "my_event" #namespace = "/my_namespace" event_name = "text" #namespace = "/my_namespace" #@socketio.on(event_name, namespace=namespace) @socketio.on(event_name) def test_message(message): print("called!") print("receive: ") print(message) #emit('my response', {'data': message['data']}) if __name__ == '__main__': socketio.run(app, host='192.168.101.58', port=8011)
import os import signal from RTKLIB import RTKLIB from port import changeBaudrateTo230400 from threading import Thread from flask import Flask, render_template, session, request from flask.ext.socketio import SocketIO, emit, disconnect app = Flask(__name__) app.template_folder = "." app.debug = False app.config["SECRET_KEY"] = "secret!" socketio = SocketIO(app) # configure Ublox for 230400 baudrate! changeBaudrateTo230400() rtk = RTKLIB(socketio) perform_update = False # at this point we are ready to start rtk in 2 possible ways: rover and base # we choose what to do by getting messages from the browser @app.route("/") def index(): return render_template("index.html")
from core.api import rest_api from core.signals import task_added, task_completed, worker_before_execution, worker_after_execution, task_deleted from core.commands import command_manager import settings # Flask application web = Flask(__name__, static_url_path='/assets') web.config.from_object(settings) # REST API web.register_blueprint(rest_api, url_prefix='/api') # WebSocket API socket = SocketIO(web) # Command manager = command_manager(web, socket) @web.route('/') @web.route('/<path:path>') def index(path=''): # if path.startswith('api'): return abort(404) return web.send_static_file('views/index.html') @web.route('/favicon.ico') def favicon():
STATIC_FOLDER = "static" TEMPLATE_FOLDER = "template" def get_ip_address_from_interface(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24]) except IOError: return "[none]" app = Flask(__name__, static_url_path = STATIC_PATH, static_folder = STATIC_FOLDER, template_folder = TEMPLATE_FOLDER) socketio = SocketIO(app) host = get_ip_address_from_interface("eth0") port = 8000 p_host = "localhost" p_port = 9000 @app.route('/') def index(): return render_template("synth", host=host, port=port) @socketio.on('connect', namespace='/pendulum') def test_connect(): print "Client connected" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
from flask import Flask, render_template from flask.ext.socketio import SocketIO import zmq import math import os import simplejson app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.debug = True socketio = SocketIO(app) context = zmq.Context() motors_socket = context.socket(zmq.PUSH) #motors_socket = context.socket(zmq.PUB) motors_socket.connect("ipc:///tmp/motors.ipc" ) #Not supported by windows, comment out for testing #motors_socket.connect("tcp://127.0.0.2:1100") #motors_socket.connect("tcp://localhost:8558") # Comment out for production battery_socket = context.socket(zmq.SUB) battery_socket.connect("ipc:///tmp/battery.ipc") battery_socket.setsockopt(zmq.SUBSCRIBE, "") #subscribe all messages #HTML_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'html/') class RemoteControl(object): neutral_max = 155 neutral_min = 100 neutral = 128
from recommender import recommender reload(sys) sys.setdefaultencoding("UTF8") import os import uuid from flask import * from flask.ext.socketio import SocketIO, emit from flask_socketio import join_room, leave_room import psycopg2 import psycopg2.extras psycopg2.extensions.register_type(psycopg2.extensions.UNICODE) psycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY) app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) def connect_to_db(): return psycopg2.connect('dbname=movie_recommendations user=movie_normal password=password host=localhost') # return psycopg2.connect('dbname=movie_recommendations user=postgres password=Cmpgamer1 host=localhost') @socketio.on('connect', namespace='/movie') def makeConnection(): session['uuid'] = uuid.uuid1() print ('Connected') @socketio.on('identify', namespace='/movie') def on_identify(user): print('Identify: ' + user) users[session['uuid']] = {'username' : user}
# -*- coding: utf8 -*- from gevent import monkey monkey.patch_all() import gevent import os from flask import Flask, render_template, request from flask.ext.socketio import SocketIO, emit from twython import TwythonStreamer app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) port = int(os.getenv('VCAP_APP_PORT', 5000)) from config import CONF class TwitterStreamer(TwythonStreamer): def __init__(self, *args, **kwargs): TwythonStreamer.__init__(self, *args, **kwargs) print("Initialized TwitterStreamer.") self.queue = gevent.queue.Queue() def on_success(self, data): self.queue.put_nowait(data) if self.queue.qsize() > 10000: self.queue.get() def on_error(self, status_code, data):
from gevent import monkey monkey.patch_all() import cgi import redis from flask import Flask, render_template, request from flask.ext.socketio import SocketIO app = Flask(__name__) db = redis.StrictRedis('localhost', 6379, 0) socketio = SocketIO(app) @app.route('/') def main(): return render_template('main.html') @app.route('/pymeetups/') def pymeetups(): return render_template('pymeetups.html') @socketio.on('connect', namespace='/dd') def ws_conn(): c = db.incr('connected') socketio.emit('msg', {'count': c}, namespace='/dd') @socketio.on('disconnect', namespace='/dd') def ws_disconn():
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.login import LoginManager from flask.ext.socketio import SocketIO app = Flask(__name__) app.debug = True app.config.from_object('config') db = SQLAlchemy(app) lm = LoginManager() lm.init_app(app) lm.login_view = 'login' socketio = SocketIO(app) from app import views, models
from lib.utils import save_reading, get_trial_path, decode_dict from flask import Flask, request, send_file, render_template from flask.ext.socketio import SocketIO, emit import lib.mindwave_client as mindwave_client import json import time import traceback import logging app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) ''' deliver the webapp to the browser handle POST data from mindwave_client ''' @app.route('/', methods = ['GET', 'POST']) def hello(): # deliver the webapp to the browser if request.method == 'GET': return render_template('index.html') # receive data from mindwave_client if request.method == 'POST': data = handle_data(request.json) # send socket.io socketio.emit('data', data) return 'ok'
from flask.ext.bcrypt import Bcrypt from flask.ext.socketio import SocketIO app = Flask(__name__, template_folder='../templates', static_folder='../static') app.jinja_env.add_extension('pyjade.ext.jinja.PyJadeExtension') app.debug=True app.secret_key = 'this is soooooo secret right?' app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://*****:*****@ec2-54-204-15-48.compute-1.amazonaws.com:5432/d983rtid8h2rk' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True db = SQLAlchemy(app) db.engine.connect() bcrypt = Bcrypt(app) socketio = SocketIO() socketio.init_app(app) from user import users from request import requestsBP from contract import contractBP from rating import ratings from notify import notifications from schedule import scheduler from chat import chatBP app.register_blueprint(users) app.register_blueprint(requestsBP) app.register_blueprint(contractBP) app.register_blueprint(ratings) app.register_blueprint(notifications) app.register_blueprint(scheduler)
from flask import Flask, render_template, request,session,redirect,url_for from flask.ext.socketio import SocketIO,emit,join_room,leave_room app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/',methods=['GET','POST']) def index(): #webbrowser.open_new(url) if request.method=='POST': session['name'] = request.form['name'] session['room'] = request.form['room'] return redirect(url_for('py')) return render_template('index.html',template_folder='templates') @app.route('/py') def py(): name = session.get('name','') room = session.get('room','') return render_template('out.html', name=name, room=room, template_folder='templates') @socketio.on('connect',namespace='/chat') def ws_connect(): """Sent by clients when they enter a room. A status message is broadcast to all people in the room."""
import subprocess #to import python modules from the $SUMO_HOME/tools directory sys.path.append(os.path.join(os.environ["SUMO_HOME"], "tools")) import sumolib from sumolib import checkBinary import traci import time from flask import Flask, Response, url_for, render_template #from flask_socketio import SocketIO from flask.ext.socketio import SocketIO, emit #################################### app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) #coords =[[28,112],[28,113],[29,114],[27,114]] coords=[] values = { 'slider1': 25, 'slider2': 0, } def init(): PORT = 8873 sumoProcess = subprocess.Popen([checkBinary("sumo"), "-c", "mwd_in_rain.sumocfg", "--remote-port", str(PORT)], stdout=sys.stdout, stderr=sys.stderr) traci.init(PORT) def sim():
from pprint import pprint import livingroom #from psutil import virtual_memory as get_memory rooms = [{'name': 'livingroom'}, {'name': 'bedroom'}, {'name': 'server'}] __author__ = 'ben' app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.config['DEBUG'] = True #turn the flask app into a socketio app socketio = SocketIO(app) #random number Generator Thread thread = Thread() thread_stop_event = Event() class RandomThread(Thread): def __init__(self): self.delay = 5 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?
if not os.path.exists(download_path): logger.info('Creating Download Path at %s', download_path) os.makedirs(download_path) if prem_config.getboolean('upload', 'watchdir_enabled'): upload_path = prem_config.get('upload', 'watchdir_location') if not os.path.exists(upload_path): logger.info('Creating Upload Path at %s', upload_path) os.makedirs(upload_path) logger.info('Initializing Flask') app = Flask(__name__) app.config['SECRET_KEY'] = os.urandom(24) app.config.update(DEBUG=prem_config.getboolean('global', 'debug_enabled'), ) socketio = SocketIO(app) app.config['LOGIN_DISABLED'] = not prem_config.getboolean( 'security', 'login_enabled') login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = 'login' db = shelve.open('premiumizer.db') tasks = [] downloading = False downloader = None total_size_downloaded = None #
from flask import Flask, render_template from flask.ext.socketio import SocketIO import zmq import math import os import simplejson app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.debug = True socketio = SocketIO(app) context = zmq.Context() motors_socket = context.socket(zmq.PUSH) #motors_socket = context.socket(zmq.PUB) motors_socket.connect("ipc:///tmp/motors.ipc") #Not supported by windows, comment out for testing #motors_socket.connect("tcp://127.0.0.2:1100") #motors_socket.connect("tcp://localhost:8558") # Comment out for production battery_socket = context.socket(zmq.SUB) battery_socket.connect("ipc:///tmp/battery.ipc") battery_socket.setsockopt(zmq.SUBSCRIBE, "") #subscribe all messages #HTML_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'html/') class RemoteControl(object): neutral_max = 155 neutral_min = 100 neutral = 128 v_max = 100 v_min = -100
import re import json import time import util import hashlib import pymongo from lib import mongo from flask.ext.cors import CORS from flask import Flask, request from bson.objectid import ObjectId from flask.ext.socketio import SocketIO, emit, send app = Flask(__name__) CORS(app) app.config['SECRET_KEY'] = "Hardcoded Temporary Key" socketio = SocketIO(app) util = util.Util() @app.route('/') def index(): return "index" # Registers a new user and logs them in @app.route("/register", methods=['POST']) def register(): user = request.form['user'] passw = request.form['passw'] if "details" in request.form: details = request.form['details'] details = json.loads(details) else:
from flask import Flask, render_template, session, redirect, url_for from flask.ext.socketio import SocketIO, emit, disconnect from flask.ext.bootstrap import Bootstrap from flask.ext.wtf import Form from wtforms import StringField, SubmitField from wtforms.validators import Required app = Flask(__name__) app.config['SECRET_KEY'] = 'test' ws = SocketIO(app) bootstrap = Bootstrap(app) app.debug = True thread = None class NickForm(Form): name = StringField('Nickname: ', validators=[Required()]) submit = SubmitField('Set Nickname') @app.route('/chat') def chat(): if session.get('nick') != None: return render_template('index.html', nickname=session.get('nick')) else: return redirect(url_for('index')) @app.route('/', methods=['GET', 'POST']) def index(): if session.get('nick') != None: return redirect(url_for('chat')) form = NickForm()
def createSocketIO(app): global thread thread = Thread(target=background_thread) thread.start() return SocketIO(app)
try : self.data = json.loads(request.form['data']) print "DATA: ", self.data return "success\n" except KeyError: print request.form return "Key Error: " + ",".join(request.form.keys()) except ValueError: return "Value Error: " + request.form['data'] def get_data(self): return self.data application = Flask(__name__) socketio = SocketIO(application) lds = LidarServer() @application.route('/') def get_root(): return render_template('index.html') @application.route('/data/') def index(): return render_template('data.html') # when we get a post full of data, send it! @application.route("/publish/", methods = ['POST']) def publish_data(): response = lds.publish_data() socketio.emit('force_update', lds.get_data())
from flask import Flask flapp = Flask(__name__) from flask.ext.socketio import SocketIO socketio = SocketIO(flapp) from app import views, conf
from flask import Flask, render_template from flask.ext.socketio import SocketIO, emit import json import plotly import dash.utils as utils from dash.components import graph name = 'dash-3-click-events' app = Flask(name) app.debug = True app.config['key'] = 'secret' socketio = SocketIO(app) from example_3_click_events_state import Dash dash = Dash() # Write the HTML "includes" blocks to /templates/runtime/dash-3-click-events # We're using the template "layout_two_column_and_controls" which uses the # includes blocks: 'controls.html', 'leftgraph.html', and 'rightgraph.html'. utils.write_templates( { # 'controls.html' is already written as a raw html file in # templates/runtime/dash-3-click-events 'leftgraph': [graph('bubbles')], 'rightgraph': [graph('line-chart')] }, name )
from flask import Flask, render_template from flask.ext.socketio import SocketIO, emit import os import time import re from random import randint, choice from utils import GetLatLon, get_antonyms, get_synonyms, spell_corrector app = Flask(__name__) app.config['SECRET_KEY'] = 'secret_key' socketio = SocketIO(app) port = int(os.getenv('VCAP_APP_PORT', 5000)) @app.route('/') def index(): return render_template('index.html') @socketio.on('connect', namespace='/app') def connect(): emit('check_connection', {'data': 'Connected'}) @socketio.on('message', namespace='/app') def message(): emit('graph_data', { 'date': time.strftime("%a %m/%d/%Y"), 'time': time.strftime("%H:%M:%S"),
from flask.ext.wtf import Form from wtforms import TextField, PasswordField from wtforms.validators import Required, length ### VAR ### #thread = None #thread2 = None fireflies = [] roomName = u'Die_freien_Verrückten' ### CONFIG SERVEUR ### app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = 'Fools rush in where angels fear to tread.' socketio = SocketIO(app) ### PARTIE SERVEUR ### def fireflies_thread(): """doesn't work currently""" size = len(fireflies) while True: sleep(5) newSize = len(fireflies) if newSize != size: print 'changes in fireflies' emit('update fireflies', {'fireflies': fireflies}) size = newSize def backup_thread():
import time, datetime import json, re from threading import Thread from flask import Flask, render_template, session, request from flask.ext.socketio import SocketIO, emit, join_room, leave_room from msc_apps import * from balancehelper import * from omnidex import getOrderbook from values_service import getValueBook from cacher import * import config app = Flask(__name__) app.debug = True app.config['SECRET_KEY'] = config.WEBSOCKET_SECRET socketio = SocketIO(app) #threads watchdog = None emitter = None bthread = None vthread = None othread = None #stat trackers clients = 0 maxclients = 0 maxaddresses = 0 #data addresses = {} orderbook = {} lasttrade = 0
# coding: utf-8 from datetime import datetime from flask import Flask from flask.ext.socketio import SocketIO, join_room app = Flask(__name__) socketio = SocketIO(app) cnt = 0 @socketio.on('connect') def test_connect(message): join_room('1') print "CONNECT" @socketio.on('disconnect') def test_disconnect(): print('Client disconnected') def redis_thread(): import redis global cnt cnt += 1 r = redis.StrictRedis(host="localhost", port=6379, db=0)
from utils.settings import SECRET_KEY, ALERT_GRP, STATUS_GRP, DATA_GRP, BRILLO_GRP, TAP_ENV_VARS from datetime import timedelta try: import pymysql pymysql.install_as_MySQLdb() except ImportError: pass """ static resource location""" static_url_prefix = '' app = Flask(__name__, static_url_path='') app.config['SECRET_KEY'] = SECRET_KEY logger = logging.getLogger(__name__) socketio = SocketIO(app, pingTimeout=60) def login_required(func): """ Decorator to check whether user's login If not, redirect to login page """ @functools.wraps(func) def wrapper(*args, **kwargs): if 'username' in session: return func(*args, **kwargs) else: return redirect(url_for('login')) return wrapper
app = Eve(__name__, static_url_path="/static") app.debug = True app.config.update( DEBUG=True, # EMAIL SETTINGS MAIL_SERVER="smtp.gmail.com", MAIL_PORT=465, MAIL_USE_SSL=True, MAIL_USERNAME="******", MAIL_PASSWORD="******", ) mail = Mail(app) socketio = SocketIO(app) def create_token(user): payload = {"sub": str(user["_id"]), "iat": datetime.now(), "exp": datetime.now() + timedelta(days=14)} token = jwt.encode(payload, TOKEN_SECRET) return token.decode("unicode_escape") def login_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not request.headers.get("Authorization"): response = jsonify(error="Missing authorization header") response.status_code = 401
#!/usr/bin/env python from gevent import monkey monkey.patch_all() from flask import Flask, render_template, request from flask.ext.socketio import SocketIO, emit import random import requests import os import json from hue import Hue app = Flask(__name__, static_folder='static', static_url_path='/static') app.config['SECRET_KEY'] = 'secret!' app.debug = True socketio = SocketIO(app) resp = requests.get('https://www.meethue.com/api/nupnp') ip = json.loads(resp.content)[0]["internalipaddress"] h = Hue() h.station_ip = ip h.get_state() @app.route('/') def index(): return render_template('index.html') @socketio.on('update_light', namespace='/lights')
from proto import cpuvisor_srv_pb2 as protosrv # setup flask app app = Flask(__name__, static_url_path='/static') app.config.from_object(__name__) app.config.update(dict( DEBUG=True, SECRET_KEY='secret', SERVER_CONFIG=os.path.normpath(os.path.join(file_dir, '../config.prototxt')) )) # pass through socketio middleware socketio = SocketIO(app) server_config = protoconfig.Config() with open(app.config['SERVER_CONFIG'], 'rb') as f: protobuf.text_format.Merge(f.read(), server_config) # link dsetimages and downloaded into static dir cwd_store = os.getcwd() os.chdir('static/app/') if os.path.islink('dsetimages'): os.unlink('dsetimages') if not os.path.exists('dsetimages'): print 'Linking dataset base dir: %s' % server_config.preproc_config.dataset_im_base_path os.symlink(server_config.preproc_config.dataset_im_base_path, 'dsetimages')
if m in service_list: port = service_list[m].port elif m.isdigit(): port = int(m) else: print("service not found") sys.exit(-1) sock = messaging.sub_sock(context, port, poller, addr=args.addr) if args.proxy: republish_socks[sock] = messaging.pub_sock(context, port) if args.map: from flask.ext.socketio import SocketIO #pylint: disable=no-name-in-module, import-error from flask import Flask app = Flask(__name__) socketio = SocketIO(app, async_mode='threading') server_thread = Thread(target=run_server, args=(socketio, )) server_thread.daemon = True server_thread.start() print('server running') values = None if args.values: values = [s.strip().split(".") for s in args.values.split(",")] while 1: polld = poller.poll(timeout=1000) for sock, mode in polld: if mode != zmq.POLLIN: continue msg = sock.recv()
from flask import Flask, render_template, request from flask.ext.socketio import SocketIO, emit import random import numpy as np from Algorithms import * import base64, zipfile, csv from io import StringIO, BytesIO app = Flask(__name__) app.config['SECRET_KEY'] = str(random.random()) socketio = SocketIO(app) @app.route('/') def index(): return render_template('index.html') @app.route('/static/<path:path>') def send_static(path): return send_from_directory('static', path) @app.route('/dataset',methods=['POST']) def load_data(): print(request.form['dataset']) dataset_raw = base64.b64decode(request.form['dataset']) dataset_file = BytesIO(dataset_raw) z = zipfile.ZipFile(dataset_file) s = z.read("features.csv").decode('utf-8') feature_file = StringIO(s) features = list(csv.reader(feature_file)) s = z.read("descriptions.csv").decode('utf-8') descriptions_file = StringIO(s)
LOG_FILE = 'logs/WebApp.log' # Initialises system variables, this object is the heart of the application HomeSurveillance = SurveillanceSystem.SurveillanceSystem() # Threads used to continuously push data to the client alarmStateThread = threading.Thread() facesUpdateThread = threading.Thread() monitoringThread = threading.Thread() alarmStateThread.daemon = False facesUpdateThread.daemon = False monitoringThread.daemon = False # Flask setup app = Flask('SurveillanceWebServer') app.config['SECRET_KEY'] = os.urandom(24) # Used for session management socketio = SocketIO(app) photos = UploadSet('photos', IMAGES) app.config['UPLOADED_PHOTOS_DEST'] = 'uploads/imgs' configure_uploads(app, photos) @app.route('/', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': session.pop('user', None) # Drops session everytime user tries to login if request.form['username'] != 'admin' or request.form[ 'password'] != 'admin': error = 'Invalid username or password. Please try again' else:
from flask import Flask, render_template, request from flask.ext.socketio import SocketIO, emit app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) @app.route('/') def index(): return render_template('test.html') @app.route('/socket.io.min.js') def getsocketio(): return render_template('socket.io.min.js') try: import rc_interface except ImportError: print "dummy motor control interface detected" import rc_interface_dummy as rc_interface @socketio.on('single-motor', namespace='/test') def singlemotor(message): rc_interface.singleMotorVector(message['motor'], int(message['power'])) emit('server-message', {'data': message['motor'] + " " + message['power']}) @socketio.on('dxdy', namespace='/test') def dxdy(message): for motor in message.keys(): rc_interface.singleMotorVector(motor, int(message[motor])) emit('server-message', {'data': "changed velocity"})
import psycopg2 import psycopg2.extras import json import os from flask import Flask, session, render_template, request, redirect, url_for from flask.ext.socketio import SocketIO, emit app=Flask(__name__, static_url_path='') app.config['SECRET_KEY']='secret!' socketio=SocketIO(app) def connectToDB(): connectionString='dbname=plumgig user=aziz password=PrudentGrape host=localhost' print connectionString try: return psycopg2.connect(connectionString) except: print("Can't connect to database") def date_handler(obj): return obj.isoformat() if hasattr(obj, 'isoformat') else obj def refresh_vids(choice, searchterm): conn=connectToDB() cur=conn.cursor(cursor_factory=psycopg2.extras.DictCursor) print 'refreshing vids'
from github import Github import os from flask import Flask, render_template from flask.ext.socketio import SocketIO # # Free Coding session for 2015-02-26 # Written by Matt Warren # app = Flask(__name__) app.config['SECRET_KEY'] = 'asdivbaiwubdfilsudbxv' app.debug = True socketio = SocketIO(app) thread = None hub = Github(os.environ['GITHUB_USERNAME'], os.environ['GITHUB_PASSWORD']) USERS = [ 'mfwarren' ] def get_public_events(): events = {} for u in USERS: hub_user = hub.get_user('mfwarren') events[u] = hub_user.get_public_events()[0].raw_data return events
#!/usr/bin/env python from gevent import monkey monkey.patch_all() import os, subprocess from flask import Flask from flask.ext.socketio import SocketIO, emit, disconnect from flask.ext.cors import CORS app = Flask(__name__) app.debug = False app.config['SECRET_KEY'] = 'superSecretSquirrel2015!' cors = CORS(app) socketio = SocketIO(app) termroot = '/var/www/ecwi/term/termroot' def sanitise_filename(filename, testing=False): if filename.startswith('/'): filename = filename[1:] f1 = os.path.join(termroot, filename) f2 = os.path.abspath(f1) prefix = termroot + '/' if f2.startswith(prefix): f = f2[len(prefix):] else: f = '[invalid_path]' if testing: print '%-18s' % filename, '%-36s' % f2, '%-20s' % f return f
from challenge import Challenge from flask import Flask, request, jsonify, redirect, url_for from flask.ext.socketio import SocketIO, send, emit, join_room, leave_room import random import time import threading ########### create app #################### app = Flask(__name__, static_url_path="", static_folder="static") app.config["SECRET_KEY"] = "secret!" app.debug = True socketio = SocketIO(app) ############# app state ############### available_users = { } challenges = { } # measured in seconds timeout_period = 10.0 def check_keepalive_users(timer=None): print "Purging usernames" now = time.time() deleted_users = [] for username, obj in available_users.iteritems(): if now - obj["last_keepalive"] > timeout_period: # remove that user deleted_users.append(username)
""" import ast import json import os import time import eventlet from flask import Flask, render_template, request, jsonify from flask.ext.socketio import SocketIO import helper_functions eventlet.monkey_patch() app = Flask(__name__) socketio = SocketIO(app) @app.route("/") def index(): return render_template('index.html', ) @app.route("/train") def train(): return render_template('train.html', ) @app.route("/dashboard/<string:channel>") def dashboard(channel): return render_template('dashboard.html', channel=str(channel))