Skip to content

flask admin cli

A CLI application to create Flask Admin instances.

Installation

pip install flask-admin-cli

Usage

To get a list of examples you can run, and follow the instructions

flask-admin list-examples

To get a list of the original examples you can run, and follow the instructions

flask-admin list-original-examples

API

Main API

This file has the main functions to check and clone remote git repos.

clone_repo(branch=None, dest_dir=None)

Clone the selected repo

Parameters:

Name Type Description Default
branch str

remote branch to clone.

None
dest_dir str

directory name inside the project.

None

Raises:

Type Description
InvalidParamsException

some of the parameters are invalid

FileExistsError

the dest_dir directory already exists

InvalidBranchException

the branch cannot be cloned.

Returns:

Type Description
True

True

Source code in flask_admin_cli/api.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def clone_repo(branch: str = None, dest_dir: str = None) -> True:
    """Clone the selected repo

    Args:
        branch (str): remote branch to clone.
        dest_dir (str): directory name inside the project.

    Raises:
        InvalidParamsException: some of the parameters are invalid
        FileExistsError: the `dest_dir` directory already exists
        InvalidBranchException: the `branch` cannot be cloned.

    Returns:
        True
    """
    if branch in ORIGINAL_EXAMPLES:
        branch = f"app-orig-{branch}"

    try:
        cross_check(dest_dir, branch)
    except Exception as e:
        raise exceptions.NotReadyException(e)
    else:
        print(f"git clone {MAIN_REPO}.git -b {branch} {dest_dir}")
        # clone = subprocess.run(
        #     ["git", "clone", f"{MAIN_REPO}.git", "-b", branch, new_dir],
        #     check=True,
        # )
        # subprocess.run(["rm", "-rf", f"{new_dir}/.git"])
        return True

cross_check(dest_dir, branch)

Pre-flight checks

Verifies the environment

Parameters:

Name Type Description Default
dest_dir str

directory name inside the project.

required
branch str

remote branch to clone.

required

Raises:

Type Description
InvalidParamsException

some of the parameters are invalid

FileExistsError

the dest_dir directory already exists

InvalidBranchException

the branch cannot be cloned.

Source code in flask_admin_cli/api.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def cross_check(dest_dir: str, branch: str) -> None:
    """Pre-flight checks

    Verifies the environment

    Args:
        dest_dir (str): directory name inside the project.
        branch (str): remote branch to clone.
    Raises:
        InvalidParamsException: some of the parameters are invalid
        FileExistsError: the `dest_dir` directory already exists
        InvalidBranchException: the `branch` cannot be cloned.
    """

    if not dest_dir or not branch:
        raise exceptions.InvalidParamsException(f"{dest_dir} or {branch} are None.")
    # new directory
    if os.path.isdir(dest_dir):
        raise FileExistsError(f"The directory {dest_dir} already exists.")

    # branch allowed
    if branch in BRANCHES_NOT_ALLOWED:
        raise exceptions.InvalidBranchException(f"`{branch}` is not allowed.")
    # branch prefix
    if not branch.startswith(BRANCH_PREFIX):
        raise exceptions.InvalidBranchException(
            f"`{branch}` must start with `{BRANCH_PREFIX}`."
        )
    # branch exists
    status = subprocess.run(
        ["git", "ls-remote", "--exit-code", "--heads", f"{MAIN_REPO}.git", branch],
        check=True,
        capture_output=False,
        stdout=subprocess.DEVNULL,
    )
    if status.returncode == 2:
        raise exceptions.RemoteBranchNotFoundException(
            f"The remote branch {branch} does not exist."
        )

CLI

CLI Application

Available Commands
  • list-original-examples: To get a list of the original examples provided by Flask-Admin
  • list-examples: To get a list of available apps for your project.
  • new_app: creates an app

Examples:

>>> flask-admin list-examples
>>> flask-admin list-original-examples

list_examples()

Lists all available examples.

All these examples are made by us.

Source code in flask_admin_cli/cli.py
33
34
35
36
37
38
39
40
41
42
43
44
@click.command()
def list_examples():
    """Lists all available examples.

    All these examples are made by us.
    """
    for example in api.AVAILABLE_EXAMPLES:
        click.secho(f"## {example}:", bold=True)
        click.secho(f"\tURL: {api.MAIN_REPO}/tree/{example}")
        click.secho(f"\tInstalls with ", nl=False)
        click.secho(f"flask-admin new_app --app {example}", bold=True)
        click.echo("")

list_original_examples()

Lists all the original examples made by the Flask-Admin team.

Source code in flask_admin_cli/cli.py
22
23
24
25
26
27
28
29
30
@click.command()
def list_original_examples():
    """Lists all the original examples made by the Flask-Admin team."""
    for example in api.ORIGINAL_EXAMPLES:
        click.secho(f"## {example}:", bold=True)
        click.secho(f"\tURL: {api.FLASK_ADMIN_REPO}/tree/master/examples/{example}")
        click.secho(f"\tInstalls with ", nl=False)
        click.secho(f"flask-admin new_app --app {example}", bold=True)
        click.echo("")

new_app(app, dest_dir)

Flask-Admin app as a Flask app

Source code in flask_admin_cli/cli.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
@click.command()
@click.option(
    "--app",
    default="app-factory",
    help="Application Name.",
    required=True,
    type=str,
    show_default=True,
)
@click.option(
    "--dest_dir",
    prompt="Directory",
    help="Directory to install.",
    required=True,
    default=".",
    type=click.Path(
        file_okay=False,
        dir_okay=True,
        resolve_path=True,
        allow_dash=False,
        exists=False,
    ),
    show_default=True,
)
def new_app(app, dest_dir):
    """Flask-Admin app as a Flask app"""
    api.clone_repo(app, dest_dir)