Flask,模板,过滤器,静态文件

Flask,模板,过滤器,静态文件

在这里插入图片描述

在前面的示例中,视图函数的主要作用是生成请求的响应,这是最简单的请求。实际上,视图函数有两个作用:处理业务逻辑和返回响应内容。在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本。

本文介绍的模板,它的作用即是承担视图函数的另一个作用,即返回响应内容。 模板其实是一个包含响应文本的文件,其中用占位符(变量)表示动态部分,告诉模板引擎其具体值需要从使用的数据中获取。使用真实值替换变量,再返回最终得到的字符串,这个过程称为“渲染”。

Flask使用Jinja2这个模板引擎来渲染模板。Jinja2能识别所有类型的变量,Flask提供的render_template函数封装了该模板引擎,render_template函数的第一个参数是模板的文件名,后面的参数都是键值对,表示模板中变量对应的真实值。

模板默认存放在项目templates目录下,可在实例化Flask对象时使用template_folder指定其它目录。

Jinja2模板引擎使用以下分隔符从HTML转义。

{% ... %}:用于语句,if/for等控制流语句
{{ ... }}:用于变量/表达式显示输出
{# ... #}:用于未包含在模板输出中的注释
# ... #:用于行语句

下面的示例中,演示了在模板中使用if条件语句。hello()函数的URL规则接受整数参数。它被传递到hello.html模板。其中,比较接收的数字(marks)的值(大于或小于50),因此有判断条件地呈现响应内容。

WC_public_flask.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates')

@app.route('/hello/<int:score>')
def hello(score):
   return render_template('hello.html', marks=score)

if __name__ == '__main__':
   app.run(debug = True)

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% if marks >= 50  %}
    <h1>you result pass !</h1>
    {% else %}
    <h1>you result fail</h1>
{% endif %}
</body>
</html>

运行Python脚本并访问URL http://localhost/hello/60,然后访问http://localhost/hello/30,以查看HTML的输出是否有条件地更改。

接下我们看一下for循环HTML示例:

WC_public_flask.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates')

@app.route('/hello')
def hello():
   data = {'c++':90,'c':95,'ruby':45}
   return render_template('hello.html', marks = data)

if __name__ == '__main__':
   app.run(debug = True)

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{% for name,score in marks.items() %}
    <h2>{{ name }}:{{ score }}</h2>
{% endfor %}
</body>
</html>

for语句放在了{%%}内,name,score放在了{{}}内,运行浏览器输入:http://127.0.0.1:5000/result,效果如下:
在这里插入图片描述

过滤器

过滤器的本质就是函数。有时候我们不仅仅只是需要输出变量的值,我们还需要修改变量的显示,甚至格式化、运算等等,这就用到了过滤器。 过滤器的使用方式为:变量名 | 过滤器。 过滤器名写在变量名后面,中间用 | 分隔。如:{{variable | capitalize}},这个过滤器的作用:把变量variable的值的首字母转换为大写,其他字母转换为小写。 其他常用过滤器如下:

字符串操作:

safe:禁用转义;

  <p>{{ '<em>hello</em>' | safe }}</p>

capitalize:把变量值的首字母转成大写,其余字母转小写;

  <p>{{ 'hello' | capitalize }}</p>

lower:把值转成小写;

<p>{{ 'HELLO' | lower }}</p>

upper:把值转成大写;

 <p>{{ 'hello' | upper }}</p>

title:把值中的每个单词的首字母都转成大写;

 <p>{{ 'hello' | title }}</p>

trim:把值的首尾空格去掉;

<p>{{ ' hello world ' | trim }}</p>

reverse:字符串反转;

<p>{{ 'olleh' | reverse }}</p>

format:格式化输出;

<p>{{ '%s is %d' | format('name',17) }}</p>

striptags:渲染之前把值中所有的HTML标签都删掉;

 <p>{{ '<em>hello</em>' | striptags }}</p>

列表操作
first:取第一个元素

 <p>{{ [1,2,3,4,5,6] | first }}</p>

last:取最后一个元素

<p>{{ [1,2,3,4,5,6] | last }}</p>

length:获取列表长度

 <p>{{ [1,2,3,4,5,6] | length }}</p>

sum:列表求和

 <p>{{ [1,2,3,4,5,6] | sum }}</p>

sort:列表排序

 <p>{{ [6,2,3,1,5,4] | sort }}</p>

当模板内置的过滤器不能满足需求,可以自定义过滤器。自定义过滤器有两种实现方式:一种是通过Flask应用对象的add_template_filter方法。还可以通过装饰器@app.template_filter(‘自定义过滤器的名字’)来实现自定义过滤器。

注意:如果不传入参数,过滤器的名字就是函数的名字。

内置的过滤器就不做示例了,我们看一下自定义过滤器的使用:

WC_public_flask.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates')

@app.route('/hello', methods=['POST','GET'])
def hello():
   if request.method == 'POST':
      name = request.form['nm']
      return render_template('hello.html', data = name)
   else:
      return render_template('hello.html')

@app.template_filter('addinfo')
def add_info(arg):
   return 'hello {} ! this is template filter '.format(arg)

if __name__ == '__main__':
   app.run(debug = True)

hello.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
   <body>
{% if data %}
<h2>{{ data | addinfo }}</h2>
{% endif %}
      <form action = "http://localhost:5000/hello" method = "post">
         <p>Enter Name:</p>
         <p><input type = "text" name = "nm" /></p>
         <p><input type = "submit" value = "submit" /></p>
      </form>

   </body>
</html>

运行效果如下:
在这里插入图片描述

静态文件

Web应用程序通常需要静态文件,例如javascript文件或支持网页显示的CSS文件。通常,配置Web服务器并为您提供这些服务,但在开发过程中,这些文件是从您的包或模块旁边的static文件夹中提供,它将在应用程序的/static中提供。
特殊端点’static’用于生成静态文件的URL。
在下面的示例中,在index.html中的HTML按钮的OnClick事件上调用hello.js中定义的javascript函数,该函数在Flask应用程序的“/”URL上呈现。

WC_public_flask.py

from flask import Flask, render_template, request

app = Flask(__name__, template_folder='templates', static_folder='static')

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

if __name__ == '__main__':
   app.run(debug = True)

index.html

<!DOCTYPE html>
<html>

   <head>
      <script type = "text/javascript"
         src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
   </head>

   <body>
      <input type = "button" onclick = "sayhello()" value = "Say Hello" />
   </body>

</html>

hello.js

function sayhello() {
    alert('Hello World')
}

效果如下:
在这里插入图片描述

这一章就到这里了,下一章我们了解一下Flask如何使用数据库。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章