Home > Blockchain >  How to use only 'flask run' command in terminal and add default config variables in code i
How to use only 'flask run' command in terminal and add default config variables in code i

Time:09-28

I would like to start my Flask application with just flask run with these config informations: host = 0.0.0.0, port = 443 & cert = adhoc. If I wanted to run this through command I would have executed the code below instead:

flask run --host=0.0.0.0 --port=443 --cert=adhoc

But then I have to tell all my group mates and my professor to do it too when they check on my code. So I tried to work around this by using the code below in my app:

werkzeug.serving.run_simple("0.0.0.0", 443, app, ssl_context='adhoc')

However when I try to close my server with CTRL C, it starts another server that actually would start if I didn't have any config informations. So I was wondering is there any way to go around this? Either it is to continue using werkzeug or to change it to something else.

Here is a shorten version of my code that includes how I have built my app. Tried to include what's just needed. If there's anything I should include more just tell me. Any help is appreciated. Thank you!

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    app.config.from_mapping(
        SECRET_KEY='env',
        DATABASE=os.path.join(app.instance_path, 'flaskr.sqlite'),
    )    

    app.app_context().push()

    if test_config is None:
        # load the instance config, if it exists, when not testing
        app.config.from_pyfile('config.py', silent=True)
    else:
        # load the test config if passed in
        app.config.from_mapping(test_config)

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass
   
    serving.run_simple("0.0.0.0", 443, app, ssl_context='adhoc')
    return app

CodePudding user response:

Environment variables would probably be the correct way to provide these values to the flask run command.

You never mentioned your platform, but on Linux, something like:

export FLASK_RUN_PORT=9999

Causes the dev sever to launch on port 9999 when launched with just flask run

You could also put these values in the file .flaskenv:

FLASK_RUN_PORT=9999
FLASK_RUN_HOST=0.0.0.0

flask run should then autoload these values.

By the way official documentation misses these values out, I had to look on issue 2661

Seems FLASK_RUN_CERT=adhoc is also a valid one, as per issue 3105.

Not sure if there's an extensive list of these anywhere.

  • Related