I have a simple single page flask web page. This app requires a cmd line argument during run as follow: python3 example.py home/dir1/dir2
.
Now I want to run this app using flask run
command. I set FLASK_APP=example.py
then executing flask run
command will start the flask server but since I am not able to provide the argument, my app will not work. How can I pass this home/dir1/dir2
argument with flask run
? I've used argv for the argument instead of argparse.
CodePudding user response:
From the flask --help
I saw you can pass arguments to the app from the command line like this:
flask --app 'example:create_app("argument to the app!", 5)' run
To do that you have to have a file called example.py
which has a method create_app
which inits the app, something like this:
from flask import Flask
def create_app(arg1, arg2):
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello, World!"
app.add_url_rule("/", endpoint="index")
print(arg1) # Prints "argument to the app!"
print(arg2) # Prints "5"
return app
Other option you have is using environment variables, for example in the shell do
export CMD_ARG=56
and you can access that in the app with
import os
cmd_arg = os.environ["CMD_ARG"] # "56"
In the flask --help
they also have an option -e
to pass in environment variables from a file.