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?
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:
print("Running simple_app")
with open('the-folder/simple.file', 'r') as f:
for line in f:
print(f)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With