Beispiel #1
def server():
    from cherrypy import wsgiserver
    app = Flask(__name__)
    # app.config.from_object('config')

    def index():
        return render_template("index.html")

    def bar():
        return render_template("bar.html")

    def sleep():
        return render_template("sleep.html")

    def up():
        return render_template("dcjsup.html")    

    def page_not_found(e):
        return render_template('404.html'), 404

    app.debug = True
    port = int(os.environ.get("PORT", 5000))'', port=port)
    d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
    server = wsgiserver.CherryPyWSGIServer(('', 8001), d)
Beispiel #2
def start():
    Start the Capo web server.
    app = Flask('capolib.web')
Beispiel #3
def start(application):
    """Start the web frontend"""

    # Make sure our views can access the main application
    global app
    app = application

    static_path = os.path.join(

    config = app.get_config()

    frontend = Flask(__name__, static_folder=static_path)

    # Make sure we crash if there's some bug in the frontend code, this is so
    # we'll find the bugs
    frontend.config['PROPAGATE_EXCEPTIONS'] = True

    frontend.add_url_rule('/', view_func=MainView.as_view('index'))
    frontend.add_url_rule('/data.json', view_func=DataView.as_view('data'))

    # Set up the route for static files
    def send_static(filename):
        return send_from_directory(static_path, filename)'', port=config.http_port)

    return frontend
Beispiel #4
def start():
    """start the flask service"""

    # create app
    app = Flask(__name__)
    app.debug = True

    #Data comes into this method:
    #'sessionStartTime' is the number of seconds since 1970 when the experiment started
    #'data' is the latest raw data, served up as a csv (each line contains up to 8 channels)
    @app.route('/data', methods=['POST'])
    def saveRatingsToGene():
        print "starting"
        print request.form

        data = request.form['data']
        sessionStartTime = request.form['sessionStartTime']

        #Do we already have a DB entry for this?
        experiment_obj = db.experiments.find_one({"sessionStartTime": sessionStartTime})

        #The data is coming in as a text CSV.
        rows = data.split('\n')
        for row in rows:
            channels = row.split(',')
            #somehow put this data into a mongo object

        return "OK"

    #This server must expose URLs to allow the user to dload the csv from the server
    #Flask gives us what we need to dload files. This sample code might be overly complicated
    #As it is built for streaming large files, which we don't necessarily need
    def generate_large_csv():
        def generate():
            for row in iter_all_rows():
                yield ','.join(row) + '\n'
        return Response(generate(), mimetype='text/csv')

    # This is where we should be able to display a list of all experiments in the mongodb
    # And use them to fill in a template (.tpl file) to allow either dloaded files
    # or perhaps, even visualized on the screen
    # Very excited about this plotting library (if it's easy to implement):
    @app.route('/', methods=['GET'])
    def hello_world():

        experiments = db.experiments.find() #get all

        for experiment in experiments:
            print "Yep we see an experiment"

        print "yep working"

    # let's go!
Beispiel #5
def run(password='', debug=False, host='', port=8282):
    SECRET_KEY = os.environ.get('CCP_FLASK_KEY', False) or _random_secret_key()
    USERNAME = os.environ.get('CCP_FLASK_ADMIN_USER', False) or 'admin'
    PASSWORD = password or 'ciscoconfparse'
    app = Flask(__name__)
    app.config.from_object(__name__), port=port, debug=False)
Beispiel #6
  def serve(self):
    Start serving.
    This is blocking.
    app = Flask(__name__)

    def hello():
      return "Hello. This is a link server."

    def stats():
      return "No stats."

    def event(event_id):"Received event {}".format(event_id))
      happened = self._execute(event_id)
      if happened:
        return "Oooh! That just happened."
        return "I'm afraid that didn't happen, Dave."
def webService(server):
    from flask import Flask, jsonify

    app = Flask(__name__)

    log = logging.getLogger('werkzeug')

    def index():
        print server.activeRelays
        return "Relays available: %s!" % (len(server.activeRelays))

    @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])
    def get_relays():
        relays = []
        for target in server.activeRelays:
            for port in server.activeRelays[target]:
                for user in server.activeRelays[target][port]:
                    if user != 'data' and user != 'scheme':
                        protocol = server.activeRelays[target][port]['scheme']
                        isAdmin = server.activeRelays[target][port][user]['isAdmin']
                        relays.append([protocol, target, user, isAdmin, str(port)])
        return jsonify(relays)

    @app.route('/ntlmrelayx/api/v1.0/relays', methods=['GET'])
    def get_info(relay):
        pass'', port=9090)
Beispiel #8
def run_webserver(destination_root_dir):
    """ Run a local """
    destination_root_dir = destination_root_dir
    if destination_root_dir.startswith("/"):
        destination_root_dir = destination_root_dir[1:]

    if destination_root_dir.endswith("/"):
        destination_root_dir = destination_root_dir[:-1]

    app = Flask(__name__)

    def serve_static_html(filename="index.html"):
        """ Serve static HTML files

        :type filename: str
        :param filename: Path to the static HTML file
        if filename.startswith(destination_root_dir):
            filename = filename.replace("{}/".format(destination_root_dir), "")
            return redirect("/{}".format(filename))

        response = make_response(send_from_directory("/{}".format(destination_root_dir), filename))
        response.cache_control.no_cache = True

        return response
Beispiel #9
class RootREST:

    def __init__(self, host, run_flask): = host
        self.run_flask = run_flask = Flask(__name__)
                 r'/*': {
                     'origins': '*',
                     'headers': ['Content-Type']
        ), url_prefix='/blueprint')

        # Root service.'/', methods=['GET'])
        def say_hello_service():
            return say_hallo()

        # Root service.'/<name>/', methods=['GET'])
        def say_hello_to_guest_service(name):
            return say_hallo(name)

        # Run Flask.
        if self.run_flask:                              # pragma: no cover
  , debug=True)    # pragma: no cover
Beispiel #10
class KodemonAPI():
	def __init__(self, SERVER_NAME='localhost:4000', db_conn_string='sqlite:///AppData/Kodemon.sqlite', debug=True): = Flask(__name__) = debug['SERVER_NAME'] = SERVER_NAME['SQLALCHEMY_DATABASE_URI'] = db_conn_string
		self.db = db

	def run(self):

	def set_routes(self):"/", methods=['GET'])
		def index():

		api_prefix = '/api/v1/' + 'messages/', methods=['GET'])
		def messages():
			return 'This will return all messages' + 'messages/keys/', methods=['GET'])
		def message_keys():
			result = []
			for m in MessageBase.query.all():
				if m.key not in result:

			return json.dumps(result) + 'messages/execution_times/<key>', methods=['GET'])
		def message_execution_times(key):
			#get query parameters (may be None)
			start_time, end_time = request.args.get('start_time'), request.args.get('end_time')

			if start_time:
				start_time = int(start_time)
				start_time = 0

			if end_time:
				end_time = int(end_time)
				end_time = sys.maxint

			#Get execution times
			times = []
			for m in MessageBase.query.filter_by(key=key):
				if start_time <= m.timestamp <= end_time:
					times.append({'execution_time': m.execution_time, 'timestamp': m.timestamp, 'token': m.token})

			result = {'key': key, 'execution_times': times}
			return json.dumps(result)
Beispiel #11
def getResult(temp):
    app = Flask(__name__)
    client = MongoClient()
    collection = client.test_database.collection_name
    db = client.test_database
    posts = db.posts
    def test():
        return jsonify({'message': "it works"})

    def returnAll():
        query = request.args.get('q')
        for eachEntry in doc:
            if query in eachEntry.keys():
        if len(results) == 0:
            for each in results:
        return jsonify({"results":results})

    def page_not_found(error):
        return jsonify({'404 err message': "enter query using"})

    if __name__ == '__main__':
Beispiel #12
class app:

    controller_list = {}

    def __init__(self, name): = Flask(name) = True = "this is a key"

    def run(self, port):
        for k, v in self.controller_list.iteritems():
            print "Start Controller: %s" % (k)"", port=port)

    def add_controller(self, controller):
        self.controller_list[] = controller
        for k, v in controller.function_list.iteritems():
            route_path = "/" + + k
            if v.type == 1:
                route_path = "/" + + k + "/<path:url_var>"
            print "Reg function: %s" % (route_path)

  , None, v.func, **v.options)
Beispiel #13
class RestServer(multiprocessing.Process):
    def __init__(self, host, port, smoker_daemon):
        :param host: host to bind the server to"
        :type host: string
        :param port: port to bind the server to"
        :type port: int
        :param smoker_daemon: instance of the smoker daemon
        :type smoker_daemon: smokerd.Smokerd
        """ = host
        self.port = port = Flask(__name__)

        self.api = Api(
        self.api.add_resource(About, '/')
        self.api.add_resource(Plugins, '/plugins', '/plugins/')
        self.api.add_resource(Plugin, '/plugins/<string:name>',
        self.api.add_resource(Processes, '/processes', '/processes/')
        self.api.add_resource(Process, '/processes/<int:id>',

        global smokerd
        smokerd = smoker_daemon

        super(RestServer, self).__init__()
        self.daemon = True

    def run(self):
        setproctitle.setproctitle('smokerd rest api server'), self.port)
Beispiel #14
def run_admin(host, port, db, password, listen):
    conn = redis.Redis(host, int(port or 6379), int(db or 0), password)
    tiger = TaskTiger(setup_structlog=True, connection=conn)
    app = Flask(__name__)
    admin = Admin(app, url='/')
    admin.add_view(TaskTigerView(tiger, name='TaskTiger', endpoint='tasktiger')), port=int(listen or 5000))
Beispiel #15
class LabyrinthServer(object) :
    def __init__(self, configFile) : = Flask(__name__)
        self.api = Api(
        logging.debug("opening config file %s for reading" % configFile)
        try :
            fp = open(configFile, 'r')
            self.config = json.load(fp)
        except IOError :
            logging.critical("Unable to open the config file %s for reading" % configFile)
        except ValueError :
            logging.critical("Unable to read the JSON object in the config file %s" % configFile)

        try :
            for endpoint in self.config['endpoints'] :
                if self.config['endpoints'][endpoint] == "JobRunner" :
                    self.api.add_resource(JobRunner, endpoint)
          "Created JobRunner endpoint for "+endpoint)
                elif self.config['endpoints'][endpoint] == "JobManager" :
                    self.api.add_resource(JobManager, endpoint)
          "Created JobManager endpoint for "+endpoint)
                else :
                    logging.error("Unknown class for endpoint '%s'.  No Class '%s' exists" % (endpoint,self.config['endpoints'][endpoint]))
        except KeyError :
            logging.critical("There is a configuration problem with the endpoints in the file '%s'" % configFile)

        try :
        except KeyError :
            logging.critical("Server Configuration does not specify a port, defaulting to port 5000")
Beispiel #16
    def video_stream_loop(self):
        flaskApp = Flask(__name__)
        running = False
        def index():
            return render_template('index.html')
        def gen():
            self.frame_count = 0
            while (self.stream_on):
                while (not self.new_stream_image):
                self.new_stream_image = False
                if (self.frame_count % self.reduse_stream_fps_by_a_factor == 0):
                    yield (b'--frame\r\n'
                        b'Content-Type: image/jpeg\r\n\r\n' + self.stream_image_jpeg.tostring() + b'\r\n\r\n')
                    self.have_yield = True
                self.frame_count += 1

        def video_feed():
            return Response(gen(),
                mimetype='multipart/x-mixed-replace; boundary=frame')
       '', port=self.streaming_port, debug=False, use_reloader=False)
Beispiel #17
class BaseApp(object):
    def __init__(self, *args, **kwargs): = Flask(__name__)

    def run(self, *args, **kwargs):*args, **kwargs)
        self.db = MongoEngine(
def web_view():
    "Setup the webview"
    app = Flask("civic_api_client")

    def template_home():
        return render_template("home.html")

    def evidence_items():
        eil1 = EvidenceItemsLister(sys.argv[2:])
        invalid_eis = eil1.get_invalid_eis()
        return render_template("evidence-items.html", invalid_eis=invalid_eis)

    def variants():
        vl1 = VariantsLister(sys.argv[2:])
        filtered_variant_details = vl1.get_filtered_variant_details()
        return render_template("variants.html", filtered_variant_details=filtered_variant_details)
Beispiel #19
def preview_runserver(args):
    output_dir = os.path.abspath(args.output)
    app = Flask(__name__)

    # TODO 3xx redirects
    # TODO 404 page
    # TODO 410 page
    def send_file(path=''):
        filename = os.path.basename(path)
        if filename == '':
            path = '%sindex.html' % path
        root, ext = os.path.splitext(path)
        if ext == '':
            path = '%s.html' % path
        print('->', path)
        return send_from_directory(output_dir, path)

    def add_header(response):
        response.cache_control.max_age = 0
        return response
Beispiel #20
def serve(directory='.', readme_file='README', port=None):
    """Starts a server to render the readme from the specified directory."""

    # Get the README filename
    filename = find_readme(directory, readme_file)
    if not filename:
        raise ValueError('No %s file found at %s' % ('README' if readme_file == 'README' else repr(readme_file), repr(directory)))

    # Flask application
    app = Flask('grip')
    app.config.from_pyfile('', silent=True)

    # Get styles from style source
    def retrieve_styles():
        if not app.config['STYLE_URL_SOURCE'] or not app.config['STYLE_URL_RE']:
        styles = _get_styles(app.config['STYLE_URL_SOURCE'], app.config['STYLE_URL_RE'])
        app.config['STYLE_URLS'] += styles
        if app.config['DEBUG_GRIP']:
            print ' * Retrieved %s style URL%s' % (len(styles), '' if len(styles) == 1 else 's')

    # Set overridden config values
    if port is not None:
        app.config['PORT'] = port

    # Views
    def index():
        return render_page(read_file(filename), filename, app.config['STYLE_URLS'])

    # Run local server['HOST'], app.config['PORT'], debug=app.debug, use_reloader=app.config['DEBUG_GRIP'])
Beispiel #21
def challenge31_and_32_server(artificial_delay=0.002,,64))):
    from flask import Flask, request, abort
    app = Flask(__name__)

    import logging
    log = logging.getLogger('werkzeug')

    def main():
        msg = ascii_to_raw(request.args.get('msg'))
        user_supplied_tag = hex_to_raw(request.args.get('tag'))
        right_tag = hmac(key, msg, raw=True)
        for i in range(len(right_tag)):
            if right_tag[i] == user_supplied_tag[i]:
        return 'ok'

    def answer():
        msg = ascii_to_raw(request.args.get('msg'))
        right_tag = hmac(key, msg, raw=True)
        return raw_to_hex(right_tag)
Beispiel #22
def runWebserver( context={}, plot_funcs = {}, database_file="database.sqlite", 
                   open_browser=False, debug=True ):
    """Runs a small local webserver using the flask module ( pip3 install flask ) serving the report. 
       When refreshing in the browser the report is updated."""
    from flask import Flask
    from flask import render_template, make_response, send_from_directory
    context['database_file'] = database_file
    app = Flask(__name__)
    setupFlaskApp(app, context=context, plot_funcs=plot_funcs, database_file=database_file )
    def main_route():
        reports = [ n[2:-5] for n in glob( "t_*.html") ]
        return render_template( "waLBerla/report_overview.html", reports=reports, **context )

    def report_route(template_name):
        template_name = "t_" + template_name + ".html"
        return render_template( template_name, **context )
    @app.route("/pdfs/<path:filename>" )
    def pdf_route( filename ):
        return send_from_directory( os.path.join( os.getcwd() , pdf_output_dir), filename)
    if open_browser:
        import webbrowser'') debug=debug )
Beispiel #23
    def run(self):
        global MASTER
        app = Flask(__name__)

        def index():
            return render_template('index.html')

        def settings():
            settingsObj = {
                "connection": "ajax"
            return jsonify(settingsObj)

        def master(value):
            global MASTER
            MASTER = float(value)
            return MASTER

        def generator(name, value):
            generatorsByName[name] = value
            return jsonify(generatorsByName)

        print "flask run", use_reloader=False, threaded=True, host="", port=4000)
Beispiel #24
def server():
    from cherrypy import wsgiserver
    app = Flask(__name__, static_folder=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'static'))
    # app = Flask(__name__)

    # @crossdomain(origin='*')
    def data_json():
        s = json.dumps([json.loads(s) for s in 
        return s

    def index_html():
        context = {
        env = Environment(loader=FileSystemLoader('templates'))
        return env.get_template('index.html').render(context)
    def sleep():
        context = {
        env = Environment(loader=FileSystemLoader('templates'))
        return env.get_template('index.html').render(context)

    print 'Listening :8001...'
    d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
    port = int(os.environ.get("PORT", 5000))'', port=8000, use_debugger=True)
    server = wsgiserver.CherryPyWSGIServer(('', 8001), d)
    except KeyboardInterrupt:
Beispiel #25
class WebApp:
    def __init__(self, www, db_path):
        self.www = www
        self.db = db_connector.DB(db_path)
        self.cache = cache.Cache(self.db)

    def start(self):
        host = self.www['host']
        port = self.www['port']
        static_folder = self.www['static_folder']
        template_folder = self.www['template_folder']
        debug = self.www['debug'] = Flask(__name__,

        router.RulesRouter(, self.db, self.cache).configure()'craft-server-start'), port=port, debug=debug, use_reloader=False)

    def stop(self):
        func = request.environ.get('werkzeug.server.shutdown')
        if func is None:
            raise RuntimeError('Not running with the Werkzeug Server')

    def html_dependencies(self):
        deps = self.www['ext']['path'], deps['file'])
Beispiel #26
def FlaskRunner(q):

    queue = q
    app = Flask(__name__)

    def index():
        return render_template('index.html')

    def gen():
        while True:
            if not queue.empty():
                frameaux = queue.get()
                if frameaux is not None:
                    ret, jpeg = cv2.imencode('.jpeg', frameaux)
                    frame = jpeg.tostring()

                if frame is not None:
                    yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
            #Slow down the streaming

    def video_feed():
        return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')'', port=7777, debug=False)
Beispiel #27
def serve(py_exec=None):
    parser = argparse.ArgumentParser()
    parser.add_argument("--python", default="python")
    args = parser.parse_args()

    py_exec = args.python

    app = Flask("touchandgo")

    def redirect_to(name, season=None, episode=None):
        interface = get_interface()
        command = "%s \"%s\" " % (py_exec, name)
        if season is not None:
            command += "%s %s " % (season, episode)
        command += "--daemon"
        print command
        process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT)
        port = 8888
        return redirect("http://%s:%s" % (interface, port))

    app.debug = True"")
Beispiel #28
class FyPress():
    def __init__(self, config, manager=False):
        from flask.ext.babel import Babel
        from utils.mysql import FlaskFyMySQL

        self.prepared = False
        self.config = config = Flask(
        ) = ProxyFix(
        self.babel = Babel(
        self.db    = FlaskFyMySQL(

        if not manager:

    def run(self, host='', port=5000):
        if self.prepared == False:
            self.prepare(), port=port, debug=self.config.DEBUG)

    def prepare(self):
        local.fp = self
        self.prepared = True
        def before_request():
            g.start = time.time()
        if self.config.DEBUG:
            def after_request(response):
                diff = time.time() - g.start
                if (response.response):
                    response.headers["Execution-Time"] = str(diff)
                return response['UPLOAD_DIRECTORY_URL']+'<filename>', 'FyPress.uploaded_file', build_only=True) = SharedDataMiddleware(, {['UPLOAD_DIRECTORY_URL']:['UPLOAD_DIRECTORY']})


    def blueprint(self):
        ### Blueprints ###
        from user import user_blueprint
        from admin import admin_blueprint
        from public import public_blueprint

        ### Load Blueprints ###

    def uploaded_file(filename):
        return send_from_directory(['UPLOAD_DIRECTORY'], filename)
Beispiel #29
class RootREST:

    def __init__(self, host, run_flask, port): = host
        self.port = port
        self.run_flask = run_flask = Flask(__name__)
                 r'/*': {
                     'origins': '*',
                     'headers': ['Content-Type']
        #blueprintRest = BlueprintRest(), url_prefix='/blueprint')'blueprint', __name__), url_prefix='/blueprint')

        # Root service.'/')
        def landing():
            return core.landing_message()

        # Run Flask.
        if self.run_flask:
  , port=self.port)
Beispiel #30
    def _runFlask(self, gw, port):
        :param gw: Gateway
        :type gw: smsframework.Gateway.Gateway
        # Init flask
        app = Flask(__name__)
        app.debug = True
        app.testing = True

        # Register gateway receivers
        gw.receiver_blueprints_register(app, prefix='/sms')

        # Stop manually
        @app.route('/kill', methods=['GET','POST'])
        def kill():
            func = request.environ.get('werkzeug.server.shutdown')
            if func is None:
                raise RuntimeError('Not running with the Werkzeug Server')
            return ''

        # Run'', port, threaded=False, use_reloader=False, passthrough_errors=True)