I intentionally removed name in app = Flask(name) and I get this error:
Traceback (most recent call last):
File "routes.py", line 4, in <module>
app = Flask()
TypeError: __init__() takes at least 2 arguments (1 given)
this is my code from nettuts and here is my code:
from flask import Flask, render_template
app = Flask()
@app.route('/')
def home():
return render_template('home.html')
@app.route('/about')
def about():
return render_template('about.html')
if __name__ == '__main__':
app.run(debug=True)
My question is: Where is this init method that takes at least 2 arguments?
from flask import Flask app = Flask(__name__) @app. route('/') def hello(): return 'Hello, World!' In the preceding code block, you first import the Flask object from the flask package. You then use it to create your Flask application instance with the name app .
You'll add to it later in the tutorial, but it already does a lot. app = Flask(__name__, instance_relative_config=True) creates the Flask instance. __name__ is the name of the current Python module. The app needs to know where it's located to set up some paths, and __name__ is a convenient way to tell it that.
To run the application, use the flask command or python -m flask . You need to tell the Flask where your application is with the --app option. As a shortcut, if the file is named app.py or wsgi.py , you don't have to use --app .
If you understand the concept of class and objects, then __init__
is the constructor which initializes an instance of the class. In this case, the class is Flask and when you do the following, you are initializing the instance of a Flask object:
app = Flask(__name__)
Now your question, "Where is this init method that takes at least 2 arguments?"
That can be explained as per the definition below that defines the constructor in the code.
def __init__(self, import_name, static_path=None, static_url_path=None,
static_folder='static', template_folder='templates',
instance_path=None, instance_relative_config=False):
If you see above, self
and import name
is the required parameter and rest are all defaulted or not required. The self
is needed by Python even though you can name it anything else. read this blog by creator of python himself for why http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html
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