Ejemplo n.º 1
0
def launch() -> None:  # pragma: no cover
    """Launch the RAPyDo-based HTTP API server"""

    mywait()

    if initializing():
        print_and_exit(
            "Please wait few more seconds: initialization is still in progress"
        )

    current_app = Env.get("FLASK_APP", "").strip()
    if not current_app:
        os.environ["FLASK_APP"] = f"{current_package}.__main__"

    args = [
        "run",
        "--host",
        BIND_INTERFACE,
        "--port",
        Env.get("FLASK_PORT", "8080"),
        "--reload",
        "--no-debugger",
        "--eager-loading",
        "--with-threads",
    ]

    # Call to untyped function "FlaskGroup" in typed context
    fg_cli = FlaskGroup()  # type: ignore
    # Call to untyped function "main" in typed context
    fg_cli.main(prog_name="restapi", args=args)  # type: ignore
    log.warning("Server shutdown")
Ejemplo n.º 2
0
def main(args):

    current_app = os.environ.get('FLASK_APP')
    if current_app is None or current_app.strip() == '':
        os.environ['FLASK_APP'] = '{}.__main__'.format(current_package)

    fg_cli = FlaskGroup()
    options = {'prog_name': 'restapi', 'args': args}

    # cannot catch for CTRL+c
    fg_cli.main(**options)
Ejemplo n.º 3
0
def main(args):  # pragma: no cover

    current_app = os.getenv("FLASK_APP")
    if current_app is None or current_app.strip() == "":
        os.environ["FLASK_APP"] = f"{current_package}.__main__"

    fg_cli = FlaskGroup()
    options = {"prog_name": "restapi", "args": args}

    # cannot catch for CTRL+c
    fg_cli.main(**options)
Ejemplo n.º 4
0
def handler(event, context):
    """ Lambda event handler, invokes the WSGI wrapper and handles command invocation
    """
    if "_serverless-wsgi" in event:
        import shlex
        import subprocess
        from werkzeug._compat import StringIO, to_native

        native_stdout = sys.stdout
        native_stderr = sys.stderr
        output_buffer = StringIO()

        try:
            sys.stdout = output_buffer
            sys.stderr = output_buffer

            meta = event["_serverless-wsgi"]
            if meta.get("command") == "exec":
                # Evaluate Python code
                exec(meta.get("data", ""))
            elif meta.get("command") == "command":
                # Run shell commands
                result = subprocess.check_output(
                    meta.get("data", ""), shell=True, stderr=subprocess.STDOUT
                )
                output_buffer.write(to_native(result))
            elif meta.get("command") == "manage":
                # Run Django management commands
                from django.core import management

                management.call_command(*shlex.split(meta.get("data", "")))
            elif meta.get("command") == "flask":
                # Run Flask CLI commands
                from flask.cli import FlaskGroup

                flask_group = FlaskGroup(create_app=_create_app)
                flask_group.main(
                    shlex.split(meta.get("data", "")), standalone_mode=False
                )
            else:
                raise Exception("Unknown command: {}".format(meta.get("command")))
        except subprocess.CalledProcessError as e:
            return [e.returncode, e.output.decode("utf-8")]
        except:  # noqa
            return [1, traceback.format_exc()]
        finally:
            sys.stdout = native_stdout
            sys.stderr = native_stderr

        return [0, output_buffer.getvalue()]
    else:
        return serverless_wsgi.handle_request(wsgi_app, event, context)
Ejemplo n.º 5
0
def main(args, another_app=None):

    if another_app is not None:
        os.environ[APP] = '%s.py' % another_app
    else:
        current_app = os.environ.get(APP)
        if current_app is None or current_app.strip() == '':
            os.environ[APP] = '%s.__main__' % current_package

    cli = FlaskGroup()
    options = {
        'prog_name': 'restapi',
        'args': args,
    }

    # cannot catch for CTRL+c
    cli.main(**options)
Ejemplo n.º 6
0
class FardelManager:
    def __init__(self, fardel: Fardel):
        self.fardel = fardel

        Migrate(fardel.app, db)

        # self.register_commands()

        self.cli = FlaskGroup(
            help="A general utility script for Fardel applications.",
            create_app=self.get_flask_app,
        )

    def get_flask_app(self, *args, **kwargs):
        return self.fardel.app

    def register_commands(self):
        self.fardel.app.cli.command(create_admin)

    def run(self):
        self.cli.main()
Ejemplo n.º 7
0
    s.start()


@cli.command()
def list_routers():
    table = [["URL", "METHOD", "ENDPOINT"]]
    s_max = [25, 25, 25]
    for rule in app.url_map.iter_rules():
        name = rule.rule
        if len(name) > s_max[0]:
            s_max[0] = len(name)
        method = ",".join(rule.methods)
        if len(method) > s_max[1]:
            s_max[1] = len(method)
        endpoint = rule.endpoint
        if len(method) > s_max[2]:
            s_max[2] = len(endpoint)
        table.append([name, method, endpoint])
    s_max = [i + 2 for i in s_max]
    for t in table:
        print("|{0}|{1}|{2}|".format(*["-" * s_max[i] for i in range(3)]))
        print("|{0}|{1}|{2}|".format(
            *[t[i] + " " * (s_max[i] - len(t[i])) for i in range(3)]))


if __name__ == '__main__':
    if len(sys.argv) == 1:
        app.run()
    else:
        cli.main()
Ejemplo n.º 8
0
import click
from flask.cli import FlaskGroup

oy_group = FlaskGroup(name="oy",
                      add_default_commands=False,
                      add_version_option=False,
                      load_dotenv=True)

from . import database
from . import user

if __name__ == "__main__":
    oy_group.main()
Ejemplo n.º 9
0
    exec(code, dict(__file__=activate_this))

app = create_app(os.path.join(AppConfig.BASE_DIR, "config.yml"))
fg = FlaskGroup(app)


@app.shell_context_processor
def make_shell_context():
    model_dict = dict(app=app, db=db, cache=cache, tasks=tasks)
    
    return model_dict


@fg.command('recreate_db', help='Recreates a local database, You probably should not use this on production.')
def recreate_db():
    db.drop_all()
    db.create_all()
    db.session.commit()


@fg.command("run", help="run server")
def runserver():
    # Aliyun.sync_events()
    # tasks.run("cron", "sync_aliyun_events")
    # tasks.run.cron("* * * * *", "aliyun sync_events", mn="cron", fn="sync_aliyun_events")
    app.run(host=app.config["HOST"], port=app.config["PORT"], use_reloader=True)


if __name__ == '__main__':
    sys.exit(fg.main())
Ejemplo n.º 10
0
    )


@cli.command()
def frontend(with_appcontext=False):
    subprocess.call(
        ['node', 'server.js'],
    )


@cli.command()
@click.argument('username')
def create_user(username):
    """Creates user from passed params."""
    password = click.prompt('Password', hide_input=True)
    if not password:
        create_user(username)

    user = User(username=username)
    user.set_password(password)
    db.session.add(user)
    db.session.commit()
    
@cli.command()
def run():
    app.run(host='0.0.0.0', port=8080, debug=True)


if __name__ == "__main__":
    cli.main()