flask框架(二)配套代码

时间:2022-06-26
本文章向大家介绍flask框架(二)配套代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、cookie.py

"""
-  解释: 用来保持服务器和浏览器交互的状态的, 由服务器设置,存储在浏览器

- 作用: 用来做广告推送
- cookie的设置和获取
  - 设置cookie: response.set_cookie(key,value,max_age)
    - max_age: 表示cookie在浏览器的存储时间,单位是秒
  - 获取cookie: request.cookies.get("key")

"""
from flask import Flask, make_response, request

app = Flask(__name__)

#设置cookie
@app.route('/set_cookie')
def set_cookie():

    #调用make_response方法获取响应体对象
    response = make_response("set cookie")

    #设置cookie
    response.set_cookie("computer","lenovo")
    response.set_cookie("age","13",10)

    return response


#获取cookie
@app.route('/get_cookie')
def get_cookie():

    #获取cookie
    name = request.cookies.get("computer")
    age = request.cookies.get("age")

    #返回
    return "name is %s, age is %s"%(name,age)

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

2、session.py

"""
2_session[理解]

- 解释: 服务器和用户来做状态保持的,里面存储的是敏感信息(比如身份证,登陆信息),由服务器设置,并存储在服务器
- 作用: 用来做用户的登陆状态保持
- session的设置和获取
  - 设置session: sessioin[key] = value
  - 获取session: value =  session.get(key)

"""
from flask import Flask, session

app = Flask(__name__)

#设置SECRET_KEY
app.config["SECRET_KEY"] = "fjdkfhkdfjkdjf"

#设置session
@app.route('/set_session/<path:name>')
def set_session(name):

    session["name"] = name

    return "set session!"


#获取session
@app.route('/get_session')
def get_session():

    value = session.get("name")

    return "set session, name is %s"%value


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

3、context.py

"""
3_上下文[了解]

- 解释: 就是一个容器
- 请求上下文
  - request: 封装的是请求相关的数据
  - session: 封装的是和用户相关的敏感信息
- 应用上下文(在项目中具体应用)
  - current_app: 是app的一个代理对象,可以通过他获取app身上设置的各种属性,主要用在模块化开发中
  - g: 一个局部的全局变量,主要用在装饰器中

"""
from flask import Flask, current_app

app = Flask(__name__)

@app.route('/')
def hello_world():

    print(app.config.get("DEBUG"))
    print(current_app.config.get("DEBUG"))

    return "helloworld"

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

4、flask_script.py

"""
4_Flask_script[掌握]

- 解释: 属于flaks的扩展
- 作用: 用来动态运行程序,配合flask_migrate做数据库迁移
- 使用格式:
  - 1.安装
    - pip install flask_script
  - 2.导入Manager类
  - 3.创建对象manager,管理app
  - 4.使用manager启动程序
    - 启动命令: python xxx.py runserver -h(host是IP地址) -p(端口号) -d(调试模式)

"""
from flask import Flask
from flask_script import Manager

app = Flask(__name__)
app.config["DEBUG"] = True

#3.创建对象manager,管理app
manager = Manager(app)

@app.route('/')
def hello_world():

    return "helloworld"

if __name__ == '__main__':
    manager.run()

5、render_template.py

"""
5_render_template[掌握]

- 解释: 属于jinja2的模板函数
- 好处:
  - 1.以后的视图函数,只负责业务逻辑的处理,比如: 数据库的增删改查
  - 2.以后数据的展示,全部都有jinja2的模板负责
- 使用格式:
  - response = render_template('模板文件')

"""
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    response = render_template('file01template.html')

    return response

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

template.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .box{
            width: 300px;
            height: 300px;
            background: red;
        }

    </style>
</head>
<body>

    <div class="box">

    </div>

</body>
</html>

6、variable.py

"""
6_模板语法,获取变量[理解]

- 解释: 在模板中获取视图函数的变量
- 格式:
  - {{ 变量 }}

注意点:
1.如果发现程序被占用端口
2.杀死端口, lsof -i:5000  然后kill 进程

"""
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    #1.定义各种类型的变量
    number = 10
    str = "老王"
    tuple = (1,2,3,4,5)
    list = [6,7,8,9,10]
    dict = {
        "name":"班长",
        "age":29
    }

    #2.携带变量到模板中展示
    return render_template("file02variable.html",number=number,str=str,tuple=tuple,list=list,dict=dict)

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

variable.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h1>1.获取各种变量的值</h1>
    <h2>整数: {{number}}</h2>
    <h2>字符串: {{str}}</h2>
    <h2>元祖: {{tuple}},分开获取: {{tuple[0]}}, {{ tuple.1 }}</h2>
    <h2>列表: {{list}},分开获取: {{ list.0 }}, {{ list.1 }}</h2>
    {# 如果字典使用方括号,获取,需要写成字符串,如果不是字符串,那么则会被当成变量对待   #}
    <h2>字典: {{dict}}, 分开获取: {{ dict.name }}, {{ dict["age"] }}</h2>

</body>
</html>

7、otherprogrammer.py

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    #1.定义各种类型的变量
    number = 10
    str = "老王"
    tuple = (1,2,3,4,5)
    list = [6,7,8,9,10]
    dict = {
        "name":"班长",
        "age":29
    }

    #2.携带变量到模板中展示
    return render_template("file03other_programer.html",number=number,str=str,tuple=tuple,list=list,dict=dict)

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

other_programer.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        h1{
            color:red;
        }

    </style>
</head>
<body>

    <h1>1.遍历元祖中的偶数</h1>
    {% for item in tuple %}
        {% if item %2 == 0 %}
            <h3>{{ item }}</h3>
        {% endif %}
    {% endfor %}


    <h1>2.遍历字典</h1>
    {% for key in dict %}
        {# dict.key那么这个key会当成字典中的一个键,  dict[key],那么这个key当成一个变量 #}
        <h3>{{ key }} = {{ dict[key] }}</h3>
    {% endfor %}


</body>
</html>

8、srting_filter.py

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    return render_template("file04stringfilter.html")

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

stringfilter.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {#    使用格式:{{ 字符串 | 字符串过滤器 }}#}
    1.safe:禁用转义,让标签生效
    <p>{{ '<em>hello</em>' | safe }}</p>

    2.capitalize:把变量值的首字母转成大写,其余字母转小写
    <p>{{ 'hello PYTHON' | capitalize }}</p>

    3.lower:把值转成小写
    <p>{{ 'HELLO PYthON' | lower }}</p>

    4.upper:把值转成大写,中文没有大小写
    <p>{{ 'hello python 你好' | upper }}</p>

    5.title:把值中的每个单词的首字母都转成大写
    <p>{{ 'hello world python java' | title }}</p>

    6.reverse:字符串反转
    <p>{{ 'olleh' | reverse }}</p>
    <p>{{ '我爱你' | reverse }}</p>


    7.format:格式化输出
    <p>{{ '%s is %d' | format('age',17) }}</p>

    8.striptags:渲染之前把值中所有的HTML标签都删掉
    <p>{{ '<em>hello</em>' | striptags }}</p>

</body>
</html>

9、list_filter.py

from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    return render_template("file05list_fliter.html")

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

list_filter.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {#    * 使用格式:{{ 列表 | 列表过滤器 }}#}

    1.first:取第一个元素
    <p>{{ [1,2,3,4,5,6] | first }}</p>

    2. last:取最后一个元素
    <p>{{ [1,2,3,4,5,6] | last }}</p>

    3. length:获取列表长度
    <p>{{ [1,2,3,4,5,6] | length }}</p>

    4.sum:列表求和
    <p>{{ [1,2,3] | sum }}</p>

    5.sort:列表排序,默认升序
    <p>{{ [6,2,3,1,5,4] | sort }}</p>


    6.过滤器的链式调用
    {# 过滤器的链式调用 #}
    {{ "hello" | upper | reverse }}

</body>
</html>

10、custom_filter.py

"""
10_自定义过滤器[掌握]

- 解释: 当系统提供的过滤器满足不了需求的时候,需要自定义
- 自定义过滤器有两种格式:
  - 1.先定义好函数,再将函数添加到系统默认的过滤器列表中
    - def 函数名: pass
    - app.add_template_filter(函数名,'过滤器名字')
  - 2.定义函数的时候,直接使用系统过滤器进行装饰
        @app.template_filter('过滤器名字')
        def 函数名():
            pass
  - 案例:
  - 1.获取列表偶数和
  - 2.反转列表

"""
from flask import Flask,render_template

app = Flask(__name__)

# 1.先定义好函数,再将函数添加到系统默认的过滤器列表中
def get_oushu(list):
    print(list)
    sum = 0
    for i in list:
        if i %2 == 0:
            sum += i

    return sum
#参数1: 关联的函数名称,  参数2: 在模板中使用的过滤器名字
app.add_template_filter(get_oushu,"oushu")


# 2.定义函数的时候,直接使用系统过滤器进行装饰
@app.template_filter("reverse")
def listreverse(list):
    list.reverse()
    return list



@app.route('/')
def hello_world():

    return render_template("file06custom_filter.html")

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

custom_filter.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h2>原列表: {{ [1,2,3,4,5,6] }}</h2>
    <h2>偶数列表: {{ [1,2,3,4,5,6] | oushu }}</h2>
    <h2>反转列表: {{ [1,2,3,4,5,6] | reverse }}</h2>
    <h2>降序列表: {{ [1,2,3,4,5,6,10,9,7] | sort | reverse }}</h2>

</body>
</html>

11、macro.py

"""
11_代码复用之宏[了解]

- 解释: 相当于python中的函数,定义好一段功能,在需要的时候进行调用即可

"""
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    return render_template("file07macro.html")

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

macro.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {# 定义宏 #}
    {% macro my_macro(name,password) %}
        用户名: <input type="text" value="{{ name }}"><br>
        密码: <input type="password" value="{{ password }}"><br>
    {% endmacro %}

    {# 调用当前文件宏 #}
    {{ my_macro("zhangsan","111111") }}


    {# 使用其他文件的宏 #}
    {% import 'file08othermacro.html' as other %}
    {{ other.my_input() }}
    {{ other.my_div() }}


</body>
</html>

othermacro.html

{% macro my_macro(name,password) %}
    用户名: <input type="text" value="{{ name }}"><br>
    密码: <input type="password" value="{{ password }}"><br>
{% endmacro %}


{% macro my_input() %}

    <h1>这是一个其他文件的宏</h1>

{% endmacro %}


{% macro my_div() %}

    <div style="color: red;">我是一个孤独的div</div>

{% endmacro %}

12、extends.py

"""
12_代码复用之继承[掌握]

- 解释: 一个子模板继承自父模板
- 作用: 共性抽取,代码复用
- 父模板
  - 1.所有子类都具有的相同的内容的, 在父模板中直接写死
  - 2.每个子类的模板中不一样的内容,使用block模板定义好
- 子模板
  - 1.根据子类自己的需求,去重写父类中的block对应的内容
  - 2.如果重写之后,还想保留父类的内容,那么使用{{super()}}
  - 3.继承格式: {% extends '父文件名'%}, 写在页面的顶部

"""
from flask import Flask,render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    # return render_template("file09zi.html")
    return render_template("file10zi.html")

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

file09zi.html

{% extends 'file11fu.html' %}

{# 重写正文部分 #}
{% block contentBlock %}
    <p>
        床前一锅汤,<br>
        撒了一裤裆, <br>
        抬头拿抹布, <br>
        低头擦裤裆 <br>
    </p>
{% endblock %}


{#<!DOCTYPE html>#}
{#<html lang="en">#}
{#<head>#}
{#    <meta charset="UTF-8">#}
{#    <title>Title</title>#}
{#</head>#}
{#<body>#}
{##}
{#    <h1>静夜思</h1>#}
{##}
{#    <p>#}
{#        床前一锅汤,<br>#}
{#        撒了一裤裆, <br>#}
{#        抬头拿抹布, <br>#}
{#        低头擦裤裆 <br>#}
{#    </p>#}
{##}
{#    <div>#}
{#        <a href="#">点我有惊喜</a>#}
{#    </div>#}
{##}
{##}
{#</body>#}
{#</html>#}

file10zi.html

{% extends 'file11fu.html' %}

{# 重写父类titleBlock内容 #}
{% block titleBlock %}
    {{ super() }}
    <h1>新静夜思</h1>
{% endblock %}

{# 重写父类中的contentBlock内容 #}
{% block contentBlock %}
    <p>
        床前明月光,<br>
        疑似地上霜, <br>
        举头望明月, <br>
        低头思故乡 <br>
    </p>
{% endblock %}

{#<!DOCTYPE html>#}
{#<html lang="en">#}
{#<head>#}
{#    <meta charset="UTF-8">#}
{#    <title>Title</title>#}
{#</head>#}
{#<body>#}
{##}
{#    <h1>静夜思</h1>#}
{##}
{#    <p>#}
{#        床前明月光,<br>#}
{#        疑似地上霜, <br>#}
{#        举头望明月, <br>#}
{#        低头思故乡 <br>#}
{#    </p>#}
{##}
{#    <div>#}
{#        <a href="#">点我有惊喜</a>#}
{#    </div>#}
{##}
{##}
{#</body>#}
{#</html>#}

file11fu.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    {# 头部部分 #}
    {% block titleBlock %}
        <h1>静夜思</h1>
    {% endblock %}

    {# 正文部分 #}
    {% block contentBlock %}

    {% endblock %}


    {# 底部部分 #}
    <div>
        <a href="#">点我有惊喜</a>
    </div>

</body>
</html>

13.practice.py

"""
给定如下5条数据,只显示4行数据,背景颜色依次为:黄,绿,红,紫
my_list = [
    {
        "id": 1,
        "value": "我爱工作"
    },
    {
        "id": 2,
        "value": "工作使人快乐"
    },
    {
        "id": 3,
        "value": "沉迷于工作无法自拔"
    },
    {
        "id": 4,
        "value": "日渐消瘦"
    },
    {
        "id": 5,
        "value": "以梦为马,越骑越傻"
    }
]
"""
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():

    #1.定义5条数据
    my_list = [
        {
            "id": 1,
            "value": "我爱工作"
        },
        {
            "id": 2,
            "value": "工作使人快乐"
        },
        {
            "id": 3,
            "value": "沉迷于工作无法自拔"
        },
        {
            "id": 4,
            "value": "日渐消瘦"
        },
        {
            "id": 5,
            "value": "以梦为马,越骑越傻"
        }
    ]

    #2.在模板中显示4条
    return render_template("file13practice.html",list=my_list)

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

file13practice.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <ul>
        {# 如果dict.id 不等于5才遍历 #}
        {% for dict in list if dict.id !=5 %}

            {# 方式一 #}
{#            {% if dict.id == 1 %}#}
{#                <li style="background: yellow;"> {{ dict.value }} </li>#}
{#            {% elif dict.id == 2 %}#}
{#                <li style="background: green;"> {{ dict.value }} </li>#}
{#            {% elif dict.id == 3 %}#}
{#                <li style="background: red;"> {{ dict.value }} </li>#}
{#            {% else %}#}
{#                <li style="background: purple;"> {{ dict.value }} </li>#}
{#            {% endif %}#}

            {# 遍历的时候可以获取到从0开始的索引 #}
{#            <h3>{{ loop.index0  }}</h3>#}

            {# 遍历的时候可以获取到从1开始的索引 #}
{#            <h3>{{ loop.index  }}</h3>#}


            {# 方式二 #}
            {% if loop.index == 1 %}
                <li style="background: yellow;"> {{ dict.value }} </li>
            {% elif loop.index == 2 %}
                <li style="background: green;"> {{ dict.value }} </li>
            {% elif loop.index == 3 %}
                <li style="background: red;"> {{ dict.value }} </li>
            {% else %}
                <li style="background: purple;"> {{ dict.value }} </li>
            {% endif %}



        {% endfor %}
    </ul>


</body>
</html>

14.special_variable.py

from flask import Flask,render_template

app = Flask(__name__)
app.config["SECRET_KEY"] ="hahaha"
@app.route('/')
def hello_world():

    return render_template("file14special_variable.html")

@app.route('/test/<int:age>')
def test(age):
    return "test..."


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

file14special_variable.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <h2>config变量: {{ config }}</h2>
    <h2>request: {{ request.method }}</h2>
    <h2>request: {{ request.url }}</h2>
    <h2>url_for(): {{ url_for("hello_world") }}</h2>
    <h2>url_for(): {{ url_for("test",age=100) }}</h2>

</body>
</html>

15.flash.py

from flask import Flask,render_template,flash

app = Flask(__name__)
app.config["SECRET_KEY"] = "fdjkfjdk"

@app.route('/')
def hello_world():



    return render_template("file15flash.html")

@app.route('/test')
def test():
    #存储消息
    flash("登陆成功")

    return "test"

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

file15flash.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>


    {{ get_flashed_messages() }}

</body>
</html>