iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 3
2
Modern Web

慢慢帶你了解Flask系列 第 3

慢慢帶你了解Flask - Day3 使用HTML模板和重新導向

  • 分享至 

  • xImage
  •  

大家好,我是長風青雲。
今天是參加鐵人賽的第三天,上次說完URL,那今天就來將html加進我們的專案裏頭吧~

現在我要說明幾個function

render_template()

這個function就是用來使用html的
但首先他必須在上方import的地方加入
from flask import render_template
當然你可以在from flask import Flask後面直接加上,render_template
變成from flask import Flask,render_template
然後你必須要在你在這專案的資料夾內新增一個叫做templates的資料夾(記得是跟你的app.py同層)
https://ithelp.ithome.com.tw/upload/images/20190903/20120116FD3FRYlKec.png
Flask會到那邊尋找他所需要的html (所以代表你的html都要放在裡面喔!)
(^w^)flask已經一切都幫你一條龍服務好囉~
然後再來就是給你們看看測試的畫面了
程式碼如下:
(app.py)

from flask import Flask,render_template

app=Flask(__name__)

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

@app.route('/second')
def test():
	return render_template('test.html')

if __name__ == '__main__':
	app.run(host='0.0.0.0',port='5000',debug=True)

(index.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ironman Day3</title>
</head>
<body>
    <p>這是index.html</p>
</body>
</html>

(test.html)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ironman Day3</title>
</head>
<body>
    <p>這是test.html</p>
</body>
</html>

然後測試畫面
先執行app.py
https://ithelp.ithome.com.tw/upload/images/20190903/20120116HLx3AsQvum.png
再到瀏覽器開啟
https://ithelp.ithome.com.tw/upload/images/20190903/201201162oEzYvuYUo.png
接下來我要說說頁面跳轉,當然我相信大家都會用超連結互相連來連去啦~
所以我說的不是這個,而是如果我在執行一件事情後,我想讓他自動跳轉到別的畫面該怎麼做呢?

url_for()

先來看看跑出來的樣子 程式碼如下:

from flask import Flask,render_template,url_for

app=Flask(__name__)

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

@app.route('/second')
def test():
	return url_for('index')

if __name__ == '__main__':
	app.run(host='0.0.0.0',port='5000',debug=True)

https://ithelp.ithome.com.tw/upload/images/20190903/20120116ITsOi8OKds.png
url_for 的回傳值是找到function名稱為index的把對方所指向的路由顯示出來
可是我們是要顯示index.html啊,該怎麼辦呢?
那就要用到redirect這個function了。

redirect()

redirect顧名思義,就是重新導向的意思。
話不必多說,先跑程式碼。

from flask import Flask,render_template,url_for,redirect

app=Flask(__name__)

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

@app.route('/second')
def test():
	return redirect(url_for('index'))

if __name__ == '__main__':
	app.run(host='0.0.0.0',port='5000',debug=True)

然後因為用圖片有點難以表示 所以我決定用手機螢幕錄製一段小影片~
Yes
有沒有發現我雖然輸入了192.168.0.10:5000/second他卻還是跑到192.168.0.10:5000/呢~

那今天的部分就說完啦~
明天我會說說如果要傳值到另外一個網頁該怎麼做~
https://ithelp.ithome.com.tw/upload/images/20190903/2012011613s7PAneTJ.png


上一篇
慢慢帶你了解Flask - Day2 Flask的URL
下一篇
慢慢帶你了解Flask - Day4 網頁之間傳值
系列文
慢慢帶你了解Flask30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
阿瑜
iT邦研究生 4 級 ‧ 2019-09-04 22:35:43

簽到 #3
頑固的 url ,怎麼樣都到達 index.html

那是因為我這樣寫 XD

我要留言

立即登入留言