用 Flask 建立網站起手式

因為建立 HEXO 的關係,我開始把 <% content %> 這種寫法放在心上但還不知道是什麼,直到開始學習 Flask 框架,才真正認識到很多框架都使用這種寫法來連結和模組化網頁檔案,這種寫法稱為 Jinja 神社


幫資料夾建立虛擬環境

因為 Python 套件在不同版本中不能共存,為了幫專案安裝應該要有的套件,就必須開虛擬環境給專案。


設定首頁

1
2
3
4
5
6
7
8
9
10
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def home():
return render_template('/pages/home.html')

if __name__ == "__main__":
app.run(port=9999, debug=True) # 開啟 port:9999 本地端伺服器,開啟 debug 模式

建立網頁結構

  • 建立 templates/layouts 資料夾:放樣版的資料夾,檔案性質為 html
  • 建立 templates/pages 資料夾:放頁面的資料夾,檔案性質為 html
  • 建立 static/images 資料夾:放圖片的資料夾,檔案性質為 jpg, png 等
  • 建立 static/styles 資料夾:放 CSS 檔案的資料夾
  • 建立 static/scripts 資料夾:放 JS 檔案的資料夾

設定樣版

  • 在 templates/layouts 資料夾建立公版檔案:layout.html
  • 在 layout.html 裡挖洞,就是共用的部分,共用的部分也可以標示名字來區分
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
     <html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}大家共用的網站名稱{% endblock %}</title>
    </head>
    <body>
    <nav>
    <ul>
    <li><a href="/">Home</a></li>
    </ul>
    </nav>
    {% block content %}{% endblock %}
    </body>
    </html>
    只是必須注意用什麼性質開洞,就要用什麼性質關洞(?)
    {% block 名字 %}{% endblock %}
    {% for 名字 %}{% endfor %}
  • 在要使用共用的網頁最上方先匯入要共用的樣版檔案 {% extends "layout.html" %}
  • 就可以在網頁內寫自己的部分
    1
    2
    3
    4
    5
    6
    7
    8
     {% extends "layout.html" %}

    {% block content %}

    <h1>HOME</h1>
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Accusantium fugit perferendis quia maiores placeat a sit aspernatur consequatur? Illo unde numquam officiis blanditiis ab dicta esse repellat doloribus laboriosam corrupti.</p>

    {% endblock %}

用 Python 寫程式

在一開始管理頁面的 py 檔中,可以直接對特定網頁寫程式:

1
2
3
4
@app.route("/lottery")
def lottery():
numbers = sorted(random.sample(range(1, 50), 6))
return render_template('/pages/lottery.html', numbers=numbers)

然後就可以回到 html 檔案中寫入這支程式:

1
2
3
4
5
{% for num in numbers %}
<div>{{ num }}</div>
{% endfor %}

{{ numbers }}
dark
sans