How to pass an arbitrary argument to Flask through app.run()?

Well the script is executing from top to bottom, so you can't print something you don't have yet. Putting the print statement inside a classic flask factory function allow you to first parse command line, then get your object and then use it:

from flask import Flask

def create_app(foo):
    app = Flask(__name__)
    app.config['foo'] = foo
    print('Passed item: ', app.config['foo'])
    return app

if __name__ == '__main__':
  from argparse import ArgumentParser
  parser = ArgumentParser()
  parser.add_argument('-a')
  args = parser.parse_args()
  foo = args.a
  app = create_app(foo)
  app.run()

Tags:

Python

Flask