import click from os import environ from flask import current_app from flask.cli import with_appcontext, run_command class PrefixMiddleware(object): def __init__(self, app, prefix=""): self.app = app self.prefix = prefix def __call__(self, environ, start_response): if environ["PATH_INFO"].startswith(self.prefix): environ["PATH_INFO"] = environ["PATH_INFO"][len(self.prefix) :] environ["SCRIPT_NAME"] = self.prefix return self.app(environ, start_response) else: start_response("404", [("Content-Type", "text/plain")]) return ["This url does not belong to the app.".encode()] @click.command() @click.option("--host", help="set hostname to listen on", default="127.0.0.1", show_default=True) @click.option("--port", help="set port to listen on", type=int, default=5000, show_default=True) @click.option("--debug", help="run in debug mode", is_flag=True) @with_appcontext @click.pass_context def run(ctx, host, port, debug): """Run Flaschengeist using a development server.""" from flaschengeist.config import config current_app.wsgi_app = PrefixMiddleware(current_app.wsgi_app, prefix=config["FLASCHENGEIST"].get("root", "")) if debug: environ["FLASK_DEBUG"] = "1" environ["FLASK_ENV"] = "development" ctx.invoke(run_command, reload=True, host=host, port=port, debugger=debug)