Flask ("application") versus vial (__ name__)

The official Quickstart recommends using __name__ when using a single module :

  1. ... If you use a single module (as in this example), you must use __name__ , because depending on whether the application is imported or as a module, the name will be different ( '__main__' versus the actual name of the import) ....

However, in its API document, hard coding is recommended when my application is a package :

So what you provide there is important. If you use one module, __name__ always the correct value. If you are, however, using a package, it is usually recommended that you hardcode the name of your package there.

I can understand why it’s better to hardcode the name of my package, but why not hardcode the name of one module? Or, in other words, what information can Flask get when it receives __main__ as its first parameter? I don’t see how this will make Flask easier to find resources ...

+7
python import flask module package
source share
1 answer

__name__ is just a convenient way to get the import name of the place where the application is defined. The checkbox uses the import name to know where to look for resources, templates, static files, instance folder, etc. When using the package, if you define your application in __init__.py , then __name__ will still point to the β€œright” place as to where the resources are. However, if you define it elsewhere, for example, mypackage/app.py , then using __name__ will indicate a resource search mypackage.app relative to mypackage.app instead of mypackage .

Using __name__ not orthogonal to hardcoding, it is simply a shorthand for using a package name. And also there is no reason to say that the name should be a basic package, it is fully consistent with your project structure.

+7
source share

All Articles