How can I make command line arguments visible to Flask routes?

I use Flask to create a tool to view data locally in a browser. I want to pass the directory containing the data as a command line argument, and then pass it to the appropriate routing function to render.

This does what I want, but with global variables:

dataDir = None

def initializeData(pathname):
    global dataDir
    dataDir = pathname

@app.route('/')
def home():
    # Use dataDir as desired

if __name__ == '__main__':
    initializeData(sys.argv[1])
    app = Flask(__name__)
    app.run()

Is there a better way to communicate between the command line and my routes?

+4
source share
1 answer

Your flash application has a property config. In addition, this code will exit with the name NameError. You want something like this:

import sys
from flask import Flask

app = Flask(__name__)


@app.route('/')
def home():
    return 'You wanted {!r} directory'.format(app.config.get('some_setting'))

if __name__ == '__main__':
    app.config['some_setting'] = sys.argv[1]
    app.run()
+8
source

Source: https://habr.com/ru/post/1664435/


All Articles