python-Web-flask-视图内容和模板知识点西宁街
作者:一觉昏睡人 时间:2021-03-10 22:21:15
基本使用
#设置cookie值
@app.route('/set_cookie')
def set_cookie():
response = make_response("set_cookie")
response.set_cookie("name","zhangsan")
response.set_cookie("age","13",10) #10秒有效期
return response
#获取cookie
@app.route('/get_cookie')
def get_cookie():
#获取cookie,可以根据cookie的内容来推荐商品信息
# name = request.cookies['haha']
name = request.cookies.get('name')
age = request.cookies.get('age')
return "获取cookie,name is %s, age is %s"%(name,age)
#设置SECRET_KEY
app.config["SECRET_KEY"] = "fhdk^fk#djefkj&*&*&"
#设置session
@app.route('/set_session/<path:name>')
def set_session(name):
session["name"] = name
session["age"] = "13"
return "set session"
#获取session内容
@app.route('/get_session')
def get_session():
name = session.get('name')
age = session.get('age')
return "name is %s, age is %s"%(name,age)
session的存储依赖于cookie,在cookie保存的session编号
session编号生成,需要进行加密,所以需要设置secret_key secret_key的作用参考:
https://segmentfault.com/q/1010000007295395
上下文:保存的一些配置信息,比如程序名、数据库连接、应用信息等
相当于一个容器,保存了 Flask 程序运行过程中的一些信息。
Flask中有两种:请求上下文(session,cookie),应用上下文(current_app,g)
current_app,g是全局变量:
current_app.test_value='value'
g.name='abc' # g是一个响应里的全局变量可跨文件
渲染模板:
from flask import Flask,render_template
app = Flask(__name__) #默认省略了三个参数,static_url_path, static_folder, template_folders
def adds(a,b):
return a+b
@app.route('/')
def hello_world():
#定义数据,整数,字符串,元祖,列表,字典,函数
num = 10
str = "hello"
tuple = (1,2,3,4)
list = [5,6,7,8]
dict = {
"name":"张三",
"age":13
}
return render_template('file01.html',my_num=num,my_str=str,my_tuple=tuple,my_list=list,my_dict=dict,adds=adds)
《html》
{{}},{{dict[‘name']}},{{dict.get(‘name')}}和{%%},{{adds(1,2)}}
# 模板全局--直接使用
@app.template_global('adds')
def adds(a,b):
return a+b
过滤器&自定义过滤器
{{ 字符串 | 字符串过滤器 }}
Safe,lower,upper,little,reverse,format
{#防止转义#}
{{ str1 | safe}} 或 在方法里str2 = Markup("<b>只有学习才能让我快乐</b>")
{{ 列表 | 列表过滤器 }}
First,last,length,sum,sort
def do_listreverse(li):
# 通过原列表创建一个新列表
temp_li = list(li)
# 将新列表进行返转
temp_li.reverse()
return temp_li
app.add_template_filter(do_listreverse,'lireverse') # 或1
@app.template_filter('lireverse') # 或2
def do_listreverse(li):
# 通过原列表创建一个新列表
temp_li = list(li)
# 将新列表进行返转
temp_li.reverse()
return temp_li
<h2>my_array 原内容:{{ my_array }}</h2>
<h2> my_array 反转:{{ my_array | lireverse }}</h2>
宏、继承、包含
宏
{% macro input(name,value='',type='text') %}
<input type="{{type}}" name="{{name}}" value="{{value}}">
{% endmacro %}
{{ input('name',value='zs')}} // 调用
继承
父模板base:
{% block top %}
顶部菜单
{% endblock top %}
子模板:
{% extends 'base.html' %}
{% block content %}
需要填充的内容
{% endblock content %}
包含
{% include 'hello.html' %}
Flask 的模板 * 有变量和方法
{{config.DEBUG}}
输出:True
{{request.url}}
输出:http://127.0.0.1
{{ g.name }}
{{url_for('home')}} // url_for 会根据传入的路由器函数名,返回该路由对应的URL
{{ url_for('post', post_id=1)}}
这个函数会返回之前在flask中通过flask()传入的消息的列表,flash函数的作用很简单,可以把由Python字符串表示的消息加入一个消息队列中,再使用get_flashed_message()函数取出它们并消费掉
{%for message in get_flashed_messages()%}
{{message}}
{%endfor%}
模板规则:
<form action="{{ url_for('login') }}" method="post">
<link rel="stylesheet" href="{{ url_for('static',filename='css.css') }}" rel="external nofollow" >
web表单
if request.method == 'POST':
# post请求的数据
print(request.form.get('uname'))
print(request.form.get('upass'))
# 存session
return redirect("/")
# get请求的数据
print(request.args.get('uname'))
print(request.args.get('upass'))
# post请求的数据
print(request.form.get('uname'))
print(request.form.get('upass'))
CSRF
from flask_wtf import CSRFProtect
#设置SECRET_KEY
app.config["SECRET_KEY"] = "fjkdjfkdfjdk"
#保护应用程序
CSRFProtect(app)
{#设置隐藏的csrf_token,使用了CSRFProtect保护app之后,即可使用csrf_token()方法#}
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
希望以上整理的内容能够帮助到大家,感谢大家对脚本之家的支持。
来源:https://www.cnblogs.com/person1-0-1/p/11400612.html
标签:python-Web-flask,视图,模板


猜你喜欢
Python实现的金山快盘的签到程序
2022-12-05 21:14:51
描述性列表的表现形式
2008-09-17 13:43:00
链接与文本标签们
2008-04-04 18:07:00
Python Pandas处理CSV文件的常用技巧分享
2022-06-18 12:56:19

ORACLE应用经验(1)
2010-07-31 12:53:00
python3 写一个WAV音频文件播放器的代码
2023-04-09 05:06:36
ASP.NET获取不到JS设置cookies的解决方法
2023-07-19 08:07:08
Python 中 Meta Classes详解
2023-06-02 11:52:47
浅谈django url请求与数据库连接池的共享问题
2024-01-26 00:12:40

自己动手用Golang实现约瑟夫环算法的示例
2024-04-23 09:48:50

Pandas直接读取sql脚本的方法
2022-08-16 20:16:34

Python机器学习pytorch交叉熵损失函数的深刻理解
2021-12-11 06:09:40

使用PHP 5.0创建图形的巧妙方法
2023-10-27 00:59:07
Git 教程之工作区、暂存区和版本库详解
2022-11-28 04:07:40

浅谈Pandas dataframe数据处理方法的速度比较
2023-04-17 06:38:39
vue实现父子组件之间的通信以及兄弟组件的通信功能示例
2024-05-21 10:15:43

Python使用shutil操作文件、subprocess运行子程序
2021-03-01 00:19:19
关于“简单,可依赖”
2008-10-22 13:33:00
Python提取视频帧图片实例代码
2023-02-11 18:15:21

Python3如何使用多线程升程序运行速度
2023-02-06 05:11:42