一、母板include和extend
二、jinjia2模板语法
三、使用session
四、使用flask_session
五、make_response
一、flask_demo1 模板include和extend
py文件
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/test2')
def test2():
return render_template('test2.html')
if __name__ == '__main__':
app.run()
templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1 style="color: #CD1C1C">我是母板</h1>
{% block son1 %}
{% endblock %}
<h1 style="color: #CD1C1C">欢迎使用母板</h1>
{% block son2 %}
{% endblock %}
</body>
</html>
templates/zujian.html
<h4 style="color: #ec971f">我是小小小组件</h4>
templates/macro.html
{% macro input(name,value='',type='text') %}
<input type="{{type}}" name="{{name}}"
value="{{value}}" class="form-control">
{% endmacro %}
templates/test2.html
{% extends 'base.html' %}
{% block son1 %}
<h3 style="color: #04b141">我是继承的母板</h3>
{% include 'zujian.html' %}
{% endblock %}
{% block son2 %}
<h3>使用宏指令</h3>
{% import 'macro.html' as func %}
{{ func.input('username','欢迎使用宏') }}
{% endblock son2 %}
二、flask_demo2 jinjia2模板语法
py文件
from flask import Flask, render_template, Markup
app = Flask(__name__)
STUDENT = {'name': '张三', 'age': 20, 'sex': '男'}
STUDENT_LIST = [
{'name': 'aaa', 'age': 38, 'gender': '中'},
{'name': 'bbb', 'age': 73, 'gender': '男'},
{'name': 'ccc', 'age': 84, 'gender': '女'}
]
STUDENT_DICT = {
1: {'name': 'aaa', 'age': 38, 'gender': '中'},
2: {'name': 'bbb', 'age': 73, 'gender': '男'},
3: {'name': 'ccc', 'age': 84, 'gender': '女'},
}
A = Markup('<a href="https://www.sogou.com/">搜狗</a>')
A1 = '<a href="https://www.baidu.com/">百度</a>'
@app.template_global() # 自定义全局模板,不用传参
def my_sum(*args):
return sum(args)
@app.template_filter() # 自定义过滤器
def ou(sum):
if not sum % 2:
return '偶数'
else:
return '奇数'
def ssum(*args):
return sum(args) / 100
@app.route('/test')
def dict_test():
return render_template('test.html',
stu=STUDENT,
**STUDENT,
stu_list=STUDENT_LIST,
stu_dict=STUDENT_DICT,
a=A,
a1=A1,
ssum=ssum, # 自定义的函数,只能自己用,且必须传
)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9527, debug=True)
templates/test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ stu }}
<hr>
{{ stu_list }}
<hr>
{{ stu_dict }}
<hr>
{{ a }}
<hr>
{{ a1|safe }}
<hr>
<table border="1px">
<tr>
<td>name</td>
<td>age</td>
<td>gender</td>
</tr>
{% for stu in stu_list %}
{% if stu.name != "Old" %}
{% if stu.age != 73 %}
<tr>
<td>{{ stu.name }}</td>
<td>{{ stu.get("age") }}</td>
<td>{{ stu["gender"] }}</td>
</tr>
{% endif %}
{% endif %}
{% endfor %}
</table>
<hr>
<table border="1px">
<tr>
<td>id</td>
<td>name</td>
<td>age</td>
<td>gender</td>
</tr>
{% for stu_id,stu in stu_dict.items() %}
<tr>
<td>{{ stu_id }}</td>
<td>{{ stu.get("name") }}</td>
<td>{{ stu.age }}</td>
<td>{{ stu.gender }}</td>
</tr>
{% endfor %}
</table>
<hr>
<table border="1px">
<tr>
<td>name</td>
<td>age</td>
<td>sex</td>
</tr>
<tr>
<td>{{ name }}</td>
<td>{{ age }}</td>
<td>{{ sex }}</td>
</tr>
</table>
<hr>
{{ my_sum(12,34,56) }}
<hr>
{{ my_sum(10,12,11)|ou }}
<hr>
{{ ssum(12,34,56,67) }}
</body>
</html>
三、flask_demo3 使用session
from flask import Flask, render_template, request, session,redirect
app = Flask(__name__)
app.secret_key = 'SSSVVVPPPEEEDDD_hhhhh_ddddd_ggggg' #【第一步:secret_key】
@app.route('/index')
def index():
if not session.get('user'): # 【第三步:获取session】
return redirect('/session_test')
return render_template('index.html')
@app.route('/session_test', methods=('GET', 'POST'))
def session_test():
msg = ''
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == 'zhangsan' and password == '123':
session['user'] = username # 【第二步:设置session】
# session['user'] = username+'aaaaaaa'
return redirect('/index')
else:
msg = '用户名或密码不对'
return render_template('login.html', msg=msg)
if __name__ == '__main__':
app.run()
四、flask_demo4 使用flask_session
py文件 (需要pip install flask_session 和 下载 redis)
from flask import Flask, session, request, render_template, redirect
from flask_session import Session
from redis import Redis
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["SESSION_TYPE"] = "redis" # 【第一步】
app.config["SESSION_REDIS"] = Redis(host="127.0.0.1", port=6379, db=5) # 【第二步】
# 这个db啊,做数据隔离用的,总共有16个,0-15.
app.config["SESSION_KEY_PREFIX"] = 'session' # 保存到session中的值的前缀
app.config["PERMANENT_SESSION_LIFETIME"] = 10 # 过期单位是秒,默认是31天
Session(app) # 【第三步】
@app.route('/index')
def index():
if not session.get('user'): # 【第五步:获取session】
return redirect('/login')
return session.get('user')
@app.route('/login', methods=('GET', 'POST'))
def login():
msg = ''
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if username == 'zhangsan' and password == '123':
session['user'] = username # 【第四步:设置session】
return redirect('/index')
else:
msg = '用户名或密码不对'
return render_template('login.html', msg=msg)
if __name__ == '__main__':
app.run()
# 使用原生session的session值:eyJ1c2VyIjoiemhhbmdzYW4ifQ.Dp5B9w.4LVnd0SLQpbmk_KYinH1Fz8hqQc
# 使用flask_session之后的session值:abd3583f-63f8-4689-a084-d9a20baac3b9
templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
用户名:
<input type="text" name="username">
<br>
密码:
<input type="text" name="password">
<br>
<input type="submit" value="提交">
</form>
<p>{{ msg }}</p>
</body>
</html>
查看redis中的session值
import redis
redis = redis.Redis(host="127.0.0.1", port=6379, db=5)
print(redis.keys())
# [b'session:e7fa0ec3-0c46-44fd-9f7d-77d669ba5357']
ret = redis.get('session:e7fa0ec3-0c46-44fd-9f7d-77d669ba5357')
print(ret)
五、flask_demo5 make_response自定制响应头,下载小文件
## -*- coding:utf-8 -*-
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/')
def index():
with open('双击666.txt', 'r', encoding='utf-8')as f:
content = f.read()
resp = make_response(content)
# 设置将内容写到磁盘里
resp.headers['Content-Disposition'] = 'attachment;filename=hehe.txt'
return resp
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9527)
网友评论