您的位置:首页 > 脚本大全 > > 正文

pythonflask编写接口(Python Flask框架模板操作实例分析)

更多 时间:2021-10-07 00:57:49 类别:脚本大全 浏览量:2927

pythonflask编写接口

Python Flask框架模板操作实例分析

本文实例讲述了python flask框架模板操作。分享给大家供大家参考,具体如下:

模板

在前面的示例中,视图函数的主要作用是生成请求的响应,这是最简单的请求。实际上,视图函数有两个作用:处理业务逻辑和返回响应内容。在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本。本节学到的模板,它的作用即是承担视图函数的另一个作用,即返回响应内容。 模板其实是一个包含响应文本的文件,其中用占位符(变量)表示动态部分,告诉模板引擎其具体值需要从使用的数据中获取。使用真实值替换变量,再返回最终得到的字符串,这个过程称为“渲染”。flask使用jinja2这个模板引擎来渲染模板。jinja2能识别所有类型的变量,包括{}。 jinja2模板引擎,flask提供的render_template函数封装了该模板引擎,render_template函数的第一个参数是模板的文件名,后面的参数都是键值对,表示模板中变量对应的真实值。

Jinja2官方文档(http://docs.jinkan.org/docs/jinja2/)

我们先来认识下模板的基本语法:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • {% if user %}
  •   {{ user }}
  • {% else %}
  •   hello!
  • <ul>
  •   {% for index in indexs %}
  •   <li> {{ index }} </li>
  • </ul>
  • 通过修改一下前面的示例,来学习下模板的简单使用:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • @app.route('/')
  • def hello_itcast():
  •   return render_template('index.html')
  • @app.route('/user/<name>')
  • def hello_user(name):
  •   return render_template('index.html',name=name)
  • 变量

    在模板中{{ variable }}结构表示变量,是一种特殊的占位符,告诉模板引擎这个位置的值,从渲染模板时使用的数据中获取;jinja2除了能识别基本类型的变量,还能识别{};

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • <span>{{mydict['key']}}</span>
  • <br/>
  • <span>{{mylist[1]}}</span>
  • <br/>
  • <span>{{mylist[myvariable]}}</span>
  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • from flask import flask,render_template
  • app = flask(__name__)
  • @app.route('/')
  • def index():
  •   mydict = {'key':'silence is gold'}
  •   mylist = ['speech', 'is','silver']
  •   myintvar = 0
  •   return render_template('vars.html',
  •               mydict=mydict,
  •               mylist=mylist,
  •               myintvar=myintvar
  •               )
  • if __name__ == '__main__':
  •   app.run(debug=true)
  • 反向路由: flask提供了url_for()辅助函数,可以使用程序url映射中保存的信息生成url;url_for()接收视图函数名作为参数,返回对应的url;

    如调用url_for('index',_external=true)返回的是绝对地址,在下面这个示例中是http://localhost:5000/

    如调用url_for('index',name='apple',_external=true)返回的是:
    http://localhost:5000/index/apple

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • @app.route('/')
  • def hello_itcast():
  •   return render_template('index.html')
  • @app.route('/user/<name>')
  • def hello_user(name):
  •   return url_for('hello_itcast',_external=true)
  • 自定义错误页面:

  • ?
  • 1
  • 2
  • 3
  • 4
  • from flask import flask,render_template
  • @app.errorhandler(404)
  • def page_not_found(e):
  •   return render_template('404.html'), 404
  • 过滤器:

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

    safe:禁用转义;

  • ?
  • 1
  • <p>{{ '<em>hello</em>' | safe }}</p>
  • capitalize:把变量值的首字母转成大写,其余字母转小写;

  • ?
  • 1
  • <p>{{ 'hello' | capitalize }}</p>
  • lower:把值转成小写;

  • ?
  • 1
  • <p>{{ 'hello' | lower }}</p>
  • upper:把值转成大写;

  • ?
  • 1
  • <p>{{ 'hello' | upper }}</p>
  • title:把值中的每个单词的首字母都转成大写;

  • ?
  • 1
  • <p>{{ 'hello' | title }}</p>
  • trim:把值的首尾空格去掉;

  • ?
  • 1
  • <p>{{ ' hello world ' | trim }}</p>
  • reverse:字符串反转;

  • ?
  • 1
  • <p>{{ 'olleh' | reverse }}</p>
  • format:格式化输出;

  • ?
  • 1
  • <p>{{ '%s is %d' | format('name',17) }}</p>
  • striptags:渲染之前把值中所有的html标签都删掉;

  • ?
  • 1
  • <p>{{ '<em>hello</em>' | striptags }}</p>
  • 语句块过滤(不常用):

  • ?
  • 1
  • 2
  • 3
  • {% filter upper %}
  •   this is a flask jinja2 introduction
  • {% endfilter %}
  • 自定义过滤器:

    通过flask应用对象的add_template_filter方法,函数的第一个参数是过滤器函数,第二个参数是过滤器名称。然后,在模板中就可以使用自定义的过滤器。

  • ?
  • 1
  • 2
  • 3
  • def filter_double_sort(ls):
  •   return ls[::2]
  • app.add_template_filter(filter_double_sort,'double_2')
  • web表单:

    web表单是web应用程序的基本功能。

    它是html页面中负责数据采集的部件。表单有三个部分组成:表单标签、表单域、表单按钮。表单允许用户输入数据,负责html页面数据采集,通过表单将用户输入的数据提交给服务器。

    在flask中,为了处理web表单,我们一般使用flask-wtf扩展,它封装了wtforms,并且它有验证表单数据的功能。

    wtforms支持的html标准字段

    pythonflask编写接口(Python Flask框架模板操作实例分析)

    wtforms常用验证函数

    pythonflask编写接口(Python Flask框架模板操作实例分析)

    使用flask-wtf需要配置参数secret_key。

    csrf_enabled是为了csrf(跨站请求伪造)保护。 secret_key用来生成加密令牌,当csrf激活的时候,该设置会根据设置的密匙生成加密令牌。

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • <form method='post'>
  •   <input type="text" name="username" placeholder='username'>
  •   <input type="password" name="password" placeholder='password'>
  •   <input type="submit">
  • </form>
  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • from flask import flask,render_template
  • @app.route('/login',methods=['get','post'])
  • def login():
  •   if request.method == 'post':
  •     username = request.form['username']
  •     password = request.form['password']
  •     print username,password
  •   return render_template('login.html',method=request.method)
  • 配置参数:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • app.config['secret_key'] = 'silents is gold'
  • {{ form.username.label }}
  • {{ form.username() }}
  • {{ form.password.label }}
  • {{ form.password() }}
  • {{ form.submit() }}
  • 我们通过登录页面来演示表单的使用。

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • #coding=utf-8
  • from flask import flask,render_template,\
  •   flash,redirect,url_for,session
  • #导入wtf扩展包的form基类
  • from flask_wtf import form
  • from wtforms.validators import datarequired,equalto
  • from wtforms import stringfield,passwordfield,submitfield
  • app = flask(__name__)
  • #设置secret_key,防止跨站请求攻击
  • app.config['secret_key'] = '2017'
  • #自定义表单类,继承form
  • class login(form):
  •   us = stringfield(validators=[datarequired()])
  •   ps = passwordfield(validators=[datarequired(),equalto('ps2','error')])
  •   ps2 = passwordfield(validators=[datarequired()])
  •   submit = submitfield()
  • #定义视图函数,实例化自定义的表单类,
  • @app.route('/',methods=['get','post'])
  • def forms():
  •   #实例化表单对象
  •   form = login()
  •   if form.validate_on_submit():
  •   #获取表单数据
  •     user = form.us.data
  •     pswd = form.ps.data
  •     pswd2 = form.ps2.data
  •     print user,pswd,pswd2
  •     session['name'] = form.us.data
  •     flash(u'登陆成功')
  •     return redirect(url_for('forms'))
  •   else:
  •     print form.validate_on_submit()
  •   return render_template('forms.html',form=form)
  • if __name__ == "__main__":
  •   app.run(debug=true)
  • 控制语句

    常用的几种控制语句:

    模板中的if控制语句

  • ?
  • 1
  • 2
  • 3
  • 4
  • @app.route('/user')
  • def user():
  •   user = 'dongge'
  •   return render_template('user.html',user=user)
  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • <html>
  •  <head>
  •    {% if user %}
  •     <title> hello {{user}} </title>
  •   {% else %}
  •      <title> welcome to flask </title>   
  •   {% endif %}
  •  </head>
  •  <body>
  •    <h1>hello world</h1>
  •  </body>
  •  </html>
  • 模板中的for循环语句

  • ?
  • 1
  • 2
  • 3
  • 4
  • @app.route('/loop')
  • def loop():
  •  fruit = ['apple','orange','pear','grape']
  •  return render_template('loop.html',fruit=fruit)
  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • <html>
  • <head>
  •   {% if user %}
  •    <title> hello {{user}} </title>
  •  {% else %}
  •     <title> welcome to flask </title>   
  •  {% endif %}
  • </head>
  • <body>
  •   <h1>hello world</h1>
  •  <ul>
  •    {% for index in fruit %}
  •      <li>{{ index }}</li>
  •    {% endfor %}
  •  </ul>
  • </body>
  • </html>
  • 宏:

    类似于python中的函数,宏的作用就是在模板中重复利用代码,避免代码冗余。

    jinja2支持宏,还可以导入宏,需要在多处重复使用的模板代码片段可以写入单独的文件,再包含在所有模板中,以避免重复。

    定义宏

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • {% macro input() %}
  •  <input type="text"
  •      name="username"
  •      value=""
  •      size="30"/>
  • {% endmacro %}
  • 调用宏

  • 您可能感兴趣