我正在用 Flask 和 python 構建一個網站,我想將用戶的輸入存盤在一個變數中,然后將其輸出到網站螢屏上。
這是我的 HTML 代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
</head>
<body>
<div><h1>Home Page</h1>
<p>Hello, {{ name }}</p>
</div>
<form>
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
<a href="/my-link/">Click me</a>
</body>
</html>
這是我的 python/flask 代碼:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/my-link/')
def my_link():
temp = 0
for i in range(10):
temp = i
return str(temp)
if __name__ == '__main__':
app.run(debug=True, port=8000)
當我運行它時,這就是我看到的: 
當我輸入 54 并點擊“計算估計”時,我不明白為什么我會http://127.0.0.1:8000/?estimate=54進入我的搜索欄,我不明白為什么它會出現在那里。我怎樣才能獲得那個 54 并將其列印在網站螢屏上?
uj5u.com熱心網友回復:
雖然我建議POST您在提交敏感資料時使用,但GET在您的情況下就足夠了。
為了解決您的問題,我們必須首先指定一個操作端點(默認情況下,它是/,這將太多的責任加載到一個端點上)。
<form action="/calculate-estimate">
<label for="fname">Enter Sq. ft.</label><br>
<input type="text" id="estimate" name="estimate" value="Ex. 1000"><br>
<input type="submit" value="Calculate Estimate">
</form>
其次,我們需要創建一個FLASK端點來處理表單資料。
@app.route("/calculate-estimate", methods=["GET"])
def calculate_estimate():
estimate = request.args.get("estimate")
## Use your data however you desire.
這應該足以解決您的問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360423.html
