Example #1
1
def init(config_args):
    app = Flask(__name__)
    slack = flask_slack.Slack(app)
    config = slackbot.load_config(config_args.config)
    if not config:
        slackbot.save_config()
        print """Looks like we can't find config.yaml-
        we've gone ahead and generated a sample one for you in the current directory.
        Please edit it according to the instructions in it and re-run parsely_slackbot!"""
        sys.exit()
    parsely_bot = slackbot.SlackBot(config)
    parsely_alert = alerts.SlackAlert(parsely_bot)
    # run this on a timer so that trending alerts don't happen the moment the bot is kicked off
    alerts_thread = threading.Timer(300.0, parsely_alert.run)
    alerts_thread.daemon = True
    alerts_thread.start()

    @slack.command("parsely", token=config["slack_token"], team_id=config["team_id"], methods=["POST"])
    def parsely(text=None, channel=None, **kwargs):
        parsed_commands = parsely_bot.parse(text)
        if not parsed_commands:
            return slack.response("Sorry, I didn't understand that query! Maybe try /parsely help?")
        if parsed_commands["meta"] == "help":
            return slack.response(parsely_bot.help())
        post_list, header_text = parsely_bot.realtime(parsed_commands)
        if not header_text:
            return slack.response("Sorry, didn't recognize that command!")
        if not post_list:
            return slack.response("Sorry, no posts found with that query!")
        attachments = parsely_bot.build_meta_attachments(post_list, header_text)
        return slack.response(text="", response_type="in_channel", attachments=attachments)

    app.add_url_rule("/", view_func=slack.dispatch)
    app.run("0.0.0.0", config_args.port, debug=False, threaded=True)
Example #2
1
class clientmain:

    JSON_HEADER = {"Content-Type": "application/json"}

    def __init__(self, server_ip, server_port, local_ip, local_folder_path, local_ctl_port, local_trans_port):

        self.server_ip = server_ip  # 192.168.1.10
        self.server_port = server_port  # 8000
        self.local_ip = local_ip  # 192.168.1.15
        self.local_folder_path = local_folder_path  # /home/shaw/Develop/snlab/simple-tracker/client
        self.local_ctl_port = local_ctl_port  # 8000
        self.local_trans_port = local_trans_port  # 9000
        self.stc = STClientInstance(
            "http://" + self.server_ip + ":" + str(self.server_port),
            self.local_folder_path,
            "http://" + self.local_ip + ":" + str(self.local_trans_port),
        )
        self.swd = SimpleWatchDog(self.local_folder_path, self.stc, self.local_ip)
        self.web_app = Flask(__name__)
        self.web_app.add_url_rule("/transfer", "transfer", self.transfer, methods=["post"])
        self.threads = []

    def success(self):
        return '{"status":"OK"}', 200, clientmain.JSON_HEADER

    def run(self):
        self.stc.register(self.local_ip, str(self.local_ctl_port))
        self.stc.update(self.local_ip)
        t1 = threading.Thread(target=self.start_HTTPServer)
        t2 = threading.Thread(target=self.start_simplewatchdog)
        t3 = threading.Thread(target=self.start_flask_server)
        self.threads.append(t1)
        self.threads.append(t2)
        self.threads.append(t3)
        for t in self.threads:
            t.setDaemon(True)
            t.start()
        try:
            while True:
                pass
        except KeyboardInterrupt:
            self.stc.deregister(self.local_ip)

    def start_HTTPServer(self):
        global ROUTES
        ROUTES.append(("/", self.local_folder_path))
        httpd = HTTPServer(("127.0.0.1", self.local_trans_port), MyHandler)
        httpd.serve_forever()
        print("start HTTPServer")

    def start_simplewatchdog(self):
        self.swd.start()
        print("start simplewatchdog")

    def transfer(self):
        print("I received transfer message")
        return self.success()

    def start_flask_server(self):
        self.web_app.run(host="0.0.0.0", port=self.local_ctl_port)
Example #3
1
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)
Example #4
1
class App(object):
    """Represents the Flask App"""

    def __init__(self):
        self.dir = os.path.dirname(__file__)

        self.app = Flask(__name__, static_folder="../app")
        self.api = Api(self.app, prefix="/api/v1")

        self.app.add_url_rule("/bower_components/<path:path>", "bower_components", self.bower)

        self.api.add_resource(canyonero.Root, "/")
        self.api.add_resource(canyonero.NameSetEndpointIndex, "/nameset")
        self.api.add_resource(canyonero.NameSetEndpointDetail, "/nameset/<string:id>")
        self.api.add_resource(canyonero.NameSetEndpointAbbrev, "/nameset/<string:id>/abbrev")
        self.api.add_resource(canyonero.NameSetEndpointIgnore, "/nameset/<string:id>/ignore")
        self.api.add_resource(canyonero.NameSetEndpointCanon, "/nameset/<string:id>/canon")
        self.api.add_resource(canyonero.ClusterEndpointIndex, "/nameset/<string:id>/cluster")
        self.api.add_resource(canyonero.ClusterEndpointDetail, "/nameset/<string:id>/cluster/<string:key>")

    def bower(self, path):
        fullPath = os.path.join(self.dir, "../bower_components", path)
        return send_file(fullPath)

    def run(self, debug):
        self.app.run(debug=debug)

    def absoluteUrl(self, relative):
        f = "{0}{1}" if relative[0] == "/" else "{0}/{1}"
        return f.format(self.api.prefix, relative)
Example #5
1
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()
Example #6
1
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))
Example #7
1
class streamStarter:
    def __init__(self):
        self.config = get_config()
        config_check(self.config)
        self.libs = parse_libraries(self.config["libraries"])
        self.app = Flask(__name__)
        self.add_routes()
        self.app.run(debug=True, host=self.config["serverIP"], port=int(self.config["serverPort"]))

    def add_routes(self):
        @self.app.route("/")
        def index():
            result = ""
            try:
                for lib in self.libs.keys():
                    result += lib + ";"
            except Exception, e:
                result = "Server Error\n"
                log("error", traceback.format_exc())
            # XXX:This is not nice hack to strip last delimiter. Review answer format
            result = result.rstrip(";")
            return result

        @self.app.route("/ahoj", methods=["GET"])
        def ahoj():
            return "Hello"

        @self.app.route("/svet", methods=["GET"])
        def svet():
            return "World"
Example #8
0
class RESTAPI(object):
    """
    REST API for OpenCog

    Implemented using the Flask micro-framework and Flask-RESTful extension

    Documentation:
    http://wiki.opencog.org/w/REST_API

    Prerequisites:
    Flask, mock, flask-restful, six, flask-restful-swagger

    Default endpoint: http://127.0.0.1:5000/api/v1.1/
    (Replace 127.0.0.1 with the IP address of the server if necessary)

    Example request: http://127.0.0.1:5000/api/v1.1/atoms?type=ConceptNode

    See: opencog/python/web/api/exampleclient.py for detailed examples of
    usage, and review the method definitions in each resource for request/
    response specifications.
    """

    def __init__(self, atomspace):
        self.atomspace = atomspace

        # Initialize the web server and set the routing
        self.app = Flask(__name__, static_url_path="")
        self.api = swagger.docs(Api(self.app), apiVersion="1.1", api_spec_url="/api/v1.1/spec")

        # Allow Cross Origin Resource Sharing (CORS) so that javascript apps
        # can use this API from other domains, ports and protocols.
        self.cors = CORS(self.app)

        # Create and add each resource
        atom_collection_api = AtomCollectionAPI.new(self.atomspace)
        atom_types_api = TypesAPI
        shell_api = ShellAPI
        scheme_api = SchemeAPI.new(self.atomspace)

        self.api.add_resource(atom_collection_api, "/api/v1.1/atoms", "/api/v1.1/atoms/<int:id>", endpoint="atoms")
        self.api.add_resource(atom_types_api, "/api/v1.1/types", endpoint="types")
        self.api.add_resource(shell_api, "/api/v1.1/shell", endpoint="shell")
        self.api.add_resource(scheme_api, "/api/v1.1/scheme", endpoint="scheme")

    def run(self, host="127.0.0.1", port=5000):
        """
        Runs the REST API

        :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
                     have the server available externally as well. Defaults to
                     ``'127.0.0.1'``.
        :param port: the port of the webserver. Defaults to ``5000``
        """
        self.app.run(debug=False, host=host, port=port)

    def test(self):
        """
        Returns a test client for the REST API
        """
        return self.app.test_client()
Example #9
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)
Example #10
0
File: ce.py Project: CelloCello/Ce
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)
Example #11
0
class HTTPServer(object):

    FORM_DATA_MIME = "application/x-www-form-urlencoded"
    JSON_DATA_MIME = "application/json"

    def __init__(self, jockey):
        self.jockey = jockey
        self.app = Flask("horse-http-server")
        self.app.add_url_rule("/", "handler", self.handle_request, methods=["GET", "POST"], defaults={"path": ""})
        self.app.add_url_rule("/<path:path>", "handler", self.handle_request, methods=["GET", "POST"])

    def handle_request(self, path):
        logging.info("Inbound request: {0}".format(path))
        if path == "command":
            response = self.jockey.handle_command(request.form)
        else:
            if request.method == "GET":
                response = self.jockey.handle_http_get(path, request.args)
            elif request.method == "POST":
                if request.headers["Content-Type"] == self.FORM_DATA_MIME:
                    response = self.jockey.handle_http_post(path, request.form)
                elif request.headers["Content-Type"] == self.JSON_DATA_MIME:
                    data = json.loads(request.body)
                    response = self.jockey.handle_http_post(path, data)
        logging.info("Outbound response: {0}".format(response))
        if response is None:
            response = ""
        return str(response)

    def start(self):
        def run(*args):
            self.app.run(host="0.0.0.0", port=5000)

        logging.info("Starting HTTP server on new thread.")
        thread.start_new_thread(run, ())
Example #12
0
class RESTInterface(object):
    def __init__(self, ip_addr, port, conn_obj, output_dir):
        self.conn = conn_obj
        self.ip_addr = ip_addr
        self.port = port
        self.output_dir = output_dir
        self.app = Flask("eyes")

    def status(self):
        resp = json.jsonify(status=str(self.conn))
        resp.status_code = 200
        return resp

    def start_test(self, test_num):
        self.conn.remove_handler()
        test_str = "test-{0}".format(test_num)
        filename = os.path.join(os.path.abspath(self.output_dir), test_str)
        self.conn.add_handler(filename)
        resp = json.jsonify(status="START - SUCCESS")
        resp.status_code = 200
        return resp

    def run_test(self):
        json_data = request.get_json(force=True)
        status = self.conn.run_cmd(json_data["cmd_str"])
        resp = None
        if status is True:
            resp = json.jsonify(status="TEST - SUCCESS")
            resp.status_code = 200
        else:
            resp = json.jsonify(status="TEST - FAILED")
            resp.status_code = 520
        return resp

    def stop_test(self):
        self.conn.remove_handler()
        resp = json.jsonify(status="STOP - SUCCESS")
        resp.status_code = 200
        return resp

    def shutdown(self):
        self.conn.stop()
        resp = json.jsonify(status="SHUTDOWN - SUCCESS")
        resp.status_code = 200
        return resp

    def reconnect(self):
        self.conn.reconnect()
        resp = json.jsonify(status="Reconnect - SUCCESS")
        resp.status_code = 200
        return resp

    def start(self):
        self.app.add_url_rule("/", "index", self.status)
        self.app.add_url_rule("/start_test/<int:test_num>", "start_test", self.start_test, methods=["POST"])
        self.app.add_url_rule("/stop_test", "stop_test", self.stop_test)
        self.app.add_url_rule("/run_test", "run_test", self.run_test, methods=["POST"])
        self.app.add_url_rule("/shutdown", "shutdown", self.shutdown, methods=["POST"])
        self.app.add_url_rule("/reconnect", "reconnect", self.reconnect, methods=["POST"])
        self.app.run(host=self.ip_addr, port=self.port)
Example #13
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)
Example #14
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)
Example #15
0
def start():
    """
    Start the Capo web server.
    """
    app = Flask("capolib.web")
    views.init_views(app)
    app.run()
Example #16
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)
Example #17
0
 def startService(self):
     app = Flask(__name__)
     app.config["UPLOADDIR"] = self.tempDirectory
     app.config["LOGGER"] = self.restUploadServiceLogger
     app.register_blueprint(uploadAPI)
     self.logger.info("Starting Flask with upload directory: " + self.tempDirectory)
     app.run(threaded=True)
Example #18
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)
def display_duplicates(duplicates, delete_cb):
    with TemporaryDirectory() as folder:
        # Generate all of the HTML files
        chunk_size = 25
        for i, dups in enumerate(chunked(duplicates, chunk_size)):
            with open("{}/{}.html".format(folder, i), "w") as f:
                f.write(render(dups, current=i, total=int(len(duplicates) / chunk_size)))

        webbrowser.open("file://{}/{}".format(folder, "0.html"))

        app = Flask(__name__)

        @app.route("/picture/<path:file_name>", methods=["DELETE"])
        def delete_picture(file_name):
            print("Moving file")
            file_name = "/" + file_name

            try:
                print(file_name)
                print(TRASH + os.path.basename(file_name))
                shutil.move(file_name, TRASH + os.path.basename(file_name))
                delete_cb(file_name)
            except FileNotFoundError:
                return "False"

            return "True"

        app.run()
Example #20
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"])
Example #21
0
class Core(object):
    def __init__(self, host, port, debug):
        self.host = host
        self.port = int(port)
        self.debug = debug
        self.backend = None
        self.backend_settings = None

    def load_backend(self):
        self.backend = self.backend.Backend(**self.backend_settings)

    def run(self):

        from leselys.reader import Reader

        self.reader = Reader()

        self.app = Flask(__name__)
        self.app.config["SECRET_KEY"] = os.urandom(24)
        self.signer = TimestampSigner(self.app.config["SECRET_KEY"])
        self.cache = SimpleCache()

        from leselys import views
        from leselys import api

        self.app.run(host=self.host, port=int(self.port), debug=self.debug)
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)
Example #23
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)
Example #24
0
def serve(directory=".", readme_file="README"):
    """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("config.py")
    app.config.from_pyfile("../local_config.py", silent=True)

    # Views
    @app.route("/")
    def index():
        return render_page(read_file(filename), filename)

    # Run local server
    app.run(
        app.config["HOST"],
        app.config["PORT"],
        debug=app.config["DEBUG"],
        use_reloader=app.config.get("DEBUG_GRIP", False),
    )
Example #25
0
    def run_webapp():
        from flask import Flask

        flask_app = Flask(__name__, static_url_path="")
        flask_app.register_blueprint(graphsvc.graph_endpoints, url_prefix="/graph")
        DEFAULT_LOGGER.info(flask_app.url_map)
        flask_app.run()
def cmd():
    import argparse

    parser = argparse.ArgumentParser(description="Capitains Nemo CTS UI")
    parser.add_argument("endpoint", metavar="endpoint", type=str, help="CTS API Endpoint")
    parser.add_argument("--port", type=int, default=8000, help="Port to use for the HTTP Server")
    parser.add_argument("--host", type=str, default="127.0.0.1", help="Host to use for the HTTP Server")
    parser.add_argument("--inventory", type=str, default=None, help="Inventory to request from the endpoint")
    parser.add_argument("--css", type=str, default=None, nargs="*", help="Full path to secondary css file")
    parser.add_argument(
        "--groupby", type=int, default=25, help="Number of passage to group in the deepest level of the hierarchy"
    )
    parser.add_argument("--debug", action="store_true", default=False, help="Set-up the application for debugging")

    args = parser.parse_args()

    if args.endpoint:
        app = Flask(__name__)
        # We set up Nemo
        nemo = Nemo(
            app=app,
            name="nemo",
            base_url="",
            css=args.css,
            inventory=args.inventory,
            api_url=args.endpoint,
            chunker={"default": lambda x, y: Nemo.level_grouper(x, y, groupby=args.groupby)},
        )

        # We run the app
        app.debug = args.debug
        app.run(port=args.port, host=args.host)
Example #27
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()
class Server(object):
    def __init__(self, modules):
        self.router = router.Router()
        self.app = Flask(__name__)
        self.api = api.Api(modules, self.app, self.router)

    def run(self, *args, **kwargs):
        self.app.run(*args, **kwargs)
Example #29
0
def serve():
    """
    Serve static pages using flask app
    """
    app = Flask(__name__, template_folder=".")
    app.add_url_rule("/", view_func=IndexView.as_view("index"))
    app.add_url_rule("/api/<path:filename>", view_func=ApiView.as_view("api"))
    app.run(debug=True)
Example #30
0
def main():
    if len(sys.argv) > 1:
        _mockdown.root = sys.argv[1]

    app = Flask(__name__)
    app.config["DEBUG"] = True
    app.register_blueprint(mockdown_app)
    app.run()