can I know which CLI command is being executed in Flask?

Question:

I want to call a function only if a certain command is being used to start the flask app. I.e. I do not want to call the function if CLI command is ‘initdb’:

flask initdb

but I want to call it when command is ‘run’:

flask run –host=0.0.0.0

Is there a way of knowing what command flask was called with?

PS. I’m looking at flaskr code and trying to start a Process() only if flask is called with ‘run’.

Asked By: user786904

||

Answers:

I don’t think you can. One way of solving this is by creating a environment variable.

When running the flask program you can assign a environment variable and then check if it’s true or not.

SOME_VARIABLE=initdb flask run

then in the code definitions you would reference that variable as:

if os.environ['SOME_VARIABLE'] == 'initdb':
    ....
else:
    ....

You would not be able to use the word ‘run’ as the environment variable, but I think that would be frowned upon anyways.

Answered By: Brett Holmes

I arrived a bit late to the party, but, you may want to check the contents of the sys.argv list after having created your flask application object (app = Flask(__name__)).

It should contain the command that was executed. From there you can figure out a way to do what you need to do.

I thought it could help someone.

Answered By: kostou
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.