Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask instanciation app = Flask()

Tags:

python

flask

init

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?

like image 599
Mike Sila Avatar asked Jul 16 '13 14:07

Mike Sila


People also ask

How do you define an app in Flask?

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 .

What does app Flask (__ name __) mean?

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.

How do I run a Flask app in Python?

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 .


1 Answers

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

like image 144
codegeek Avatar answered Nov 04 '22 15:11

codegeek