《flask Web 開發(fā)》讀書筆記 & chapter 3

概念剖析

  • (Model View Control) 表現(xiàn)層、業(yè)務(wù)層與模型層分離機制,而模板用來管理表現(xiàn)層。
  • 模板是一個包含相應(yīng)文本的文件,其中的動態(tài)部分用占位量表示,占位量的具體值只有在請求上下文中才知道。使用真實值替換相應(yīng)字符。

jinja2初試

  • 創(chuàng)建模板文件夾templates,創(chuàng)建模板文件index.html,user.html
  • index.html 輸入 <h1> hello world!</h1>
  • index.html 輸入 <h1> hello {{ name }}!</h1>
  • hello.py 文件
from flask import Flask, render_template
from flask_script import Manager

app = Flask(__name__)
manager = Manager(app)

# 路由的基本用例
@app.route('/')
def index():
    return render_template( 'index.html' )

# 動態(tài)路由的基本用例
@app.route('/user/<name>')
def user(name):
    ## 使用 jinja2 模板引擎,傳入鍵值對,關(guān)鍵字參數(shù)
    return render_template('user.html', name=name)

if __name__ == '__main__':
    manager.run()
  • 提交到倉庫git add hello.py, readme.md templates,git commit -m "jinja2 first demo"
  • 創(chuàng)建標(biāo)簽 git tag 3a

jinjia2 傳入復(fù)雜變量

Flask中Jinja2模板引擎詳解(一)–控制語句和表達式

@app.route('/hello/<name>')
def hello(name=None):
    if name == 'world':
        name = '<em>World</em>'
    return render_template('hello-1.html', name=name, digits=[1,2,3,4,5],
                           users=[{'name':'John'},
                                  {'name':'Tom', 'hidden':True},
                                  {'name':'Lisa'},
                                  {'name':'Bob'}])

模板示例:

<dl>
{% for user in users if not user.hidden %}
  {% if loop.first %}
    <div>User List:</div>
    <dd>Deep: {{ loop.depth }}</dd>
    {% continue %}
  {% endif %}
  <div class="{{ loop.cycle('odd', 'even') }}">
  <dt>User No {{ loop.index }}:</dt>
  <dd>{{ user.name }}</dd>
  </div>
  {% if loop.last %}
    <div>Total Users: {{ loop.length }}</div>
  {% endif %}
{% else %}
  <li>No users found</li>
{% endfor %}
</dl>

常用過濾器

過濾器名 說明
safe 渲染時不轉(zhuǎn)義
capitalize 首字母大寫
lower 轉(zhuǎn)換小寫
upper 轉(zhuǎn)換大寫
title 每個單詞的首字母大寫
trim 刪除首尾空格
striptags 刪除所有的HTML標(biāo)簽

模板語法 {{ name|capitalize }}
git commit -m "jinja2 filter", git tag 3b

模板中的 block 和繼承機制

base.html 文件

<html>
<head>
    {% block head %}
    <title>{% block title %} {% endblock %}</title>
    {% endblock %}
    <style>
      h1{
        background: black;
        color: white;
        text-align: center;
        font-size: 200% ;
        padding: 20px;
        margin: 5px
      }
    </style>
</head>
<body>
   {% block body %}
   {% endblock %}
</body>
</html>

user.html 文件

{% extends "base.html" %}
<!-- title 嵌套在內(nèi)層,先對title模塊進行衍生 -->
{% block title %} Index {% endblock %}

<!-- super() 調(diào)用父文件的定義 -->
{% block head %}
  {{ super() }}
{% endblock %}

{% block body %}
  <h1> Hello {{ name|capitalize }} ! </h1>
{% endblock %}

git add., git commit -m "Jinja2 block and inhert"
git tag 3c

使用 Flask-Bootstrap 集成 Twitter Bootstrap

Bootstrap中文教程

Bootstrap 是一個用于快速開發(fā) Web 應(yīng)用程序和網(wǎng)站的前端框架。Bootstrap 是基于 HTML、CSS、JAVASCRIPT 的。

安裝flask-bootstrap

pip install flask-bootstrap

初始化 Flask-Bootstrap之后,就可以在程序中使用一個包含所有Bootstrap文件的基模板,這個模板采用Jinja2的模板繼承機制,讓程序擴展一個具有基本頁面結(jié)構(gòu)的基模板
Bootstrap入門教程

from flask.ext.bootstrap import Bootstrap
# ...
bootstrap = Bootstrap( app )

采用Bootstrap的 user.html

初試flask-bootstrap

{% extends "bootstrap/base.html" %}
<!-- 頁面標(biāo)題 -->
{% block title %} Flasky {% endblock %}
{% block navbar %}
<!-- 導(dǎo)航欄 -->
<!-- navbar-inverse 顏色反色即黑色 -->
<nav class="navbar navbar-inverse" role="navigation">
    <div class="container-fluid">
    <!-- 首個導(dǎo)航標(biāo)簽字體稍大 -->
    <div class="navbar-header">
        <a class="navbar-brand" href="/">Flasky</a>
    </div>
    <!-- 其余導(dǎo)航標(biāo)簽 -->
    <div>
        <ul class="nav navbar-nav">
            <li class="active"><a href="/user/zhanghl">zhanghl</a></li>
            <li class="active"><a href="/user/zhanglm">zhanglm</a></li>
        </ul>
    </div>
    </div>
</nav>
{% endblock %}

<!-- 正文 -->
{% block content %}
<div class="container">
    <div class="page-header">
        <h1> Hello, {{name}}</h1>
    </div>
</div>
{% endblock %}

git add., git commit -m "Jinja2 bootstrap first demo"
git tag 3d

FLask-Boostarp基模板定義的塊

block名 說明
doc 整個 html 文檔
html_attribs <html> 標(biāo)簽屬性
html <html> 標(biāo)簽中的內(nèi)容
head <head> 標(biāo)簽中的內(nèi)容
title <title> 標(biāo)簽中的內(nèi)容
metas 一組 <meta> 標(biāo)簽
styles 層疊樣式表定義
body_attribs <body>標(biāo)簽的屬性
body <body> 標(biāo)簽的內(nèi)容
navbar 用戶定義的導(dǎo)航條
<content> 用戶定義的頁面內(nèi)用
scripts 文檔底部的 JavaScripts 聲明

示例:

    <!-- scripts 塊示例 -->
    {% block scripts %}
         {{ super() }}
        <script type="text/javascript" src="my-script.js"></script>>
    {% endblock %}
    
    <!-- styles 塊示例 -->
    {% block styles %}
        {{ super() }}
        <style type="text/css" src="my-style.css"> </style>
    {% endblock %}

git add . , git commit -m "usual blocks in flask-bootstrap"

自定義錯誤處理模塊

# 處理錯誤碼的路由
#處理 404 錯誤
@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

自定義錯誤頁面:

{% extends "base.html" %}
{% block title %} Flasky - page not found {% endblock %}
{% block page_content %}
  <div class="page-header">
     <h1> Not Found !</h1>
  </div>
{% endblock %}

git add . , git commit -m "user define error page "
git tag 3e

創(chuàng)建url的輔助函數(shù)

url_for('視圖函數(shù)名', 動態(tài)路由的關(guān)鍵字參數(shù), 額外參數(shù),_external=True)url_for('user', name='John', page2, _external=True ) 返回 http://localhost:5000/user/John?page=2

靜態(tài)文件

  • 大多數(shù) web 程序中還會使用靜態(tài)文件,如 圖片,JavaScript 源碼文件 和 CSS
  • 靜態(tài)文件對應(yīng) url_map 中的 /static/<filename>, 存放在 static 文件夾下

base.html 中加入 :

    {% block head%}
        {{ super() }}
        <!-- 對于大多數(shù)瀏覽器,包括 chrome firefox -->
        <link rel="icon" href="{{ url_for('static', filename='favicon.ico' )}}" type="image/x-icon">
        <!-- 對于 I E -->
        <link rel="shortcut icon" href="{{ url_for('static', filename='favicon.ico' )}}" type="image/x-icon">
    {% endblock %}

創(chuàng)建 static 文件夾加入 favicon.ico 文件

git add . , git commit -m "use static file create icon "
git tag 3f

使用 Flask-Moment 本地化日期和時間

安裝 pip install flask-moment

from flask.ext.moment import Moment
...
moment = Moment( app)

# 把 current_time 傳入模板進行渲染

from datatime import datatime
@app.route('/')
def index():
  return render_template('index.html', current_time=datatime.utcnow()) 
 <!-- base.html -->
 {% block scripts %}
    {{ super() }}    
    <!-- 引入 moment.js 庫 -->
    {{ moment.include_moment() }}
{% endblock %}
<!-- 為了處理時間戳,F(xiàn)lask-Moment 向模板開放了 moment 類 ????? -->

<!--  index.html  -->
<p>the local data and time is {{ moment(current_time).format('LLL') }}.</p>
<p>That was {{ moment(current_time).fromNow(refresh=True) }}.</p>

git add . , git commit -m "use flask moment "
git tag 3g

查看代碼及全文

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 22年12月更新:個人網(wǎng)站關(guān)停,如果仍舊對舊教程有興趣參考 Github 的markdown內(nèi)容[https://...
    tangyefei閱讀 35,393評論 22 257
  • 第三章 模板 序 為什么要分離 易于維護的代碼,關(guān)鍵在于保持簡單的結(jié)構(gòu)。而我們之前編寫的hello.py雖然簡單,...
    科幻經(jīng)典閱讀 1,609評論 0 6
  • 第三章 模板(Templates) 編寫易于維護的程序的要點在于書寫干凈、良好結(jié)構(gòu)的代碼。你以前所見的代碼都過于...
    易木成華閱讀 1,256評論 0 2
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,537評論 19 139
  • 3 小王子的生活是孤獨的,因為他說的就是憂傷本身。白天,他會一個人守著電視,小公子喜歡看電視,看有意思的電視,有意...
    佛二代閱讀 444評論 0 0

友情鏈接更多精彩內(nèi)容