Home > Back-end >  Trouble understanding flask logic
Trouble understanding flask logic

Time:10-20

I want develop a web application with flask so I started learning it.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

In this piece of code what exactly is the @app.route("/") for?

In my app I have made a form which gets data like name, class and section and stores it in a sql database. Here is the code:

from flask import Flask, render_template, request, url_for, flash, redirect
import sqlite3
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('Main.html')


@app.route('/addrec',methods = ['POST', 'GET'])
def addrec():
   if request.method == 'POST':
  
     std = request.form['class']
     section = request.form['Section'].lower()
     Alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
     if section not in Alphabet:
         return render_template("NoSuchSection.html")

In this I can observe that above the addrec() there is @app.route('/addrec',methods = ['POST', 'GET']).

So what is exactly @app.route() and what are all its uses in flask ?

(I want to understand its uses because after that only I can use it efficiently in my projects)

I have seen similar questions but I cannot understand them

CodePudding user response:

They are called decorators. It special functionality. In Flask, app.route() is what you want your URL to be.

For example:

@app.route(‘/hello’)

Would be for http://yourdomain.com/hello or http://127.0.0.1:5000/hello Whatever website you are running the server on.

You can learn more about decorators here: https://realpython.com/primer-on-python-decorators/

CodePudding user response:

route() is a decorator in flask which tells about the path/url in your application. Whatever path you want to have in your application, you have to put that in route()


from flask import Flask

app = Flask(__name__)


@app.route('/')
def home_page():
    return 'hompage'


@app.route('/user')
def user():
    return 'user_page'


@app.route('/shopping')
def shopping():
    return 'shopping'


if __name__ == '__main__':
    app.run()

This is a very basic example. Here, there are three different path/url in your application as /user, /shopping and / means home page. When you will run your application, your sever would provide you some url where this flask application would be serving something like Running on http://127.0.0.1:5000/

so when you hit http://127.0.0.1:5000/ it will land you on very home page due to / path and you would see homepage message in your browser.

similarly when you hit http://127.0.0.1:5000/users , you would be seeing user_page as message in your browser as /user path was hitted

  • Related