- 基本
- request
- response
- 闪现
- 请求扩展
- 运行错误时也会执行(必须关掉debug)
- 可以在前端直接通过{{labe(a,b)}}调用
- 可以在前端直接通过{{a|filet(b,c)}}调用
- 信号
- 1. template_rendered:模版渲染完成后的信号。
- 2. before_render_template:模版渲染之前的信号。
- 3. request_started:模版开始渲染。
- 4. request_finished:模版渲染完成。
- 5. request_tearing_down:request对象被销毁的信号。
- 6. got_request_exception:视图函数发生异常的信号。一般可以监听这个信号,来记录网站异常信息。
- 7. appcontext_tearing_down:app上下文被销毁的信号。
- 8. appcontext_pushed:app上下文被推入到栈上的信号。
- 9. appcontext_popped:app上下文被推出栈中的信号
- 10. message_flashed:调用了Flask的
flashed方法的信号。
基本
设置cookie:
from flask import make_response
response=make_response(‘返回内容’)
response.set_cookie() exipre=None #关闭浏览器时失效
重定向
from flask import redirect return redirect(“url”)
404
from flask import abort abort(404)
渲染模板
return render_template(‘html文件’,传入数据(字典形式))
防止表单攻击
app=Flask(name)
app.config[‘SECRET_KEY’]=’hard to guess string’
request
args
from
method
values
cookies
headers
path
full_path
url
response
response=make_response()
创建名为response的response对象
传入的值是可以return的对象
response.set_cookie(‘key’,’value’)
response.headers[‘key’]=’value’
闪现
flash(‘内容’,category=’key’)
get_flashed_messages(category_filter[‘key’])
取出flash
请求扩展
请求来时触发
@app.before_request
def before():
pass
请求结束时触发
@app.after_request
def after(response):
return response
每次触发视图函数时执行
@app.teardown_request
def tear():
pass运行错误时也会执行(必须关掉debug)
当出现相应错误码时执行
@app.errorhandler(500)
def error_500():
pass
全局标签
@app.template_global
def labe(a,b):
return a+b可以在前端直接通过{{labe(a,b)}}调用
全局过滤器
@app.template_filter
def filet(a,b,c):
return a+b+c可以在前端直接通过{{a|filet(b,c)}}调用
数据库连接池
from dbutils.persistent_db import PersistentDB
import pymysql
POOL = PersistentDB(
creator=pymysql, #使用连接数据库的模块
maxusage=None, #一个链接最多被重复使用的次数,None表示无限制
setsession=[], #开始会话前执行的命令列表
ping=0, #ping MySQL服务端检测是否可用
closeable=False, #如果维False时,conn.close()实际上被忽略,供下次使用,在线程关闭时,才会自动关闭链接,如果为True,conn.close()则关闭链接,那么猜词调用时会报错
threadlocal=None, #单线程独享值得对象,用于保存链接对象
host=’127.0.0.1’,
port=3306,
user=’root’,
password=’000000’,
database=’first’,
charset=’utf8’
)
def func():
conn = POOL.connection(shareable=False)
cursor = conn.cursor()
cursor.execute(‘select * from user’)
result = cursor.fetchall()
print(result)
cursor.close()
conn.close()
信号
def xinhao():
passsignals.request_started.connect(xinhao)
1. template_rendered:模版渲染完成后的信号。
2. before_render_template:模版渲染之前的信号。
3. request_started:模版开始渲染。
4. request_finished:模版渲染完成。
5. request_tearing_down:request对象被销毁的信号。
6. got_request_exception:视图函数发生异常的信号。一般可以监听这个信号,来记录网站异常信息。
7. appcontext_tearing_down:app上下文被销毁的信号。
8. appcontext_pushed:app上下文被推入到栈上的信号。
9. appcontext_popped:app上下文被推出栈中的信号
10. message_flashed:调用了Flask的
flashed方法的信号。
