Kyle Swanson
Kyle Swanson

Reputation: 1428

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

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

Upvotes: 10

Views: 30295

Answers (3)

rrobby86
rrobby86

Reputation: 1484

An update for more recent versions of Flask: when running through flask run you can now invoke an app factory and even pass arguments (docs).

Example code:

from flask import Flask

def create_app(foo=None):
    app = Flask(__name__)
    app.config["foo"] = foo
    return app

# if __name__ == "__main__": ... not necessary

Assuming it is saved as flaskTest.py, you can run it using:

export FLASK_APP="flaskTest:create_app('value of foo')"
flask run

Upvotes: -1

lee-pai-long
lee-pai-long

Reputation: 2292

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

Upvotes: 12

cwallenpoole
cwallenpoole

Reputation: 82078

So, the problem is that you're trying to access the value before you define it. You would need to do something like this in your case:

from flask import Flask

app = Flask(__name__)
app.config['foo'] = 'Goo'

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

if __name__ == '__main__':
  app.run()

If you're trying to access that value while loading some third module, you'll need to define the value somewhere ahead of time.

Upvotes: 1

Related Questions