我想用 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()它在燒瓶中究竟是什么以及它的所有用途是什么?
(我想了解它的用途,因為之后只有我才能在我的專案中有效地使用它)
我看過類似的問題,但我看不懂
uj5u.com熱心網友回復:
他們被稱為裝飾者。它的特殊功能。在 Flask 中, app.route() 就是你想要的 URL。
例如:
@app.route(‘/hello’)
將用于http://yourdomain.com/hello或http://127.0.0.1:5000/hello無論您在哪個網站上運行服務器。
您可以在此處了解有關裝飾器的更多資訊:https : //realpython.com/primer-on-python-decorators/
uj5u.com熱心網友回復:
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,這個燒瓶應用程式將在其中提供類似的服務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路徑被點擊
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/324090.html
