Running Flask CLI and API

Running Flask CLI and API

Note to self: Here’s a super simple starting point for setting up a Flask application that supports both API and CLI interaction.

import click
from flask import Flask
from flask.cli import FlaskGroup

#app = Flask(__name__)
def create_app():
    app = Flask('wiki')
    # other setup
    return app

app = create_app()

def get_profile_name():
  return "alice"

@app.route("/")
def hello_world():
    name = get_profile_name()
    return f"<p>Hello, {name}!</p>"

@click.group(cls=FlaskGroup)
def cli():
    """Management script for the Wiki application."""

@cli.command()  # @cli, not @click!
def hello():
    name = get_profile_name()
    click.echo(f"Hello {name}!")

To run it, run this command:

FLASK_DEBUG=1 FLASK_APP=app flask run

To “map” the CLI to a custom app name, add a setup.py file with contents like this:

from setuptools import setup

setup(
    name='flask-my-extension',
    entry_points={
        'console_scripts': [
            'myapp=app:cli'
        ],
    },
)

Restart the Flask app. Now, uses can interact with the CLI like this:

> myapp hello
Hello!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: