理解Flask逻辑的困难

2024-10-04 03:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用flask开发一个web应用程序,所以我开始学习它

from flask import Flask
app = Flask(__name__)

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

在这段代码中@app.route("/")的确切含义是什么

在我的应用程序中,我制作了一个表单,可以获取名称、类和节等数据,并将其存储在sql数据库中。代码如下:

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")

在这里,我可以看到addrec()上面有@app.route('/addrec',methods = ['POST', 'GET'])

那么@app.route()到底是什么?它在烧瓶中有什么用途

(我想了解它的用途,因为在此之后,只有我才能在我的项目中有效地使用它)

我见过类似的问题,但我不能理解


Tags: namefromimportapp应用程序flaskreturnrequest
2条回答

route()是flask中的一个装饰器,它告诉您的应用程序中的路径/url。无论您希望在应用程序中使用什么路径,都必须将其放在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()

这是一个非常基本的例子。在这里,应用程序中有三种不同的路径/url,/user/shopping/表示主页。 当您运行应用程序时,服务器将为您提供一些url,该flask应用程序将在其中提供类似Running on http://127.0.0.1:5000/ 的服务

因此,当您点击http://127.0.0.1:5000/ 时,它将根据/路径将您置于主页上,您将在浏览器中看到homepage消息

类似地,当您点击http://127.0.0.1:5000/users时,您会在浏览器中看到user_page作为消息,因为/user路径被点击

他们被称为装饰师。它具有特殊的功能。在Flask中,app.route()是您想要的URL

例如:

@app.route(‘/hello’)

将用于http://yourdomain.com/hellohttp://127.0.0.1:5000/hello运行服务器的任何网站

您可以在此处了解有关装饰器的更多信息:https://realpython.com/primer-on-python-decorators/

相关问题 更多 >