回调接入点-页面缓存逻辑

from flask import Flask,request,render_template
from werkzeug.contrib.cache import SimpleCache
app = Flask(__name__)

CACHE_TIMEOUT = 300
cache = SimpleCache()
cache.timeout = CACHE_TIMEOUT

@app.before_request
def return_cached():
    if not request.values:
        response = cache.get(request.path)
        if response:
            print('从网页获取了cache')
            return response
    print('将会加载网页')

@app.after_request
def cache_response(response):
    if not request.values:
        cache.set(request.path,response,CACHE_TIMEOUT)
    return response

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

 使用过滤器

 字符串过滤器

{# 当变量未定义时,显示默认字符串,可以缩写为d #}
<p>{{ name | default('No name', true) }}</p>
 
{# 单词首字母大写 #}
<p>{{ 'hello' | capitalize }}</p>
 
{# 单词全小写 #}
<p>{{ 'XML' | lower }}</p>
 
{# 去除字符串前后的空白字符 #}
<p>{{ '  hello  ' | trim }}</p>
 
{# 字符串反转,返回"olleh" #}
<p>{{ 'hello' | reverse }}</p>
 
{# 格式化输出,返回"Number is 2" #}
<p>{{ '%s is %d' | format("Number", 2) }}</p>
 
{# 关闭HTML自动转义 #}
<p>{{ '<em>name</em>' | safe }}</p>
 
{% autoescape false %}
{# HTML转义,即使autoescape关了也转义,可以缩写为e #}
<p>{{ '<em>name</em>' | escape }}</p>
{% endautoescape %}

数值操作

{# 四舍五入取整,返回13.0 #}
<p>{{ 12.8888 | round }}</p>
 
{# 向下截取到小数点后2位,返回12.88 #}
<p>{{ 12.8888 | round(2, 'floor') }}</p>
 
{# 绝对值,返回12 #}
<p>{{ -12 | abs }}</p>

列表操作

{# 取第一个元素 #}
<p>{{ [1,2,3,4,5] | first }}</p>
 
{# 取最后一个元素 #}
<p>{{ [1,2,3,4,5] | last }}</p>
 
{# 返回列表长度,可以写为count #}
<p>{{ [1,2,3,4,5] | length }}</p>
 
{# 列表求和 #}
<p>{{ [1,2,3,4,5] | sum }}</p>
 
{# 列表排序,默认为升序 #}
<p>{{ [3,2,1,5,4] | sort }}</p>
 
{# 合并为字符串,返回"1 | 2 | 3 | 4 | 5" #}
<p>{{ [1,2,3,4,5] | join(' | ') }}</p>
 
{# 列表中所有元素都全大写。这里可以用upper,lower,但capitalize无效 #}
<p>{{ ['tom','bob','ada'] | upper }}</p>

字典列表操作

{% set users=[{'name':'Tom','gender':'M','age':20},
              {'name':'John','gender':'M','age':18},
              {'name':'Mary','gender':'F','age':24},
              {'name':'Bob','gender':'M','age':31},
              {'name':'Lisa','gender':'F','age':19}]
%}
 
 
{# 按指定字段排序,这里设reverse为true使其按降序排 #}
<ul>
{% for user in users | sort(attribute='age', reverse=true) %}
     <li>{{ user.name }}, {{ user.age }}</li>
{% endfor %}
</ul>
 
{# 列表分组,每组是一个子列表,组名就是分组项的值 #}
<ul>
{% for group in users|groupby('gender') %}
    <li>{{ group.grouper }}<ul>
    {% for user in group.list %}
        <li>{{ user.name }}</li>
    {% endfor %}</ul></li>
{% endfor %}
</ul>
 
{# 取字典中的某一项组成列表,再将其连接起来 #}
<p>{{ users | map(attribute='name') | join(', ') }}</p>

Flask内置过滤器

Flask提供了一个内置过滤器”tojson”,它的作用是将变量输出为JSON字符串。这个在配合Javascript使用时非常有用。我们延用上节字典列表操作中定义的”users”变量

 
<script type="text/javascript">
var users = {{ users | tojson | safe }};
console.log(users[0].name);
</script>

语句块过滤

Jinja2还可以对整块的语句使用过滤器。

{% filter upper %}
    This is a Flask Jinja2 introduction.
{% endfilter %}

自定义过滤器

自己写过滤器,过滤器就是一个函数

回到Flask应用代码中

def double_step_filter(l):
    return l[::2]

我们定义了一个”double_step_filter”函数,返回输入列表的偶数位元素(第0位,第2位,..)。Flask应用对象提供了”add_template_filter”方法来帮我们实现把它加到模板中当过滤器用

app.add_template_filter(double_step_filter, 'double_step')

函数的第一个参数是过滤器函数,第二个参数是过滤器名称。然后,我们就可以愉快地在模板中使用这个叫”double_step”的过滤器了:

{# 返回[1,3,5] #}
<p>{{ [1,2,3,4,5] | double_step }}</p>

Flask还提供了添加过滤器的装饰器”template_filter”,使用起来更简单。下面的代码就添加了一个取子列表的过滤器。装饰器的参数定义了该过滤器的名称”sub”。

@app.template_filter('sub')
def sub(l, start, end):
    return l[start:end]
{# 返回[2,3,4] #}
<p>{{ [1,2,3,4,5] | sub(1,4) }}</p>

测试器使用

{# 检查变量是否被定义,也可以用undefined检查是否未被定义 #}
{% if name is defined %}
    <p>Name is: {{ name }}</p>
{% endif %}
 
{# 检查是否所有字符都是大写 #}
{% if name is upper %}
  <h2>"{{ name }}" are all upper case.</h2>
{% endif %}
 
{# 检查变量是否为空 #}
{% if name is none %}
  <h2>Variable is none.</h2>
{% endif %}
 
{# 检查变量是否为字符串,也可以用number检查是否为数值 #}
{% if name is string %}
  <h2>{{ name }} is a string.</h2>
{% endif %}
 
{# 检查数值是否是偶数,也可以用odd检查是否为奇数 #}
{% if 2 is even %}
  <h2>Variable is an even number.</h2>
{% endif %}
 
{# 检查变量是否可被迭代循环,也可以用sequence检查是否是序列 #}
{% if [1,2,3] is iterable %}
  <h2>Variable is iterable.</h2>
{% endif %}
 
{# 检查变量是否是字典 #}
{% if {'name':'test'} is mapping %}
  <h2>Variable is dict.</h2>
{% endif %}

自定义测试器

import re
def has_number(str):
    return re.match(r'.*\d+', str)
app.add_template_test(has_number,'contain_number')
{% if name is contain_number %}
  <h2>"{{ name }}" contains number.</h2>
{% endif %}

Flask提供了添加测试器的装饰器”template_test”。

@app.template_test('end_with')
def end_with(str, suffix):
    return str.lower().endswith(suffix.lower())
{% if name is end_with "me" %}
  <h2>"{{ name }}" ends with "me".</h2>
{% endif %}

 

相关文章: