1、flask模板引擎
2、flask擴展之flask-wtf實現表單驗證
Flask中使用jinja2模板引擎css
jinja2是由Flask做者開發,模仿Django的模板引擎html
優勢:python
速度快,被普遍使用 HTML設計和後端python分離 很是靈活,快速和安全 提供了控制,繼承等高級功能
模板中的變量:{{ var }}jquery
視圖傳遞給模板的數據 前面定義出來的數據 變量不存在,默認忽略
模板中的標籤:{% tag %}django
控制邏輯 使用外部表達式 建立變量 宏定義
blockflask
{% block xxx %} {% endblock %} 塊操做 父模板挖坑,子模板填坑
extends後端
{% extends ‘xxx.html’ %} 繼承之後保留塊中的內容 {{ super() }}
挖坑繼承體現的化整爲零的操做api
macro安全
{% macro hello(name) %} {{ name }} {% endmacro %} 宏定義,能夠在模板中定義函數,在其餘地方調用
宏定義可導入函數
{% from 'xxx' import xxx %}
例子1:
在index.html中定義macro標籤,定義一個方法,而後去調用方法,結果是展現商品的id和商品名稱
{% macro show_goods(id, name) %} 商品id:{{ id }} 商品名稱:{{ name }} {% endmacro %} {{ show_goods('1', '娃哈哈') }} <br> {{ show_goods('2', '雪碧') }}
例子2:
在index.html頁面中定義一個say()方法,而後解析該方法:
{% macro say() %} <h3>今每天氣氣溫回升</h3> <h3>適合去游泳</h3> <h3>適合去郊遊</h3> {% endmacro %} {{ say() }}
例子3:
定義一個function.html中定義一個方法:
{% macro create_user(name) %} 建立了一個用戶:{{ name }} {% endmacro %}
在index.html中引入function.html中定義的方法
{% from 'functions.html' import create_user %} {{ create_user('小花') }}
{% for item in cols %} aa {% else %} bb {% endfor %}
也能夠獲取循環信息loop
loop.first loop.last loop.index loop.revindex
例子:
在視圖中定義一個視圖函數:
@stu.route('/scores/') def scores(): scores_list = [21,34,32,67,89,43,22,13] content_h2 = '<h2>今天大家真帥</h2>' content_h3 = ' <h3>今天大家真帥</h3> ' return render_template('scores.html', scores=scores_list, content_h2=content_h2, content_h3=content_h3)
(該視圖函數,在下面講解的過濾器中任然使用其返回的content_h2等參數)
首先: 在頁面中進行解析scores的列表。題目要求:第一個成績展現爲紅色,最後一個成績展現爲綠色,其餘的不變
<ul> {% for score in scores %} {% if loop.first %} <li style="color:red;">{{ loop.revindex }}:{{ loop.index }}:{{ score }}</li> {% elif loop.last %} <li style="color:green;">{{ loop.revindex }}:{{ loop.index }}:{{ score }}</li> {% else %} <li> {{ loop.revindex }}:{{ loop.index }}:{{ score }}</li> {% endif %} {% endfor %} </ul>
語法:
{{ 變量|過濾器|過濾器... }}
capitalize 單詞首字母大寫
lower 單詞變爲小寫
upper 單詞變爲大寫
title
trim 去掉字符串的先後的空格
reverse 單詞反轉
format
striptags 渲染以前,將值中標籤去掉
safe 講樣式渲染到頁面中
default
last 最後一個字母
first
length
sum
sort
例子:
<ul> <li>{{ content_h2 }}</li> <li>{{ content_h2|safe }}</li> <li>{{ content_h2|striptags }}</li> <li>{{ content_h3 }}</li> <li>{{ content_h3|length }}</li> <li>{{ content_h3|trim|safe }}</li> <li>{{ content_h3|trim|length }}</li> </ul>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> {% block title %} {% endblock %} </title> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> {% block extCSS %} {% endblock %} </head> <body> {% block header %} {% endblock %} {% block content%} {% endblock %} {% block footer%} {% endblock %} {% block extJS %} {% endblock %} </body> </html>
{% extends 'base.html' %} {% block extCSS %} <link rel="stylesheet" href="{{ url_for('static', filename='css/main.css') }}"> {% endblock %}
django:
第一種方式:
{% load static %} <link rel="stylesheet" href="{% static 'css/index.css' %}">
第二種方式:
<link rel="stylesheet" href="/static/css/index.css">
flask:
第一種方式:
<link rel="stylesheet" href="/static/css/index.css">
第二種方式:
<link rel="stylesheet" href="{{ url_for('static', filename='css/index.css') }}">
在Flask項目開發中針對提交表單的校驗,可使用Flask-WTF擴展庫進行快速的字段校驗,也能夠進行頁面快速渲染,並提供跨站請求僞造的保護功能。
pip install flask-wtf
在定義的表單類中定義須要驗證的username、password和password2字段,並實現以下校驗:
校驗用戶名的長度是否符合規範
# 導入擴展類 from flask_wtf import FlaskForm # 導入驗證字段 from wtforms import StringField, SubmitField, ValidationError # 導入表單驗證 from wtforms.validators import DataRequired, EqualTo from user.models import User class UserForm(FlaskForm): """ 登陸註冊表單驗證 """ username = StringField('用戶名', validators=[DataRequired()]) password = StringField('密碼', validators=[DataRequired()]) password2 = StringField('確認密碼', validators=[DataRequired(), EqualTo('password', '密碼不一致')] ) submit = SubmitField('提交') def validate_username(self, field): # 驗證用戶名是否重複 if User.query.filter(User.username == field.data).first(): raise ValidationError('用戶名已存在') # 對用戶名的長度進行判斷 if len(field.data) < 3: raise ValidationError('用戶名長度不能少於3個字符') if len(field.data) > 6: raise ValidationError('用戶名長度不能大於6個字符')
注意: 驗證字段的方法名爲: validate_字段(self, field)
當HTTP請求爲GET時,將表單驗證對象返回給頁面。
當HTTP請求爲POST時,經過方法validate_on_submit()方法進行字段校驗和提交判斷,若是校驗失敗,則能夠從form.errors中獲取錯誤信息。
若是驗證經過,則從form.字段.data中獲取到字段的值。
@blue.route('/register/', methods=['GET', 'POST']) def register(): form = UserForm() if request.method == 'GET': return render_template('register.html', form=form) if request.method == 'POST': # 判斷表單中的數據是否經過驗證 if form.validate_on_submit(): # 獲取驗證經過後的數據 username = form.username.data password = form.password.data # 保存 user = User() user.username = username user.password = generate_password_hash(password) user.save() return redirect(url_for('user.login')) return render_template('register.html', form=form)
註冊模板採用繼承父模板base.html的形式。在register.html模壓中分析以下:
1. 定義字段名: {{ form.字段.label }} 2. 定義input輸入框: {{ form.字段 }} 3. 展現錯誤信息: {{ form.errors.字段 }} 4. 跨站請求僞造: {{ form.csrf_token }}
註冊register.html頁面以下:
{% extends 'base.html' %} {% block title %} 註冊頁面 {% endblock %} {% block content %} <form action="" method="post"> {{ form.csrf_token }} {{ form.username.label }}:{{ form.username(style='color:red;', placeholder='請輸入用戶名', onblur="alert('123')") }} {{ form.password.label }}:{{ form.password }} {{ form.password2.label }}:{{ form.password2 }} {{ form.submit }} {% if form.errors %} 姓名錯誤信息:{{ form.errors.username }} 密碼錯誤信息:{{ form.errors.password2 }} {% endif %} </form> {% endblock %}
注意: 經過form.字段解析的input標籤中能夠自定義樣式,如{{ form.字段(class='xxx', style='color:red') }}
字段類型 說明 StringField 普通文本字段 PasswordField 密碼文本字段 SubmitField 提交按鈕 HiddenField 隱藏文本字段 TextAreaField 多行文本字段 DateField 文本字段,datetime.date格式 DateTimeField 文本字段,datetime.datetime格式 IntegerField 文本字段,整數類型 FloatField 文本字段,小數類型 BooleanField 複選框,值爲True或False RadioField 單選框 SelectField 下拉列表 FileField 文件上傳字段
驗證器 說明 DataRequired 確保字段有值(而且if判斷爲真) Email 郵箱地址 IPAddress IPv4的IP地址 Length 規定字符長度 NumberRange 輸入數值的範圍 EqualTo 驗證兩個字段的一致性 URL 有效的URL Regexp 正則驗證