Photo by Kyle Loftus / Unsplash

Background

之前都沒有在用相關的套件. 那現在覺得有必要用一下相關的套件服務, 所以來研究一下. Flask-script 官方也建議使用 Flask-CLI. 所以就紀錄一下.

Installation

$ pip3 install flask-cli
# For the flask script to work, an application needs to be discovered. This is achieved by exporting the FLASK_APP environment variable.
$ export FLASK_APP=/path/to/run.py

Start

Basic

$ flask run
 * Serving Flask app "run"
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)

Custom Commands

import click
from flask import Flask

app = Flask(__name__)

@app.cli.command()
def initdb():
    """Initialize the database."""
    click.echo('Init the db')
$ flask initdb
Init the db

list routes

接下來我想實作一個command可以list我目前flask用到的url的route.

run.py

from src import app
from flask import url_for
import urllib
import click

@app.cli.command()
def initdb():
    """Initialize the database."""
    click.echo('Init the db')

@app.cli.command()
def list_routes():
    import urllib

    output = []
    for rule in app.url_map.iter_rules():
        methods = ','.join(rule.methods)
        line = urllib.parse.unquote("{:50s} {:20s} {}".format(rule.endpoint, methods, rule))
        output.append(line)

    for line in sorted(output):
        print(line)

if __name__ == '__main__':
    app.run()

執行會得到以下的結果

$ flask list_routes
dashboard                   OPTIONS,HEAD,GET     /dashboard
domain                      OPTIONS,HEAD,GET     /domain
hello                       OPTIONS,HEAD,GET     /
login                       OPTIONS,POST         /login
login_page                  OPTIONS,HEAD,GET     /login_page
logout                      OPTIONS,HEAD,GET     /logout

Database

待補.. 我還沒想好要怎麼結合.

Reference