Flask 模板语言,装饰器
程序员文章站
2022-03-03 22:16:49
Jinja2模板语言 #-*-coding:utf-8-*- fromflaskimportFlask,render_template,request,redirect,Markup app=Flask(__name__) STUDENT={'name':'Old','age':38,'gen... ......
jinja2模板语言
- # -*- coding: utf-8 -*-
- from flask import flask, render_template, request, redirect, markup
- app = flask(__name__)
- student = {'name': 'old', 'age': 38, 'gender': '中'}
- student_list = [
- {'name': 'old', 'age': 38, 'gender': '中'},
- {'name': 'boy', 'age': 73, 'gender': '男'},
- {'name': 'edu', 'age': 84, 'gender': '女'}
- ]
- student_dict = {
- 1: {'name': 'old', 'age': 38, 'gender': '中'},
- 2: {'name': 'boy', 'age': 73, 'gender': '男'},
- 3: {'name': 'edu', 'age': 84, 'gender': '女'},
- }
- # 返回标签
- tag = '<input type="text", name="username">'
- tag = markup(tag) # 安全标签字符串
- # 传入函数, 全局可以使用
- @app.template_global()
- def func(a, b):
- return a + b
- @app.template_filter()
- def fil(a, b, c):
- return a + b + c
- @app.route('/')
- def index():
- return render_template('index.html', stu=student,
- stu_list=student_list,
- stu_dic=student_dict,
- tagtag=tag) # 传递参数给前端
- @app.route('/login', methods=['post', 'get'])
- def login():
- if request.method == 'get':
- return render_template('login.html')
- if request.form.get('username') == 'root' or request.form.get('password') == 'root':
- return redirect('/')
- app.run(host='0.0.0.0', debug=true)
前端展示:
- <!doctype html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>首页</title>
- </head>
- <body>
- {{ tag }} {# 后端传入标签 #}
- {{ func(1, 2) }} {# 函数调用 #}
- {{ func(1, 2) | fil(1, 2) }} {# 将 | 前面当成第一个参数传入 #}
- {% macro create_drf(na, ty) %} {# 声明函数 叫宏#}
- {# {{ na }}: {{ ty }} <input name="{{ na }}", type="{{ ty }}">#}
- {{ na + ty }}
- {% endmacro %}
- {# 调用 macro #}
- {#{{ create_drf('username', 'text') }}#}
- {{ create_drf(1, 2) }}
- <br>
- 学生信息{{ stu }}
- <table border="2px">
- <tr>
- <td>{{ stu.name }}</td> {# 三种取值的方式 #}
- <td>{{ stu.get('age' )}}</td>
- <td>{{ stu['gender'] }}</td>
- </tr>
- </table>
- {{ stu_list }}
- <table border="2px">
- {% for stu in stu_list %} {# 遍历列表 #}
- <tr>
- <td>{{ stu.name }}</td>
- <td>{{ stu.get('age')}}</td>
- <td>
- {% if stu['gender'] == '中' %} {# for循环 #}
- 男
- {% else %}
- {{ stu['gender'] }}
- {% endif %}
- </td>
- </tr>
- {% endfor %}
- </table>
- {{ stu_dic }}
- <table border="2px">
- {% for id, info in stu_dic.items() %} {# 遍历字典 keys. vals #}
- <tr>
- <td>{{ id }}</td>
- <td>{{ info.name }}</td>
- <td>{{ info.get('age') }}</td>
- <td>{{ info['gender'] }}</td>
- </tr>
- {% endfor %}
- </table>
- </body>
- </html>
session
- # -*- coding: utf-8 -*-
- from flask import flask, session, render_template, request, redirect
- app = flask(__name__)
- app.secret_key = 'ujyujyunyun#yurefrefr' # 加密字符串
- @app.route('/')
- def index():
- if not session.get('user'):
- return redirect('/login')
- return render_template('index2.html')
- @app.route('/login', methods=['post', 'get'])
- def login():
- if request.method == 'get':
- return render_template('login.html')
- if request.form.get('username') == 'root':
- session['user'] = 'peach' # 设置session,存放在了客户端(我们映像中session是存在服务端的)
- # 因为,flask 为了精简自己,不往自己和内存中添加,就是通过secret_key 加密放在客户端浏览器
- # 因此,引入的第三方组件 flask-session,相对安全解决了session存放在浏览器问题
- return redirect('/')
- app.run(host='0.0.0.0', debug=true)
装饰器
通用装饰器
- # 装饰器
- def waibu(func):
- def neibu(*args, **kwargs):
- ret = func(*args, **kwargs)
- return ret
- return neibu
- def f(a, b):
- return a + b
- # print(waibu(f)) # <function waibu.<locals>.neibu at 0x7fb86dffe2f0> 得到一个内部函数neibu
- ni = waibu(f)
- print(ni(1, 2))