Grey Li
Grey Li

Reputation: 12762

Flask definition: Route and View

Here is a minimal application with Flask:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def index():
    return 'Hello, World!'

I know index() is the view function. [Q1] The question is, I can't tell exactly which part is route and which part is view. I didn't find the clarity definitions about them in Documentation.

[Q2] The wording below make me confused, which one is wrong?

[Q3] Could I say the button below was *pointed to index *view?

<a href="{{ url_for('index') }}">Button</a>

Thanks!

Upvotes: 3

Views: 1603

Answers (1)

jz22
jz22

Reputation: 2638

Q1: The function below @app.route('/') is the starting point of your website. Whenever your website is opened this is the code that gets executed. You can now add more app routes.

For example @app.route('/contact'). That means if you open your website the code below @app.route('/') gets executed but if you open example.com/contact the code of your /contact app route will be executed. The function name does not have to be index or contact. You can choose whatever name you want.

You can also add href tags to your HTML that refer to the desired app route. For example <a href="./contact"></a> will lead you to your contact app route when being clicked.

Q2: Depends on what you want to express. As I mentioned the function of @app.route('/') does not have to be index. You can put whatever function you want into that route.

Q3: '/' is your root url. This app route gets executed when you open example.com.

Upvotes: 1

Related Questions