Horje
Why do we pass __name__ to the Flask class?

The __name__ is a built-in special variable that evaluates the name of the current module. If the source file is executed as the main program, the interpreter sets the __name__ variable to have a value “__main__”. If this file is being imported from another module, __name__ will be set to the module’s name.

index.html

 Let’s look at a very basic boilerplate code for a flask application. These variables (name and age) will pass with values from the Python functions and are shown up here.

HTML

<html>
    <head>
        <title>My Name</title>
    </head>
    <body>
      <p>hey, my name is {{name}}, and i'm {{age}} years old</p>
    </body>
</html>

app.py

This specific code shall render the index.html file and we are passing the name of the current module and age as 13.

Python3

from flask import Flask, render_template
  
app = Flask(__name__)
app.config["DEBUG"] = True
  
  
@app.route('/')
def index():
    dic = {
        "name": __name__,
        "age": 13
    }
    return render_template('index.html', dic=dic)
  
  
if __name__ == "__main__":
    print("My namme is : ", __name__)
  
    app.run(debug=True)

Output:

Why do we pass __name__ to the Flask class?

 

We see an argument __name__ being passed in the Flask class, but what does it exactly do?  

According to the official flask documentation, a __name__ argument is passed in the Flask class to create its instance, which is then used to run the application. Flask uses it to know from where to get resources, templates, static files, etc required to run the application.

Python3

print("My namme is : ", __name__)

Output:

What is __name__ in Python Flask?

 




Reffered: https://www.geeksforgeeks.org


Python

Related
Change case of all characters in a .txt file using Python Change case of all characters in a .txt file using Python
How to install Python packages with requirements.txt How to install Python packages with requirements.txt
Difference between Numpy array and Numpy matrix Difference between Numpy array and Numpy matrix
Count the occurrence of a certain item in an ndarray - Numpy Count the occurrence of a certain item in an ndarray - Numpy
Extract multidict values to a list in Python Extract multidict values to a list in Python

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12