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>

flask 框架 转载:https://cloud.tencent.com/developer/article/1465949的更多相关文章

  1. 有状态(Stateful)应用的容器化 - 云+社区 - 腾讯云 https://cloud.tencent.com/developer/article/1020178

    有状态(Stateful)应用的容器化 - 云+社区 - 腾讯云 https://cloud.tencent.com/developer/article/1020178

  2. flask 框架 转载:https://cloud.tencent.com/developer/article/1465968

    特点总结: 类名称---->数据库表名 类属性---->数据库字段 类的对象----->数据库表中的一行一行数据 3.ORM操作注意(理解) 1/因为SQLALChemy去app身上 ...

  3. 我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=i5j7gwrxj9x5

    我的博客即将搬运同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=i5j7gwrxj9x5

  4. 我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cp8ng15g94wc

    我的博客即将同步至腾讯云+社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=3cp8ng15g94wc

  5. zookeeper选举状态介绍 摘自https://cloud.tencent.com/developer/news/303891

    zookeeper集群 配置多个实例共同构成一个集群对外提供服务以达到水平扩展的目的,每个服务器上的数据是相同的,每一个服务器均可以对外提供读和写的服务,这点和redis是相同的,即对客户端来讲每个服 ...

  6. Mui本地打包笔记(一)使用AndroidStudio运行项目 转载 https://blog.csdn.net/baidu_32377671/article/details/79632411

    转载 https://blog.csdn.net/baidu_32377671/article/details/79632411 使用AndroidStudio运行HBuilder本地打包的Mui项目 ...

  7. Scrapy框架的学习(6.item介绍以及items的使用(提前定义好字段名))转载https://blog.csdn.net/wei18791957243/article/details/86259688

      在Scrapy框架中的items.py的作用   1.可以预先定义好要爬取的字段     items.py import scrapy     class TencentItem(scrapy.I ...

  8. AutoFac控制反转 转载https://blog.csdn.net/u011301348/article/details/82256791

    一.AutoFac介绍 Autofac是.NET里IOC(Inversion of Control,控制反转)容器的一种,同类的框架还有Spring.NET,Unity,Castle等.可以通过NuG ...

  9. 爬虫出现Forbidden by robots.txt(转载 https://blog.csdn.net/zzk1995/article/details/51628205)

    先说结论,关闭scrapy自带的ROBOTSTXT_OBEY功能,在setting找到这个变量,设置为False即可解决. 使用scrapy爬取淘宝页面的时候,在提交http请求时出现debug信息F ...

随机推荐

  1. BOOT目录磁盘占用满处理

    背景:Ubuntu:16.04 查看已安装启动镜像 dpkg --get-selections |grep linux-image 这里会列出目前已经安装的启动镜像,一般分两种,一种状态为“insta ...

  2. 配置jdbc问题 mysql与IDEA

    1.新建lib文件夹,将jar文件导入 2在structure中添加jar文件 3设置url时需要设置时区: import java.sql.Connection;import java.sql.Dr ...

  3. todo...git ssh http的区别

    todo...git ssh http的区别 https://www.jianshu.com/p/2cced982009f https://www.cnblogs.com/skating/p/6296 ...

  4. 了解CAdoSqlserver

    include <vector> 表示引用了vector类, vector是STL中的一种数据结构,或者叫容器,功能相当于数组,但是功能强大很多.vector在C++标准模板库中的部分内容 ...

  5. Django基础之django分页

    一.Django的内置分页器(paginator) view from django.shortcuts import render,HttpResponse # Create your views ...

  6. Python重要配置大全

    PYTHON 环境安装 安装虚拟环境 pip install virtualenv 卸载包是用:pip uninstall virtualenv 快捷下载安装可用豆瓣源,方法为: pip instal ...

  7. python实战项目 — 爬取中国票房网年度电影信息并保存在csv

    import pandas as pd import requests from bs4 import BeautifulSoup import time def spider(url, header ...

  8. C++中的构造函数与析构函数及组合类的调用

    // 构造函数与析构函数及类的组合 #include "stdafx.h"#include <iostream>using namespace std; //枚举enu ...

  9. 约会II

    #include <stdio.h> int main() { int a,b; while(scanf("%d %d",&a,&b)!=EOF& ...

  10. gopacket 在 windows 上面遇到的问题

    前阵子有个需求是使用 golang 抓包改包,我用到了 gopacket 这个包,但是出了一些小问题. 我按照网上的方法进行使用 OpenLive 抓包,发现并不行,报错 error open ada ...