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

Issue

I would like to pass an object to a newly initiated flask app. I tried following the solution from the question: how-can-i-make-command-line-arguments-visible-to-flask-routes

Edit

I would like to take a value that I pick up from initiating the python script from the command line.

ie.

$ run python flaskTest.py -a goo

I am not seeing the difference between this and the solution to the question I am trying to replicate.
Edit

Thus, I tried the following:

from flask import Flask

app = Flask(__name__)

print('Passed item: ', app.config.get('foo'))

if __name__ == '__main__':
  from argparse import ArgumentParser

  parser = ArgumentParser()
  parser.add_argument('-a')
  args = parser.parse_args()
  val = args.a

  app.config['foo'] = val
  app.run()

Hoping to get the result…

'Passed item: Goo'

Is there a method for passing an arbitrary object through the initialization with app.run()?

Solution

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()

Answered By – lee-pai-long

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published