Flask框架之功能详解
1|0浏览目录
1|1配置文件
知识点
给你一个路径 “settings.Foo”,可以找到类并获取其中的大写的静态字段。
settings.py
1
2
3
|
class Foo: DEBUG = True TEST = True |
xx.py
1
2
3
4
5
6
7
8
9
10
11
12
|
import importlib path = "settings.Foo" p,c = path.rsplit( '.' ,maxsplit = 1 ) m = importlib.import_module(p) cls = getattr (m,c) # 如果找到这个类? for key in dir ( cls ): if key.isupper(): print (key, getattr ( cls ,key)) |
配置相关
importlib模块
实现机制:根据字符串的形式导入模块,通过反射找到里面的内容,有一个特点,只有全部大写才能被读到。
导入方式:app.config.from_object()
默认配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
flask中的配置文件是一个flask.config.Config对象(继承字典),默认配置为: { 'DEBUG' : get_debug_flag(default = False ), 是否开启Debug模式 'TESTING' : False , 是否开启测试模式 'PROPAGATE_EXCEPTIONS' : None , 'PRESERVE_CONTEXT_ON_EXCEPTION' : None , 'SECRET_KEY' : None , 'PERMANENT_SESSION_LIFETIME' : timedelta(days = 31 ), 'USE_X_SENDFILE' : False , 'LOGGER_NAME' : None , 'LOGGER_HANDLER_POLICY' : 'always' , 'SERVER_NAME' : None , 'APPLICATION_ROOT' : None , 'SESSION_COOKIE_NAME' : 'session' , 'SESSION_COOKIE_DOMAIN' : None , 'SESSION_COOKIE_PATH' : None , 'SESSION_COOKIE_HTTPONLY' : True , 'SESSION_COOKIE_SECURE' : False , 'SESSION_REFRESH_EACH_REQUEST' : True , 'MAX_CONTENT_LENGTH' : None , 'SEND_FILE_MAX_AGE_DEFAULT' : timedelta(hours = 12 ), 'TRAP_BAD_REQUEST_ERRORS' : False , 'TRAP_HTTP_EXCEPTIONS' : False , 'EXPLAIN_TEMPLATE_LOADING' : False , 'PREFERRED_URL_SCHEME' : 'http' , 'JSON_AS_ASCII' : True , 'JSON_SORT_KEYS' : True , 'JSONIFY_PRETTYPRINT_REGULAR' : True , 'JSONIFY_MIMETYPE' : 'application/json' , 'TEMPLATES_AUTO_RELOAD' : None , } |
修改配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
|
方式一: app.config[ 'DEBUG' ] = True PS: 由于Config对象本质上是字典,所以还可以使用app.config.update(...) 方式二: app.config.from_pyfile( "python文件名称" ) 如: settings.py DEBUG = True app.config.from_pyfile( "settings.py" ) app.config.from_envvar( "环境变量名称" ) 环境变量的值为python文件名称名称,内部调用from_pyfile方法 app.config.from_json( "json文件名称" ) JSON文件名称,必须是json格式,因为内部会执行json.loads app.config.from_mapping({ 'DEBUG' : True }) 字典格式 app.config.from_object( "python类或类的路径" ) 如:app.config.from_object( 'pro_flask.settings.TestingConfig' ) settings.py class Config( object ): DEBUG = False TESTING = False DATABASE_URI = 'sqlite://:memory:' class ProductionConfig(Config): DATABASE_URI = 'mysql://user@localhost/foo' class DevelopmentConfig(Config): DEBUG = True class TestingConfig(Config): TESTING = True PS: 从sys.path中已经存在路径开始写 PS: settings.py文件默认路径要放在程序root_path目录,如果instance_relative_config为 True ,则就是instance_path目录 |
常用:app.config.from_object()
1|2路由系统
本质:带参数的装饰器和闭包实现的。
@app.route('/user/<username>')
@app.route('/post/<int:post_id>')
@app.route('/post/<float:post_id>')
@app.route('/post/<path:path>')
@app.route('/login', methods=['GET', 'POST'])
常用路由系统有以上五种,所有的路由系统都是基于一下对应关系来处理:
1
2
3
4
5
6
7
8
9
|
DEFAULT_CONVERTERS = { 'default' : UnicodeConverter, 'string' : UnicodeConverter, 'any' : AnyConverter, 'path' : PathConverter, 'int' : IntegerConverter, 'float' : FloatConverter, 'uuid' : UUIDConverter, } |
总结:
- app.route()支持三个参数:url、method、endpoint(相当于django中的name);
- endpoint:反向生成url,如果不写,默认为函数名,用url_for 反向生成url
- 动态路由:一定要有视图函数接收。如果显示列表页面,需要传id,就要有一个地方接收。app.route('/post/<int:id>'),如上五种方法。限制参数类型。注意:它只支持这几种类型,不支持正则表达式。
- 如果带参数,如何反向生成:
1
2
3
4
|
@app .route( '/index/<int:nid>' ,methods = [ "GET" , "POST" ]) def index(nid): url_for( "index" ,nid = 1 ) #/index/1 return "Index" |
- 没有参数:url_for('endpoint'),有参数:url_for("index",nid=777)
1|3视图
FBV
1|4请求相关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
# 请求相关信息 request.method request.args request.form request.values request.cookies request.headers request.path request.full_path request.script_root request.url request.base_url request.url_root request.host_url request.host request.files #上传文件 obj = request.files[ 'the_file_name' ] #拿到上传的文件名 obj.save( '/var/www/uploads/' + secure_filename(f.filename)) #将文件保存,写到本地的路径 |
1|5响应
1
2
3
4
5
|
# 响应相关信息 return "字符串" return jsonify({ 'k1' : 'v1' }) #内部帮我们序列化 return render_template( 'html模板路径' , * * {}) return redirect( '/index.html' ) #重定向 |
注:jsonify内部帮我们序列化,跟django的jsonresponse有点相似。
我们返回的都是响应体,页面可以看到的。那我们如何加响应头?
如果我们想要返回相关的信息时,可以通过make_response将我们的内容封装起来。
1
2
3
4
|
response = make_response(render_template( 'index.html' )) # response是flask.wrappers.Response类型 response.headers[ 'X-Something' ] = 'A value' #加响应头 return response |
那我们可以设置cookie吗?
1
2
3
4
5
6
|
response = make_response(render_template( 'index.html' )) # response是flask.wrappers.Response类型 response.delete_cookie( 'key' ) response.set_cookie( 'key' , 'value' ) return response |
1|6模板渲染
1、模板的使用
Flask使用的是Jinja2模板,所以其语法和Django无差别
2、自定义模板方法
Flask中自定义模板方法的方式和Bottle相似,创建一个函数并通过参数的形式传入render_template,如:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>自定义函数</h1>
{{ww()|safe}} </body>
</html>
HTML
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template
app = Flask(__name__) def wupeiqi():
return '<h1>yaya</h1>' @app.route('/login', methods=['GET', 'POST'])
def login():
return render_template('login.html', ww=yaya) app.run()
run.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>{</span>% macro input(name, type=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">text</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>, value=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">''</span>) %<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">}
</span><input type=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">{{ type }}</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span> name=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">{{ name }}</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span> value=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">{{ value }}</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span>><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">
{</span>% endmacro %<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">} {{ input(</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">n1</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">) }} {</span>% include <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">tp.html</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span> %<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">} </span><h1>asdf{{ v.k1}}</h1>
</body>
</html>
其他
注意:Markup等价django的mark_safe
模板详细用法
基本数据类型
可以执行python语法,如:dict.get(),list["xx"]
传入函数
Django中函数自动加括号执行;
Flask中不自动执行,需要自己主动执行,可以传参数。
全局定义函数
1
2
3
4
5
6
7
8
9
|
@app .template_global() def sb(a1, a2): # {{sb(1,9)}} return a1 + a2 @app .template_filter() def db(a1, a2, a3): # {{ 1|db(2,3) }} return a1 + a2 + a3 |
模板继承
layout.html
1
2
3
4
5
6
7
8
9
10
11
12
|
<! DOCTYPE html> < html lang="zh-CN"> < head > < meta charset="UTF-8"> < title >Title</ title > < meta name="viewport" content="width=device-width, initial-scale=1"> </ head > < body > < h1 >模板</ h1 > {% block content %}{% endblock %} </ body > </ html > |
tpl.html
1
2
3
4
5
6
7
|
{% extends "layout.html"%} {% block content %} {{users.0}} {% endblock %} |
include
1
2
3
4
5
6
7
8
|
{% include "form.html" %} form.html < form > asdfasdf asdfasdf </ form > |
宏
1
2
3
4
5
|
{ % macro ccccc(name, type = 'text' , value = '') % } <h1>宏< / h1> < input type = "{{ type }}" name = "{{ name }}" value = "{{ value }}" > < input type = "submit" value = "提交" > { % endmacro % } |
#默认不显示,相当于定义了函数没执行,想要执行,需要调用
要用几次,就调用几遍
1
2
3
|
{{ ccccc( 'n1' ) }} {{ ccccc( 'n2' ) }} |
安全
前端做法
1
|
{{u|safe}} |
后端做法
1
|
MarkUp( "asdf" ) |
注:Flask中的markup相当于Django中的mark_safe.
1|7session
除请求对象之外,还有一个 session 对象。它允许你在不同请求间存储特定用户的信息。它是在 Cookies 的基础上实现的,并且对 Cookies 进行密钥签名要使用会话,你需要设置一个密钥。
设置:session['username'] = 'xxx'
- 删除:session.pop('username', None)
from flask import Flask, session, redirect, url_for, escape, request app = Flask(name) @app.route('/')
def index():
if 'username' in session:
return 'Logged in as %s' % escape(session['username'])
return 'You are not logged in' @app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
session['username'] = request.form['username']
return redirect(url_for('index'))
return '''
<form action="" method="post">
<p><input type=text name=username>
<p><input type=submit value=Login>
</form>
''' @app.route('/logout')
def logout():
# remove the username from the session if it's there
session.pop('username', None)
return redirect(url_for('index')) # set the secret key. keep this really secret:
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
基本使用
pip3 install Flask-Sessionrun.py
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> flask <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> Flask
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> flask <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> session
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> pro_flask.utils.session <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> MySessionInterface
app </span>= Flask(<span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__name__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">) app.secret_key </span>= <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">A0Zr98j/3yX R~XHH!jmN]LWX/,?RT</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">
app.session_interface </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> MySessionInterface() @app.route(</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">/login.html</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>, methods=[<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">GET</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>, <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">POST</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">])
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> login():
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">print</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(session)
session[</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">user1</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>] = <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">alex</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">
session[</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">user2</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>] = <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">alex</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span>
<span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">del</span> session[<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">user2</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">] </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">内容</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"</span> <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">if</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__name__</span> == <span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">__main__</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">:
app.run() session.py
</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">!/usr/bin/env python</span>
<span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> -*- coding:utf-8 -*-</span>
<span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> uuid
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> json
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> flask.sessions <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> SessionInterface
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> flask.sessions <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> SessionMixin
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">from</span> itsdangerous <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> Signer, BadSignature, want_bytes </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">class</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> MySession(dict, SessionMixin):
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__init__</span>(self, initial=None, sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">None):
self.sid </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> sid
self.initial </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> initial
super(MySession, self).</span><span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__init__</span>(initial <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">or</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> ()) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__setitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(self, key, value):
super(MySession, self).</span><span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__setitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(key, value) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__getitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(self, item):
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> super(MySession, self).<span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__getitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(item) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__delitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(self, key):
super(MySession, self).</span><span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__delitem__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(key) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">class</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> MySessionInterface(SessionInterface):
session_class </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> MySession
container </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> {} </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span> <span style="color: rgb(128, 0, 128); background-color: rgb(246, 248, 250);">__init__</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">(self):
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">import</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> redis
self.redis </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> redis.Redis() </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> _generate_sid(self):
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> str(uuid.uuid4()) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> _get_signer(self, app):
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">if</span> <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">not</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> app.secret_key:
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> None
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> Signer(app.secret_key, salt=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">flask-session</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">,
key_derivation</span>=<span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">hmac</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">'</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> open_session(self, app, request):
</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"""</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">
程序刚启动时执行,需要返回一个session对象
</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"""</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">
sid </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> request.cookies.get(app.session_cookie_name)
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">if</span> <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">not</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> sid:
sid </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self._generate_sid()
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> self.session_class(sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">sid) signer </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self._get_signer(app)
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">try</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">:
sid_as_bytes </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> signer.unsign(sid)
sid </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> sid_as_bytes.decode()
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">except</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> BadSignature:
sid </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self._generate_sid()
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> self.session_class(sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">sid) </span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> session保存在redis中</span>
<span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> val = self.redis.get(sid)</span>
<span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> session保存在内存中</span>
val =<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.container.get(sid) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">if</span> val <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">is</span> <span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">not</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> None:
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">try</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">:
data </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> json.loads(val)
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> self.session_class(data, sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">sid)
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">except</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">:
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> self.session_class(sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">sid)
</span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">return</span> self.session_class(sid=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">sid) </span><span style="color: rgb(0, 0, 255); background-color: rgb(246, 248, 250);">def</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> save_session(self, app, session, response):
</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"""</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">
程序结束前执行,可以保存session中所有的值
如:
保存到resit
写入到用户cookie
</span><span style="color: rgb(128, 0, 0); background-color: rgb(246, 248, 250);">"""</span><span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">
domain </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.get_cookie_domain(app)
path </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.get_cookie_path(app)
httponly </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.get_cookie_httponly(app)
secure </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.get_cookie_secure(app)
expires </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self.get_expiration_time(app, session) val </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> json.dumps(dict(session)) </span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> session保存在redis中</span>
<span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime)</span>
<span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);">#</span><span style="color: rgb(0, 128, 0); background-color: rgb(246, 248, 250);"> session保存在内存中</span>
self.container.setdefault(session.sid, val)
session_id </span>=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);"> self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id,
expires</span>=expires, httponly=<span style="color: rgb(0, 0, 0); background-color: rgb(246, 248, 250);">httponly,
domain</span>=domain, path=path, secure=secure)</div></div><div id="mCSB_5_scrollbar_vertical" class="mCSB_scrollTools mCSB_5_scrollbar mCS-minimal-dark mCSB_scrollTools_vertical" style="display: none;"><div class="mCSB_draggerContainer"><div id="mCSB_5_dragger_vertical" class="mCSB_dragger" style="position: absolute; min-height: 50px; top: 0px;"><div class="mCSB_dragger_bar" style="line-height: 50px;"></div></div><div class="mCSB_draggerRail"></div></div></div><div id="mCSB_5_scrollbar_horizontal" class="mCSB_scrollTools mCSB_5_scrollbar mCS-minimal-dark mCSB_scrollTools_horizontal" style="display: block;"><div class="mCSB_draggerContainer"><div id="mCSB_5_dragger_horizontal" class="mCSB_dragger" style="position: absolute; min-width: 50px; display: block; width: 0px; left: 0px;"><div class="mCSB_dragger_bar"></div></div><div class="mCSB_draggerRail"></div></div></div></pre>
自定义session
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
pip3 install redis
pip3 install flask-session """ from flask import Flask, session, redirect
from flask.ext.session import Session app = Flask(name)
app.debug = True
app.secret_key = 'asdfasdfasd' app.config['SESSION_TYPE'] = 'redis'
from redis import Redis
app.config['SESSION_REDIS'] = Redis(host='192.168.0.94',port='6379')
Session(app) @app.route('/login')
def login():
session['username'] = 'alex'
return redirect('/index') @app.route('/index')
def index():
name = session['username']
return name if name == 'main':
app.run()第三方session
总结
以加密的形式放到浏览器的cookie里面。
用户浏览器可以禁用cookie,禁用掉之后就不能用。用户登录就不能成功。
请求进来去cookie中把数据拿到,拿到之后将数据解密并反序列化成字典放到内存,让视图函数使用,视图函数使用完交给其他人,再进行序列化加密放到session中去,
本质:放到session,再给他移除掉。
当请求刚到来:flask读取cookie中session对应的值:eyJrMiI6NDU2LCJ1c2VyIjoib2xkYm95,将该值解密并反序列化成字典,放入内存以便视图函数使用。
视图函数:
1234567@app
.route(
'/ses'
)
def
ses():
session[
'k1'
]
=
123
session[
'k2'
]
=
456
del
session[
'k1'
]
return
"Session"
session是以字典的形式保存在cookie中,字典有啥操作,它就有啥操作。
当请求结束时,flask会读取内存中字典的值,进行序列化+加密,写入到用户cookie中。
可以在配置文件中对相应的配置进行修改。
生命周期默认是31天,可以修改。Django中cookie生命周期默认是2周。
1|8闪现
是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除。
在session中存储一个数据,读取时通过pop将数据移除。
1234567891011121314from
flask
import
Flask,flash,get_flashed_messages
@app
.route(
'/page1'
)
def
page1():
flash(
'临时数据存储'
,
'error'
)
flash(
'sdfsdf234234'
,
'error'
)
flash(
'adasdfasdf'
,
'info'
)
return
"Session"
@app
.route(
'/page2'
)
def
page2():
(get_flashed_messages(category_filter
=
[
'error'
]))
return
"Session"
1|9中间件
请求执行wsgi.app之前和之后定制一些操作,用的是call方法。
Django和Falsk请求源码的入口就是call方法。
call方法什么时候触发?
用户发起请求时,才执行。
任务
在执行call方法之前,做一个操作,call方法执行之后做一个操作。
方式一:改源码
方式二:
123456789101112class
Middleware(
object
):
def
__init__(
self
,old):
self
.old
=
old
def
__call__(
self
,
*
args,
*
*
kwargs):
#4、浏览器发送请求,触发__call__方法
ret
=
self
.old(
*
args,
*
*
kwargs)
#5、赋值
return
ret
if
__name__
=
=
'__main__'
:
#1
app.wsgi_app
=
Middleware(app.wsgi_app)
#2、先会给app.wsgi_app赋值
app.run()
#3、启动werkzeug服务器,等待请求
Django中的中间件是请求和响应时做一些操作,而Flask中间件是自定义一些操作。在请求执行之前和执行之后定制一些操作。
Flask源码入口:
![]()
1|10蓝图(blueprint)
目标
给开发者提供目录结构
简单蓝图步骤:
- 创建一个跟项目名同名的目录。
- 在跟项目名同名的目录下新建__init__.py
- 新建函数下实例化app
- 在项目下新建manage.py
- 导入app
- 在目录下创建views文件夹,放所有的视图,根据不同的业务建相应的py文件
- 在视图py文件中新建蓝图,并实例化蓝图对象
- 在__init__.py文件中导入蓝图并注册
- 在目录下新建templates文件夹,放所有的模板
- 在目录下新建static文件夹,放所有的静态文件
总结:
- 目录结构的划分;
- 前缀;
- 特殊装饰器;
其他
1、如果某一个蓝图想在别的地方找模板,怎么办?
如上所示,在实例化蓝图中可以自定义模板位置。那蓝图如果想用模板怎么找?
先找目录下的template下的,没有才去蓝图中找。跟Django一样。(先在项目中找,没找到再去app中去找。)
2、还可以给某一类加前缀。
在每次执行前都要加上前缀,否则报错。
3、可以给某一类添加before_request
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
from flask import Blueprint,render_template ac = Blueprint( 'ac' ,__name__,template_folder = "xxxxx" ) @ac .before_request def x1(): print ( 'app.before_request' ) @ac .route( '/login' ) def login(): return render_template( 'login.html' ) @ac .route( '/logout' ) def logout(): return 'Logout' |
这个什么时候用到呢?
登录认证。
只要登录成功才能访问的蓝图中就加before_request.
1|11特殊装饰器
before_request
- 不需要加参数
- 没有返回值
- 谁先定义谁先执行(Django框架中间件的process_request)
after_request
- 需要至少加一个参数
- 要有返回值
- 谁后定义谁先执行(Django框架中间件的process_response)(内部反转了一下)
flask与django1.9版本之前,不管请求函数有没有return,中间件响应函数都执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
from flask import Flask app = Flask(__name__) @app .before_request def x1(): print ( 'before:x1' ) return '滚' @app .before_request def xx1(): print ( 'before:xx1' ) @app .after_request def x2(response): print ( 'after:x2' ) return response @app .after_request def xx2(response): print ( 'after:xx2' ) return response @app .route( '/index' ) def index(): print ( 'index' ) return "Index" @app .route( '/order' ) def order(): print ( 'order' ) return "order" if __name__ = = '__main__' : app.run() |
before_first_request
项目启动起来,第一次请求才执行。
是一个标识,最开始是True,第一次请求之后改为False,就不再执行。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from flask import Flask app = Flask(__name__) @app .before_first_request def x1(): print ( '123123' ) @app .route( '/index' ) def index(): print ( 'index' ) return "Index" @app .route( '/order' ) def order(): print ( 'order' ) return "order" if __name__ = = '__main__' : app.run() |
template_global
给模板用
1
2
3
4
|
@app .template_global() def sb(a1, a2): # {{sb(1,9)}} return a1 + a2 |
template_filter
给模板用
1
2
3
4
|
@app .template_filter() def db(a1, a2, a3): # {{ 1|db(2,3) }} return a1 + a2 + a3 |
errorhandler
定制错误页面
1
2
3
4
|
@app .errorhandler( 404 ) def not_found(arg): print (arg) return "没找到" |
__EOF__
作 者:高雅
出 处:https://www.cnblogs.com/gaoya666/p/9174665.html
关于博主:编程路上的小学生,热爱技术,喜欢专研。评论和私信会在第一时间回复。或者直接私信我。
版权声明:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本。
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角【推荐】一下。您的鼓励是博主的最大动力!
Flask框架之功能详解的更多相关文章
- Flask框架 之 功能详解
浏览目录 配置文件 路由系统 视图 请求相关 响应 模板渲染 session 闪现 中间件 蓝图(blueprint) 特殊装饰器 配置文件 知识点 给你一个路径 “settings.Foo”,可以找 ...
- iOS-----AVFoundation框架的功能详解
使用AVFoundation拍照和录制视频 需要开发自定义的拍照和录制视频功能,可借助于AVFoundation框架来实现,该框架提供了大量的类来完成拍照和录制视频.主要使用如下类: AVCaptur ...
- VideoPipe可视化视频结构化框架新增功能详解(2022-11-4)
VideoPipe从国庆节上线源代码到现在经历过了一个月时间,期间吸引了若干小伙伴的参与,现将本阶段新增内容总结如下,有兴趣的朋友可以加微信拉群交流. 项目地址:https://github.com/ ...
- .NET ORM框架 SqlSuagr4.0 功能详解与实践【开源】
SqlSugar 4.0 ORM框架的优势 为了未来能够更好的支持多库分布式的存储,并行计算等功能,将SqlSugar3.x全部重写,现有的架构可以轻松扩展多库. 源码下载: https://gith ...
- java的集合框架最全详解
java的集合框架最全详解(图) 前言:数据结构对程序设计有着深远的影响,在面向过程的C语言中,数据库结构用struct来描述,而在面向对象的编程中,数据结构是用类来描述的,并且包含有对该数据结构操作 ...
- iOS之UI--使用SWRevealViewController实现侧边菜单功能详解实例
使用SWRevealViewController实现侧边菜单功能详解 下面通过两种方法详解SWRevealViewController实现侧边菜单功能: 1.使用StoryBoard实现 2.纯代 ...
- 转载]IOS LBS功能详解[0](获取经纬度)[1](获取当前地理位置文本 )
原文地址:IOS LBS功能详解[0](获取经纬度)[1](获取当前地理位置文本作者:佐佐木小次郎 因为最近项目上要用有关LBS的功能.于是我便做一下预研. 一般说来LBS功能一般分为两块:一块是地理 ...
- SNS社交系统“ThinkSNS V4.6”活动应用功能详解及应用场景举例
sns社交系统ThinkSNS目前拥有功能:朋友圈(微博).微吧(论坛).频道.积分商城.IM即时聊天.直播.问答.活动.资讯(CMS).商城.广场.找人.搜索.评论.点赞.转发.分享.话题.积分.充 ...
- Struts功能详解——ActionMapping对象
Struts功能详解——ActionMapping对象 ActionMapping描述了struts中用户请求路径和Action的映射关系,在struts中每个ActionMapping都是通过pat ...
随机推荐
- Pwn-pwn-100
题目地址http://www.whalectf.xin/files/2779dd8a2562a1d5653c5c6af9791711/binary_100 32位 ,没有防护 上IDA 很简单的栈溢出 ...
- ESP8266 LUA脚本语言开发: 外设篇-GPIO中断检测
https://nodemcu.readthedocs.io/en/master/modules/gpio/#gpiomode 测试引脚 GPIO0 gpio.mode(,gpio.INT) func ...
- CF1041C Coffee Break
CF1041C Coffee Break 题目大意: 给定nn个数和一个kk,这nn个数都不超过mm 每次从没被去掉的数里面选一个数aa,去掉aa,然后可以任意一个b(b>a+k)b(b> ...
- 教你用好 Javascript 数组
原文链接:https://juejin.im/post/5d9769b26fb9a04df26c1b89 作为 Javascript 的标准对象之一,数组是非常底层而且实用的数据结构.虽然结构很简单, ...
- 洛谷P2508 [HAOI2008]圆上的整点
题目描述 求一个给定的圆$ (x^2+y^2=r^2) $,在圆周上有多少个点的坐标是整数. 输入格式 \(r\) 输出格式 整点个数 输入输出样例 输入 4 输出 4 说明/提示 \(n\le 20 ...
- 数据仓库009 - SQL命令实战 - where GROUP BY join 部门综合案例
一.where条件 WHERE 子句中主要的运算符,可以在 WHERE 子句中使用,如下表: 运算符 描述 = 等于 <> 不等于.注释:在 SQL 的一些版本中,该操作符可被写成 != ...
- Pandownload倒下了,还有它,又一款百度云下载神器,速度可达10M/s
最近很多小伙伴反馈 Pandownload 不好使了 对此我表示 脑壳疼 不过经过一番折腾 还是找到了一个不错的替代品 它就是 baidupcs-web 下载解压后就这么一个可执行文件 干净的不可思议 ...
- Python连载34-信息队列
一.生产者消费者模型 1.一个模型.可以用来搭建消息队列:queue是一个用来存放变量的数据结构,特点是:先进先出 import threading import time import queue ...
- torch_13_自定义数据集实战
1.将图片的路径和标签写入csv文件并实现读取 # 创建一个文件,包含image,存放方式:label pokemeon\\mew\\0001.jpg,0 def load_csv(self,file ...
- cmake打印shell
cmake链接库失败时,可通过打印路径下对应的lib来定位问题 execute_process(COMMAND ls -lt ${CMAKE_CURRENT_SOURCE_DIR}/lib #执行sh ...