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

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

    @app.route("/bar/")
    def bar():
        return render_template("bar.html")

    @app.route("/sleep/")
    def sleep():
        return render_template("sleep.html")

    @app.route("/up/")
    def up():
        return render_template("dcjsup.html")    

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

    app.debug = True
    port = int(os.environ.get("PORT", 5000))
    app.run(host='0.0.0.0', port=port)
    d = wsgiserver.WSGIPathInfoDispatcher({'/': app})
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8001), d)
Beispiel #2
0
def start():
    """
    Start the Capo web server.
    """
    app = Flask('capolib.web')
    views.init_views(app)
    app.run()
Beispiel #3
0
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(
        os.path.dirname(os.path.abspath(__file__)),
        '../static/'
    )

    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
    @frontend.route('/static/<path:filename>')
    def send_static(filename):
        return send_from_directory(static_path, filename)

    frontend.run(host='0.0.0.0', port=config.http_port)

    return frontend
Beispiel #4
0
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
    #http://flask.pocoo.org/docs/patterns/streaming/
    @app.route('/large.csv')
    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):
    # http://code.shutterstock.com/rickshaw/
    @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!
    app.run()
Beispiel #5
0
def run(password='', debug=False, host='127.0.0.1', 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__)
    app.run(host=host, port=port, debug=False)
Beispiel #6
0
  def serve(self):
    """
    Start serving.
    This is blocking.
    """
    logger.info("Serving.")
    app = Flask(__name__)

    @app.route("/")
    def hello():
      return "Hello. This is a link server."

    @app.route("/stats")
    def stats():
      return "No stats."

    @app.route("/event/<event_id>")
    def event(event_id):
      logger.info("Received event {}".format(event_id))
      happened = self._execute(event_id)
      if happened:
        return "Oooh! That just happened."
      else:
        return "I'm afraid that didn't happen, Dave."

    app.run()
def webService(server):
    from flask import Flask, jsonify

    app = Flask(__name__)

    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)

    @app.route('/')
    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

    app.run(host='0.0.0.0', port=9090)
Beispiel #8
0
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__)

    @app.route("/")
    @app.route("/<path:filename>")
    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

    app.run()
Beispiel #9
0
class RootREST:

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

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

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

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

		self.app.config['SERVER_NAME'] = SERVER_NAME
		
		self.app.config['SQLALCHEMY_DATABASE_URI'] = db_conn_string
		self.db = db
		
		self.db.init_app(self.app)
		self.set_routes()

	def run(self):
		self.app.run()

	def set_routes(self):
		@self.app.route("/", methods=['GET'])
		def index():
			return self.app.send_static_file('index.html')


		api_prefix = '/api/v1/'
		
		@self.app.route(api_prefix + 'messages/', methods=['GET'])
		def messages():
			return 'This will return all messages'

		@self.app.route(api_prefix + 'messages/keys/', methods=['GET'])
		def message_keys():
			result = []
			for m in MessageBase.query.all():
				if m.key not in result:
					result.append(m.key)

			return json.dumps(result)

		@self.app.route(api_prefix + '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)
			else:
				start_time = 0

			if end_time:
				end_time = int(end_time)
			else:
				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
0
def getResult(temp):
    result_final=[]
    app = Flask(__name__)
    client = MongoClient()
    collection = client.test_database.collection_name
    preprocessInputData()
    db = client.test_database
    posts = db.posts
    @app.route('/',methods=['GET'])
    def test():
        return jsonify({'message': "it works"})

    @app.route('/search',methods=['GET'])
    def returnAll():
        results=[]
        query = request.args.get('q')
        doc=db.test_database.find();
        for eachEntry in doc:
            if query in eachEntry.keys():
                results.append(eachEntry[query])
        if len(results) == 0:
            results=findTopResultsForQuery(query)
            for each in results:
                db["test_database"].insert_one({query:each})
        return jsonify({"results":results})

    @app.errorhandler(404)
    def page_not_found(error):
        return jsonify({'404 err message': "enter query using http://127.0.0.1:5000/search?q=QUERY"})

    if __name__ == '__main__':
        app.run(debug=True)
Beispiel #12
0
class app:
    """
    """

    controller_list = {}

    def __init__(self, name):
        self.app = Flask(name)
        self.app.debug = True
        self.app.secret_key = "this is a key"
        # app.run(host='0.0.0.0')

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

        self.app.run(host="0.0.0.0", port=port)

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

            self.app.add_url_rule(route_path, None, v.func, **v.options)
Beispiel #13
0
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
        """
        self.host = host
        self.port = port
        self.app = Flask(__name__)

        self.api = Api(self.app)
        self.api.add_resource(About, '/')
        self.api.add_resource(Plugins, '/plugins', '/plugins/')
        self.api.add_resource(Plugin, '/plugins/<string:name>',
                              '/plugins/<string:name>/')
        self.api.add_resource(Processes, '/processes', '/processes/')
        self.api.add_resource(Process, '/processes/<int:id>',
                              '/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.app.run(self.host, self.port)
Beispiel #14
0
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'))
    app.run(debug=True, port=int(listen or 5000))
Beispiel #15
0
class LabyrinthServer(object) :
    def __init__(self, configFile) :
        self.app = Flask(__name__)
        self.api = Api(self.app)
        logging.debug("opening config file %s for reading" % configFile)
        try :
            fp = open(configFile, 'r')
            self.config = json.load(fp)
            fp.close()
        except IOError :
            logging.critical("Unable to open the config file %s for reading" % configFile)
            exit(10)
        except ValueError :
            logging.critical("Unable to read the JSON object in the config file %s" % configFile)
            exit(10)

        try :
            for endpoint in self.config['endpoints'] :
                if self.config['endpoints'][endpoint] == "JobRunner" :
                    self.api.add_resource(JobRunner, endpoint)
                    logging.info("Created JobRunner endpoint for "+endpoint)
                elif self.config['endpoints'][endpoint] == "JobManager" :
                    self.api.add_resource(JobManager, endpoint)
                    logging.info("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)
            exit(10)

        try :
            self.app.run(port=self.config['port'])
        except KeyError :
            logging.critical("Server Configuration does not specify a port, defaulting to port 5000")
            self.app.run(port=5000)
Beispiel #16
0
    def video_stream_loop(self):
        flaskApp = Flask(__name__)
        running = False
        
        @flaskApp.route('/')
        def index():
            return render_template('index.html')
    
        def gen():
            self.frame_count = 0
            while (self.stream_on):
                while (not self.new_stream_image):
                    time.sleep(0.001)
                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
                

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

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

    @app.route("/")
    def template_home():
        return render_template("home.html")

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

    @app.route("/variants")
    def variants():
        vl1 = VariantsLister(sys.argv[2:])
        vl1.parse_args()
        vl1.create_filtered_variants_list()
        filtered_variant_details = vl1.get_filtered_variant_details()
        return render_template("variants.html", filtered_variant_details=filtered_variant_details)

    app.run(debug=True)
Beispiel #19
0
def preview_runserver(args):
    output_dir = os.path.abspath(args.output)
    app = Flask(__name__)

    # TODO 3xx redirects
    # TODO 404 page
    # TODO 410 page
    @app.route('/')
    @app.route('/<path:path>')
    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)

    @app.after_request
    def add_header(response):
        response.cache_control.max_age = 0
        return response

    app.run(port=3567)
Beispiel #20
0
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('default_config.py')
    app.config.from_pyfile('local_config.py', silent=True)

    # Get styles from style source
    @app.before_first_request
    def retrieve_styles():
        if not app.config['STYLE_URL_SOURCE'] or not app.config['STYLE_URL_RE']:
            return
        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
    @app.route('/')
    def index():
        return render_page(read_file(filename), filename, app.config['STYLE_URLS'])

    # Run local server
    app.run(app.config['HOST'], app.config['PORT'], debug=app.debug, use_reloader=app.config['DEBUG_GRIP'])
Beispiel #21
0
def challenge31_and_32_server(artificial_delay=0.002, key=Random.new().read(random.randint(16,64))):
    
    from flask import Flask, request, abort
    app = Flask(__name__)

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

    @app.route("/")
    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]:
                time.sleep(artificial_delay)  
            else:
                abort(500)
        return 'ok'

    @app.route("/answer")
    def answer():
        msg = ascii_to_raw(request.args.get('msg'))
        right_tag = hmac(key, msg, raw=True)
        return raw_to_hex(right_tag) 

    app.run(threaded=True)
Beispiel #22
0
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__)
    app.debug=True
    setupFlaskApp(app, context=context, plot_funcs=plot_funcs, database_file=database_file )
    
    @app.route("/")
    def main_route():
        reports = [ n[2:-5] for n in glob( "t_*.html") ]
        return render_template( "waLBerla/report_overview.html", reports=reports, **context )

    @app.route("/<template_name>")
    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
        webbrowser.open('http://127.0.0.1:5000/')

    app.run( debug=debug )
Beispiel #23
0
    def run(self):
        global MASTER
        app = Flask(__name__)

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

        @app.route("/settings")
        def settings():
            settingsObj = {
                "connection": "ajax"
            }
            return jsonify(settingsObj)

        @app.route("/master/<string:value>")
        def master(value):
            global MASTER
            MASTER = float(value)
            return MASTER

        @app.route("/generator/<string:name>/<int:value>")
        def generator(name, value):
            generatorsByName[name] = value
            updateGenerators()
            return jsonify(generatorsByName)

        print "flask run"
        app.run(debug=False, use_reloader=False, threaded=True, host="0.0.0.0", port=4000)
Beispiel #24
0
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__)

    @app.route('/data.json')
    # @crossdomain(origin='*')
    def data_json():
        s = json.dumps([json.loads(s) for s in 
            list(redis.smembers('fitbit'))])
        return s

    @app.route('/')
    def index_html():
        context = {
        }
        env = Environment(loader=FileSystemLoader('templates'))
        return env.get_template('index.html').render(context)
    
    @app.route('/sleep/')
    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))    
    app.run(host='0.0.0.0', port=8000, use_debugger=True)
    server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8001), d)
    try:
        server.start()
    except KeyboardInterrupt:
        server.stop()
Beispiel #25
0
class WebApp:
    def __init__(self, www, db_path):
        self.www = www
        self.db = db_connector.DB(db_path)
        self.html_dependencies()
        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']

        self.app = Flask(__name__,
                         static_folder=static_folder,
                         template_folder=template_folder)

        router.RulesRouter(self.app, self.db, self.cache).configure()

        logger.info('craft-server-start')
        self.app.run(host=host, port=port, debug=debug, use_reloader=False)

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

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

    queue = q
    app = Flask(__name__)

    @app.route('/')
    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
            time.sleep(0.15)

    @app.route('/video_feed')
    def video_feed():
        return Response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame')

    app.run(host='0.0.0.0', port=7777, debug=False)
Beispiel #27
0
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")

    @app.route("/<name>")
    @app.route("/<name>/<season>/<episode>")
    def redirect_to(name, season=None, episode=None):
        interface = get_interface()
        command = "%s touchandgo.py \"%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)
        sleep(10)
        port = 8888
        return redirect("http://%s:%s" % (interface, port))

    app.debug = True
    app.run(host="0.0.0.0")
Beispiel #28
0
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
        self.app = Flask(
            __name__,
            template_folder=self.config.TEMPLATE_FOLDER,
            static_folder=self.config.STATIC_FOLDER
        )
        self.app.config.from_object(config)
        self.app.wsgi_app = ProxyFix(self.app.wsgi_app)
        self.babel = Babel(self.app)
        self.db    = FlaskFyMySQL(self.app)

        if not manager:
            self.prepare()

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

    def prepare(self):
        local.fp = self
        self.prepared = True

        @self.app.before_request
        def before_request():
            g.start = time.time()
            
        if self.config.DEBUG:
            @self.app.after_request
            def after_request(response):
                diff = time.time() - g.start
                if (response.response):
                    response.headers["Execution-Time"] = str(diff)
                return response

        self.app.add_url_rule(self.app.config['UPLOAD_DIRECTORY_URL']+'<filename>', 'FyPress.uploaded_file', build_only=True)
        self.app.wsgi_app = SharedDataMiddleware(self.app.wsgi_app, {self.app.config['UPLOAD_DIRECTORY_URL']: self.app.config['UPLOAD_DIRECTORY']})

        self.blueprint()

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

        ### Load Blueprints ###
        self.app.register_blueprint(user_blueprint)
        self.app.register_blueprint(admin_blueprint)
        self.app.register_blueprint(public_blueprint)

    @staticmethod
    def uploaded_file(filename):
        return send_from_directory(self.app.config['UPLOAD_DIRECTORY'], filename)
Beispiel #29
0
class RootREST:

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

        # Root service.
        @self.app.route('/')
        def landing():
            return core.landing_message()

        # Run Flask.
        if self.run_flask:
            self.app.run(host=self.host, port=self.port)
Beispiel #30
0
    def _runFlask(self, gw, port):
        """
        :param gw: Gateway
        :type gw: smsframework.Gateway.Gateway
        :return:
        :rtype:
        """
        # 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')
            func()
            return ''

        # Run
        app.run('0.0.0.0', port, threaded=False, use_reloader=False, passthrough_errors=True)