Domanda

I looked at a fairly generic structure to base my app off of, which looks something like this in directory structure:

run.py
config.py
app/
  __init__.py
  views.py
  blueprints/
  sql/

I put some variables in my config.py, which is then read by __init__.py when the app is made. Some pieces are completely static and don't matter, but some parts I want to be configurable on each different run. For example, queries = [x for x in os.listdir(os.path.join(_basedir, sql_path))] where sql_path is configurable, or changing the port_number

The absolute ideal would be to use command line arguments on the run.py script. My first reaction was clearly to do the following in run.py to configure it:

from app import app
import argparse
import os

_basedir = os.path.abspath(os.path.dirname(__file__))
parser = argparse.ArgumentParser(description='run the app')
parser.add_argument('--port', type=int, default=1225)
parser.add_argument('--sql_path', type=str, default='/app/sql/')
parser.add_argument('--debug', type=boolean, default=False)
args = parser.parse_args()

app.config['queries'] = [x for x in os.listdir(os.path.join(_basedir, args.sql_path))]
app.config['port_number'] = args.port
app.config['debug'] = args.debug

app.run(debug=args.debug, port=app.config['port_number'])

this will result in a KeyError when I run the app, saying that sql_path is not configured, as one of the blueprints uses it.

Is there a way to configure this with command line arguments? I want to be able to do python run.py --sql_path=../sql/ --port_number=5000, for example, and have that configure in the app.

È stato utile?

Soluzione

So you can do this as follows with a decorator that Flask provides:

from flask import Flask

app = Flask(__name__)

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

Then on the command like call that function like so:

$ flask -a hello.py initdb

Flask uses the Click package to pass through command line args, so anything available there should be available from Flask as well.

app.cli is an instance of click.Group (docs here) meaning things like @click.option() should translate over to be @app.cli.option() pretty nicely.

If you wanted to actually pass an option it might look something like this:

@app.cli.command()
@app.cli.option('--test', help='test')
def takearg(test):
    print test

And then call it as follows:

$ flask -a hello.py --test=teststring
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top