flask简单应用(2)

一、母板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




    
    Title


我是母板

{% block son1 %} {% endblock %}

欢迎使用母板

{% block son2 %} {% endblock %}

templates/zujian.html

我是小小小组件

templates/macro.html

{% macro input(name,value='',type='text') %}
    
{% endmacro %}

templates/test2.html

{% extends 'base.html' %}

{% block son1 %}
    

我是继承的母板

{% include 'zujian.html' %} {% endblock %} {% block son2 %}

使用宏指令

{% 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('搜狗')
A1 = '百度'


@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




    
    Title


{{ stu }}

{{ stu_list }}
{{ stu_dict }}
{{ a }}
{{ a1|safe }}
{% for stu in stu_list %} {% if stu.name != "Old" %} {% if stu.age != 73 %} {% endif %} {% endif %} {% endfor %}
name age gender
{{ stu.name }} {{ stu.get("age") }} {{ stu["gender"] }}

{% for stu_id,stu in stu_dict.items() %} {% endfor %}
id name age gender
{{ stu_id }} {{ stu.get("name") }} {{ stu.age }} {{ stu.gender }}

name age sex
{{ name }} {{ age }} {{ sex }}

{{ my_sum(12,34,56) }}
{{ my_sum(10,12,11)|ou }}
{{ ssum(12,34,56,67) }}

三、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




    
    Title


用户名:
密码:

{{ msg }}

查看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)

你可能感兴趣的:(flask简单应用(2))