Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to understand the first parameter in Flask instance init?

Tags:

python

flask

When create a Flask instance , we always use __name__ as the first arguments, but why?

class flask.Flask(import_name, static_path=None, static_url_path=None,static_folder='static', template_folder='templates', instance_path=None, instance_relative_config=False)

The official document says that first parameter is used to find resource,how?

like image 574
storen Avatar asked Jan 07 '23 20:01

storen


1 Answers

The import name is used to resolve the directory where the Flask application is installed (see the get_root_path function in flask/helpers.py). This makes it possible for things like render_template, send_static_file, and relative file paths in config to resolve to files in the application's folder without needing a file path to be provided.

Consider an extremely simple Python app without this functionality:

simple_app.py

print("Running simple_app")

with open('the-folder/simple.file', 'r') as f:
    for line in f:
        print(f)

simple.file

Hello
World!

And a directory structure looking like this:

some-path/
    simple-app/
        simple_app.py
        the-folder/
            simple.file

If we start Python while our current working directory is simple-app/ everything will work just fine:

simple-app$ python simple_app.py
Running simple_app
Hello
World!

But if we move up one folder and try again:

some-path$ python simple-app/simple_app.py
Traceback (most recent call last):
IOError: [Errno 2] No such file or directory: 'the-folder/simple.file'

The same thing happens when we move down one folder. However, if we could get the location of simple_app.py on the file system, we could then os.join the directory in which simple_app.py was installed with the-folder/simple.file

with open(os.join(SIMPLE_APP_DIR, 'the-folder/simple.file', 'r') as f:

And our working directory wouldn't matter, since we would always be dealing with an absolute path. This is what Flask does, and this is why it needs the __name__ passed in.

like image 95
Sean Vieira Avatar answered Jan 28 '23 05:01

Sean Vieira