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 importlibpath = "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.methodrequest.argsrequest.formrequest.valuesrequest.cookiesrequest.headersrequest.pathrequest.full_pathrequest.script_rootrequest.urlrequest.base_urlrequest.url_rootrequest.host_urlrequest.hostrequest.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')defses():session['k1']=123session['k2']=456delsession['k1']return"Session"session是以字典的形式保存在cookie中,字典有啥操作,它就有啥操作。
当请求结束时,flask会读取内存中字典的值,进行序列化+加密,写入到用户cookie中。
可以在配置文件中对相应的配置进行修改。
生命周期默认是31天,可以修改。Django中cookie生命周期默认是2周。
1|8闪现
是一个基于Session实现的用于保存数据的集合,其特点是:使用一次就删除。
在session中存储一个数据,读取时通过pop将数据移除。
 1234567891011121314fromflaskimportFlask,flash,get_flashed_messages@app.route('/page1')defpage1():flash('临时数据存储','error')flash('sdfsdf234234','error')flash('adasdfasdf','info')return"Session"@app.route('/page2')defpage2():(get_flashed_messages(category_filter=['error']))return"Session"1|9中间件
请求执行wsgi.app之前和之后定制一些操作,用的是call方法。
Django和Falsk请求源码的入口就是call方法。
call方法什么时候触发?
用户发起请求时,才执行。
任务
在执行call方法之前,做一个操作,call方法执行之后做一个操作。
方式一:改源码
方式二:
 123456789101112classMiddleware(object):def__init__(self,old):self.old=olddef__call__(self,*args,**kwargs):#4、浏览器发送请求,触发__call__方法ret=self.old(*args,**kwargs)#5、赋值returnretif__name__=='__main__':#1app.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_templateac = Blueprint('ac',__name__,template_folder="xxxxx")@ac.before_requestdef 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 Flaskapp = Flask(__name__)@app.before_requestdef x1():    print('before:x1')    return '滚'@app.before_requestdef xx1():    print('before:xx1')@app.after_requestdef x2(response):    print('after:x2')    return response@app.after_requestdef 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 Flaskapp = Flask(__name__)@app.before_first_requestdef 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 ...
 
随机推荐
- python-判断文件后缀名
			
>>> str = 'jidlhdpf.jpg' >>> str.endswith('.jpg') True endswith
 - leetcode 分类
			
https://www.douban.com/note/330562764/ https://blog.csdn.net/Irving_zhang/article/details/78835035 h ...
 - LG4979 矿洞:坍塌  珂朵莉树
			
问题描述 LG4979 题解 珂朵莉树+O2简直就是绝配 对于操作 A ,直接 \(\mathrm{assign}\) 推平就完事了. 对于操作 B ,如果它左右端点有在边界上的,直接把区间 \([l ...
 - ES6 Set求两个数组的并集、交集、差集;以及对数组去重
			
并集: const arr1 = [1, 2, 3, 2, 5]; const arr2 = [1, 4, 6, 8, 3]; // 将两个数组合并 const concatArr = [...arr ...
 - Linux 下 make 的时候,老是一堆warning
			
用下面的方法只显示error : 1) export CFLAGS="-w" 2) ./configure 3) make
 - 【2019.8.12 慈溪模拟赛 T2】汪哥图(wang)(前缀和)
			
森林 考虑到题目中给出条件两点间至多只有一条路径. 就可以发现,这是一个森林. 而森林有一个很有用的性质. 考虑对于一棵树,点数-边数=\(1\). 因此对于一个森林,点数-边数=连通块个数. 所以, ...
 - 校园邮箱注册jetbrains全家桶遇到的问题
			
校园邮箱怎么注册jetbrains账号,百度就可以,发两次邮件 我遇到的问题: 1.登录时出现connection refused 因为之前都是破解使用,所以修改过hosts文件,添加了“0.0.0. ...
 - nginx nginx_upstream_check_module自动踢除后端机器
			
nginx 1.14.0 描述: nginx自带的upstream配置,如果后端挂了,接口会慢,原因不讲述,故接入第三方的自动检测与自动踢除模式 nginx_upstream_check_module ...
 - Qt 编译配置相关总结
			
MinGW 与 MSVC 编译的区别 我们可以从 Qt 下载页面看到两种版本编译器,如下图: 我们来对比一下这两个编译器的区别: MSVC 是指微软的 VC 编译器. MinGW 是 Minimali ...
 - HTTP和RPC是现代微服务架构,HTTP和RPC是现代微服务架构
			
.NET Core使用gRPC打造服务间通信基础设施 一.什么是RPC rpc(远程过程调用)是一个古老而新颖的名词,他几乎与http协议同时或更早诞生,也是互联网数据传输过程中非常重要的传输机制 ...
 
			
		
