Flask是一個基於Python開發並且依賴jinja2模板和Werkzeug WSGI服務的一個微型框架,對於Werkzeug本質是Socket服務端,其用於接收http請求並對請求進行預處理,然后觸發Flask框架,開發人員基於Flask框架提供的功能對請求進行相應的處理,並返回給用戶,如果要返回給用戶復雜的內容時,需要借助jinja2模板來實現對模板的處理,即:將模板和數據進行渲染,將渲染后的字符串返回給用戶瀏覽器。
“微”(micro) 並不表示你需要把整個 Web 應用塞進單個 Python 文件(雖然確實可以 ),也不意味着 Flask 在功能上有所欠缺。微框架中的“微”意味着 Flask 旨在保持核心簡單而易於擴展。Flask 不會替你做出太多決策——比如使用何種數據庫。而那些 Flask 所選擇的——比如使用何種模板引擎——則很容易替換。除此之外的一切都由可由你掌握。如此,Flask 可以與您珠聯璧合。
默認情況下,Flask 不包含數據庫抽象層、表單驗證,或是其它任何已有多種庫可以勝任的功能。然而,Flask 支持用擴展來給應用添加這些功能,如同是 Flask 本身實現的一樣。眾多的擴展提供了數據庫集成、表單驗證、上傳處理、各種各樣的開放認證技術等功能。Flask 也許是“微小”的,但它已准備好在需求繁雜的生產環境中投入使用。
1
|
pip3 install flask
|

from werkzeug.wrappers import Request, Response @Request.application def hello(request): return Response('Hello World!') if __name__ == '__main__': from werkzeug.serving import run_simple run_simple('localhost', 4000, hello)
一. 基本使用
1
2
3
4
5
6
7
8
9
|
from
flask
import
Flask
app
=
Flask(__name__)
@app
.route(
'/'
)
def
hello_world():
return
'Hello World!'
if
__name__
=
=
'__main__'
:
app.run()
|
二、配置文件

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, } 方式一: app.config['DEBUG'] = True PS: 由於Config對象本質上是字典,所以還可以使用app.config.update(...) 方式二: app.config.from_pyfile("python文件名稱") 如: settings.py DEBUG = True app.config.from_pyfile("settings.py") import os os.environ['FLAKS-SETTINGS'] = '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.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,
}
|

def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner @app.route('/index.html',methods=['GET','POST'],endpoint='index') @auth def index(): return 'Index' 或 def index(): return "Index" self.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) or app.add_url_rule(rule='/index.html', endpoint="index", view_func=index, methods=["GET","POST"]) app.view_functions['index'] = index 或 def auth(func): def inner(*args, **kwargs): print('before') result = func(*args, **kwargs) print('after') return result return inner class IndexView(views.View): methods = ['GET'] decorators = [auth, ] def dispatch_request(self): print('Index') return 'Index!' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint 或 class IndexView(views.MethodView): methods = ['GET'] decorators = [auth, ] def get(self): return 'Index.GET' def post(self): return 'Index.POST' app.add_url_rule('/index', view_func=IndexView.as_view(name='index')) # name=endpoint @app.route和app.add_url_rule參數: rule, URL規則 view_func, 視圖函數名稱 defaults=None, 默認值,當URL中無參數,函數需要參數時,使用defaults={'k':'v'}為函數提供參數 endpoint=None, 名稱,用於反向生成URL,即: url_for('名稱') methods=None, 允許的請求方式,如:["GET","POST"] strict_slashes=None, 對URL最后的 / 符號是否嚴格要求, 如: @app.route('/index',strict_slashes=False), 訪問 http://www.xx.com/index/ 或 http://www.xx.com/index均可 @app.route('/index',strict_slashes=True) 僅訪問 http://www.xx.com/index redirect_to=None, 重定向到指定地址 如: @app.route('/index/<int:nid>', redirect_to='/home/<nid>') 或 def func(adapter, nid): return "/home/888" @app.route('/index/<int:nid>', redirect_to=func) subdomain=None, 子域名訪問 from flask import Flask, views, url_for app = Flask(import_name=__name__) app.config['SERVER_NAME'] = 'wupeiqi.com:5000' @app.route("/", subdomain="admin") def static_index(): """Flask supports static subdomains This is available at static.your-domain.tld""" return "static.your-domain.tld" @app.route("/dynamic", subdomain="<username>") def username_index(username): """Dynamic subdomains are also supported Try going to user1.your-domain.tld/dynamic""" return username + ".your-domain.tld" if __name__ == '__main__': app.run()

from flask import Flask, views, url_for from werkzeug.routing import BaseConverter app = Flask(import_name=__name__) class RegexConverter(BaseConverter): """ 自定義URL匹配正則表達式 """ def __init__(self, map, regex): super(RegexConverter, self).__init__(map) self.regex = regex def to_python(self, value): """ 路由匹配時,匹配成功后傳遞給視圖函數中參數的值 :param value: :return: """ return int(value) def to_url(self, value): """ 使用url_for反向生成URL時,傳遞的參數經過該方法處理,返回的值用於生成URL中的參數 :param value: :return: """ val = super(RegexConverter, self).to_url(value) return val # 添加到flask中 app.url_map.converters['regex'] = RegexConverter @app.route('/index/<regex("\d+"):nid>') def index(nid): print(url_for('index', nid='888')) return 'Index' if __name__ == '__main__': app.run()
四、視圖函數
在Flask中視圖函數也分為CBV和FBV
FBV

def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner 方式一: @app.route('/index',endpoint='xx') @auth def index(nid): url_for('xx',nid=123) return "Index" 方式二: @auth def index(nid): url_for('xx',nid=123) return "Index" app.add_url_rule('/index',index)
CBV

def auth(func): def inner(*args, **kwargs): result = func(*args, **kwargs) return result return inner class IndexView(views.MethodView): # methods = ['POST'] decorators = [auth,] def get(self): v = url_for('index') print(v) return "GET" def post(self): return "GET" app.add_url_rule('/index', view_func=IndexView.as_view(name='index'))
五、模板
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>

#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask,render_template app = Flask(__name__) def wupeiqi(): return '<h1>Wupeiqi</h1>' @app.route('/login', methods=['GET', 'POST']) def login(): return render_template('login.html', ww=wupeiqi) app.run()

from flask import Flask,url_for,request,redirect,render_template,jsonify,make_response,Markup from urllib.parse import urlencode,quote,unquote app = Flask(__name__) def test(a1,a2): return a1+a2 #全局視圖函數,無需在render_template時傳入也可在前端調用 #前端使用方式{{sb(1,2)}} @app.template_global() def sb(a1, a2): return a1 + a2 + 100 #與上面的全局視圖函數相似,無需在render_template時傳入也可在前端調用 #前端使用方式{{ 1|db(2,3)}} @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3 @app.route('/index',endpoint='xx') def index(): v1 = "字符串" v2 = [11,22,33] v3 = {'k1':'v1','k2':'v2'} v4 = Markup("<input type='text' />")#若不使用Markup,前端需{{v4|safe}} return render_template('index.html',v1=v1,v2=v2,v3=v3,v4=v4,test=test) if __name__ == '__main__': # app.__call__ app.run()

{% extends 'layout.html'%} {%block body %} {{v1}} <ul> {% for item in v2 %} <li>{{item}}</li> {% endfor %} </ul> {{v2.1}} <ul> {% for k,v in v3.items() %} <li>{{k}} {{v}}</li> {% endfor %} </ul> {{v3.k1}} {{v3.get('k1')}} {{v4}} <!--{{v4|safe}}--> <h1>{{test(1,19)}}</h1> {{sb(1,2)}} {{ 1|db(2,3)}} {% macro xxxx(name, type='text', value='') %} <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> <input type="{{ type }}" name="{{ name }}" value="{{ value }}"> {% endmacro %} {{ xxxx('n1') }} {%endblock%}
注意:Markup等價django的mark_safe
六、請求和響應

from flask import Flask from flask import request from flask import render_template from flask import redirect from flask import make_response app = Flask(__name__) @app.route('/login.html', methods=['GET', "POST"]) def login(): # 請求相關信息 # 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)) # 響應相關信息 # return "字符串" # return render_template('html模板路徑',**{}) # return redirect('/index.html') # response = make_response(render_template('index.html')) # response是flask.wrappers.Response類型 # response.delete_cookie('key') # response.set_cookie('key', 'value') # response.headers['X-Something'] = 'A value' # return response return "內容" if __name__ == '__main__': app.run()
七、Session
除請求對象之外,還有一個 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'

#!/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.py中用兩個類自定義: import uuid import json from flask.sessions import SessionInterface from flask.sessions import SessionMixin from itsdangerous import Signer, BadSignature, want_bytes class MySession(dict, SessionMixin): def __init__(self, initial=None, sid=None): self.sid = sid self.initial = initial super(MySession, self).__init__(initial or ()) def __setitem__(self, key, value): super(MySession, self).__setitem__(key, value) def __getitem__(self, item): return super(MySession, self).__getitem__(item) def __delitem__(self, key): super(MySession, self).__delitem__(key) class MySessionInterface(SessionInterface): session_class = MySession container = { # 'asdfasdfasdfas':{'k1':'v1','k2':'v2'} # 'asdfasdfasdfas':"{'k1':'v1','k2':'v2'}" } def __init__(self): pass # import redis # self.redis = redis.Redis() def _generate_sid(self): return str(uuid.uuid4()) def _get_signer(self, app): if not app.secret_key: return None return Signer(app.secret_key, salt='flask-session', key_derivation='hmac') def open_session(self, app, request): """ 程序剛啟動時執行,需要返回一個session對象 """ sid = request.cookies.get(app.session_cookie_name) if not sid: # 生成隨機字符串,並將隨機字符串添加到 session對象中 sid = self._generate_sid() return self.session_class(sid=sid) signer = self._get_signer(app) try: sid_as_bytes = signer.unsign(sid) sid = sid_as_bytes.decode() except BadSignature: sid = self._generate_sid() return self.session_class(sid=sid) # session保存在redis中 # val = self.redis.get(sid) # session保存在內存中 val = self.container.get(sid) if val is not None: try: data = json.loads(val) return self.session_class(data, sid=sid) except: return self.session_class(sid=sid) return self.session_class(sid=sid) def save_session(self, app, session, response): """ 程序結束前執行,可以保存session中所有的值 如: 保存到resit 寫入到用戶cookie """ domain = self.get_cookie_domain(app) path = self.get_cookie_path(app) httponly = self.get_cookie_httponly(app) secure = self.get_cookie_secure(app) expires = self.get_expiration_time(app, session) val = json.dumps(dict(session)) # session保存在redis中 # self.redis.setex(name=session.sid, value=val, time=app.permanent_session_lifetime) # session保存在內存中 self.container.setdefault(session.sid, val) session_id = self._get_signer(app).sign(want_bytes(session.sid)) response.set_cookie(app.session_cookie_name, session_id, expires=expires, httponly=httponly, domain=domain, path=path, secure=secure) #run.py: from flask import Flask,request,session app = Flask(__name__) app.secret_key = 'sdfsdfsd' app.session_interface = MySessionInterface() # app.session_interface # app.make_null_session() @app.route('/index') def index(): print('網站的所有session',MySessionInterface.container) print(session) session['k1'] = 'v1' session['k2'] = 'v2' del session['k1'] # 在內存中操作字典.... # session['k1'] = 'v1' # session['k2'] = 'v2' # del session['k1'] return "xx" if __name__ == '__main__': app.run()
補充:
Flask的session與Django有所不同,Flask默認服務器不保存session,當用戶來訪問時若需要用到session則在內存中生成字典,字典中存放着相應的鍵值對,然后經過加鹽加密后返回給瀏覽器,瀏覽器以cookie的形式保存,訪問結束后服務器立即刪除內存中的session。下次訪問時瀏覽器攜帶cookie,其中鍵值對的值就是加密形態的session,經過服務器解密后得到session內容。
而Django的session則是寫入數據庫中的,瀏覽器的cookie只存有sessionid:隨機字符串,待下次訪問時由隨機字符串匹配數據庫中的session的鍵,得到session的值(字典)
八、跨域請求
跨域請求問題一直都是web項目的第一門檻,Flask 處理跨域請求需要導入一個模塊 flask_cors
pip install flask_cors
from flask import Flask from flask_cors import * app = Flask(__name__) CORS(app, supports_credentials=True) # 用於允許跨域請求
九、flash(閃現)
flash是session的一種特殊形式,是一個基於Session實現的用於保存數據的集合,其與普通session的不同之處:使用一次就刪除。

from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request app = Flask(__name__) app.secret_key ='sdfsdfsdf' @app.route('/users') def users(): # msg = request.args.get('msg','') # msg = session.get('msg') # if msg: # del session['msg'] v = get_flashed_messages() print(v) msg = '' return render_template('users.html',msg=msg) @app.route('/useradd') def user_add(): # 在數據庫中添加一條數據 # 假設添加成功,在跳轉到列表頁面時,顯示添加成功 # return redirect('/users?msg=添加成功') # session['msg'] = '添加成功' flash('添加成功') return redirect('/users') if __name__ == '__main__': app.run()
十、藍圖
藍圖用於為應用提供目錄划分:
小型應用程序:示例
大型應用程序:示例
其他:
- 藍圖URL前綴:xxx = Blueprint('xxx', __name__,url_prefix='/xxx')
- 藍圖子域名:xxx = Blueprint('xxx', __name__,subdomain='admin')
# 使用子域名前提需要給配置SERVER_NAME: app.config['SERVER_NAME'] = 'helloworld.com:5000'
# 訪問時:admin.helloworld.com:5000/login.html
實例說明:

import fcrm if __name__ == '__main__': fcrm.app.run(port=8001)

from flask import Flask from .views import account from .views import order app = Flask(__name__) print(app.root_path) app.register_blueprint(account.account) app.register_blueprint(order.order)

from flask import Blueprint,render_template account = Blueprint('account',__name__) @account.route('/login') def login(): # return 'Login' return render_template('login.html')

from flask import Blueprint order = Blueprint('order',__name__) @order.route('/order') def login(): return 'Order'
十一、請求擴展(Flask中的類似於Django中間件的功能)

#!/usr/bin/env python # -*- coding:utf-8 -*- from flask import Flask, Request, render_template app = Flask(__name__, template_folder='templates') app.debug = True @app.before_first_request def before_first_request1(): print('before_first_request1') @app.before_first_request def before_first_request2(): print('before_first_request2') @app.before_request def before_request1(): Request.nnn = 123 print('before_request1') @app.before_request def before_request2(): print('before_request2') @app.after_request def after_request1(response): print('before_request1', response) return response @app.after_request def after_request2(response): print('before_request2', response) return response @app.errorhandler(404) def page_not_found(error): return 'This page does not exist', 404 @app.template_global() def sb(a1, a2): return a1 + a2 @app.template_filter() def db(a1, a2, a3): return a1 + a2 + a3 @app.route('/') def hello_world(): return render_template('hello.html') if __name__ == '__main__': app.run()

from flask import Flask,session,Session,flash,get_flashed_messages,redirect,render_template,request app = Flask(__name__) app.secret_key ='sdfsdfsdf' @app.before_request def process_request1(): print('process_request1') @app.after_request def process_response1(response): print('process_response1') return response @app.before_request def process_request2(): print('process_request2') @app.after_request def process_response2(response): print('process_response2') return response @app.route('/index') def index(): print('index') return 'Index' @app.route('/order') def order(): print('order') return 'order' @app.route('/test') def test(): print('test') return 'test' if __name__ == '__main__': app.run()
十二、數據庫連接池(DButils)
在Flask中創建多線程,在程序運行時若想對數據庫進行操作需建立連接。若每次都進行連接的創建,就會使連接數太多,費時費資源;若直接加鎖則不能支持並發。所以這里我們引入數據庫連接池來解決問題。
安裝
pip3 install dbutils
使用方法:

from flask import Flask import time import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用鏈接數據庫的模塊 maxconnections=6, # 連接池允許的最大連接數,0和None表示不限制連接數 mincached=2, # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建 maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。 blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯 maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制 setsession=[], # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host='127.0.0.1', port=3306, user='root', password='123', database='pooldb', charset='utf8' ) app = Flask(__name__) app.secret_key ='sdfsdfsdf' @app.route('/index') def index(): # 第一步:缺點:每次請求反復創建數據庫連接,連接數太多 # conn = pymysql.connect() # cursor = conn.cursor() # cursor.execute('select * from tb where id > %s',[5,]) # result = cursor.fetchall() # cursor.close() # conn.close() # print(result) # 第二步:缺點,不能支持並發 # pymysql.threadsafety # with LOCK: # cursor = CONN.cursor() # cursor.execute('select * from tb where id > %s', [5, ]) # result = cursor.fetchall() # cursor.close() # # print(result) # 第三步:基於DBUtils實現數據連接池 # - 為每個線程創建一個連接,該線程關閉時,不是真正關閉;本線程再次調用時,還是使用的最開始創建的連接。直到線程終止,數據庫連接才關閉。 # - 創建一個連接池(10個連接),為所有線程提供連接,使用時來進行獲取,使用完畢后,再次放回到連接池。 # PS: #檢測當前正在運行連接數的是否小於最大鏈接數,如果不小於則:等待或報raise TooManyConnections異常 # 否則 # 則優先去初始化時創建的鏈接中獲取鏈接 SteadyDBConnection。 # 然后將SteadyDBConnection對象封裝到PooledDedicatedDBConnection中並返回。 # 如果最開始創建的鏈接沒有鏈接,則去創建一個SteadyDBConnection對象,再封裝到PooledDedicatedDBConnection中並返回。 # 一旦關閉鏈接后,連接就返回到連接池讓后續線程繼續使用。 conn = POOL.connection() cursor = conn.cursor() cursor.execute('select * from tb1') result = cursor.fetchall() conn.close() return '執行成功' if __name__ == '__main__': app.run()
擴展:用類的自定義方法解耦數據庫連接池的數據庫操作

#用類的自定義方法解耦數據庫連接池的數據庫操作 #創建數據庫連接池 import pymysql import threading from DBUtils.PooledDB import PooledDB, SharedDBConnection POOL = PooledDB( creator=pymysql, # 使用鏈接數據庫的模塊 maxconnections=6, # 連接池允許的最大連接數,0和None表示不限制連接數 mincached=2, # 初始化時,鏈接池中至少創建的空閑的鏈接,0表示不創建 maxcached=5, # 鏈接池中最多閑置的鏈接,0和None不限制 maxshared=3, # 鏈接池中最多共享的鏈接數量,0和None表示全部共享。PS: 無用,因為pymysql和MySQLdb等模塊的 threadsafety都為1,所有值無論設置為多少,_maxcached永遠為0,所以永遠是所有鏈接都共享。 blocking=True, # 連接池中如果沒有可用連接后,是否阻塞等待。True,等待;False,不等待然后報錯 maxusage=None, # 一個鏈接最多被重復使用的次數,None表示無限制 setsession=[], # 開始會話前執行的命令列表。如:["set datestyle to ...", "set time zone ..."] ping=0, # ping MySQL服務端,檢查是否服務可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always host='47.93.4.198', port=3306, user='root', password='123', database='s6', charset='utf8' ) #定義用於解耦操作的類 class SQLHelper(object): def __init__(self): self.conn = None self.cursor = None def open(self,cursor=pymysql.cursors.DictCursor): self.conn = db_pool.POOL.connection() self.cursor = self.conn.cursor(cursor=cursor) def close(self): self.cursor.close() self.conn.close() def fetchone(self,sql,params): cursor = self.cursor cursor.execute(sql,params) result = cursor.fetchone() return result def fetchall(self, sql, params): cursor = self.cursor cursor.execute(sql, params) result = cursor.fetchall() return result def __enter__(self): self.open() return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() #調用(可以是在其他文件下,只要引入上述代碼所在文件即可) with SQLHelper() as helper: result = helper.fetchone('select * from users where name=%s and pwd = %s',[request.form.get('user'),request.form.get('pwd'),]) if result: #做操作
十三、Flask的__call__源碼解析
Flask執行app.run()時即執行Flask類的__call__方法

import sys from itertools import chain from .globals import _request_ctx_stack, _app_ctx_stack #flask\app.py: class Flask(_PackageBoundObject): #1、執行__call__方法 def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) #2、執行Flask類的wsgi_app方法 def wsgi_app(self, environ, start_response): #2.1、執行Flask類的request_context(environ),最后得到封裝了request和session的對象 ctx = self.request_context(environ)#RequestContext類的對象 #3、在ctx.py中的RequestContext類中執行push堆棧操作 ctx.push() error = None try: try: #4、執行Flask類的full_dispatch_request方法 response = self.full_dispatch_request() except Exception as e: error = e response = self.handle_exception(e) except: error = sys.exc_info()[1] raise return response(environ, start_response) finally: if self.should_ignore_error(error): error = None ctx.auto_pop(error) #2.1 def request_context(self, environ): #2.2、實例化了ctx.py中的RequestContext類賦值給2中的ctx,執行其構造方法 return RequestContext(self, environ)#self=app #2.3.1、得到Werkzeug 模塊提供的Request request_class = Request #2.4、封裝request def create_url_adapter(self, request): """Creates a URL adapter for the given request. The URL adapter is created at a point where the request context is not yet set up so the request is passed explicitly. .. versionadded:: 0.6 .. versionchanged:: 0.9 This can now also be called without a request object when the URL adapter is created for the application context. """ if request is not None: return self.url_map.bind_to_environ(request.environ, server_name=self.config['SERVER_NAME']) # We need at the very least the server name to be set for this # to work. if self.config['SERVER_NAME'] is not None: return self.url_map.bind( self.config['SERVER_NAME'], script_name=self.config['APPLICATION_ROOT'] or '/', url_scheme=self.config['PREFERRED_URL_SCHEME']) #4、 def full_dispatch_request(self): #4.1、執行before_first_request方法,只執行一次 self.try_trigger_before_first_request_functions() try: #執行信號 request_started.send(self) #5、執行Flask類的preprocess_request方法,類似Django中間件的裝飾器函數 rv = self.preprocess_request()#rv是裝飾器函數的返回值 if rv is None:#裝飾器函數沒有返回值,執行視圖函數 # 6、執行Flask類的dispatch_request方法,即視圖函數 rv = self.dispatch_request() except Exception as e: rv = self.handle_user_exception(e) #7、執行Flask類的finalize_request方法,試圖函數結束后執行的裝飾器 return self.finalize_request(rv) # 5、執行Flask類的preprocess_request方法,類似Django中間件的裝飾器函數 def preprocess_request(self): #top讀棧中的request bp = _request_ctx_stack.top.request.blueprint funcs = self.url_value_preprocessors.get(None, ()) if bp is not None and bp in self.url_value_preprocessors: funcs = chain(funcs, self.url_value_preprocessors[bp]) for func in funcs: func(request.endpoint, request.view_args) funcs = self.before_request_funcs.get(None, ()) if bp is not None and bp in self.before_request_funcs: funcs = chain(funcs, self.before_request_funcs[bp]) for func in funcs: rv = func() if rv is not None: return rv #6、執行Flask類的dispatch_request方法,即視圖函數 def dispatch_request(self): req = _request_ctx_stack.top.request if req.routing_exception is not None: self.raise_routing_exception(req) rule = req.url_rule # if we provide automatic options for this URL and the # request came with the OPTIONS method, reply automatically if getattr(rule, 'provide_automatic_options', False) \ and req.method == 'OPTIONS': return self.make_default_options_response() # otherwise dispatch to the handler for that endpoint return self.view_functions[rule.endpoint](**req.view_args) # 7、執行Flask類的finalize_request方法,試圖函數結束后執行的裝飾器 def finalize_request(self, rv, from_error_handler=False): response = self.make_response(rv) try: #8、執行Flask類的process_response方法,處理session response = self.process_response(response) #信號 request_finished.send(self, response=response) except Exception: if not from_error_handler: raise self.logger.exception('Request finalizing failed with an ' 'error while handling an error') return response # 8、執行Flask類的process_response方法,處理session def process_response(self, response): ctx = _request_ctx_stack.top bp = ctx.request.blueprint funcs = ctx._after_request_functions if bp is not None and bp in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[bp])) if None in self.after_request_funcs: funcs = chain(funcs, reversed(self.after_request_funcs[None])) for handler in funcs: response = handler(response) if not self.session_interface.is_null_session(ctx.session): self.save_session(ctx.session, response) return response #ctx.py: class RequestContext(object): #2.2、 def __init__(self, app, environ, request=None): #self=ctx,app=app self.app = app # 2.3.1、如果沒有request的話,執行Flask類下的request_class靜態字段 if request is None: request = app.request_class(environ) #2.3.2、有request self.request = request #2.4、執行Flask類下的create_url_adapter方法封裝request self.url_adapter = app.create_url_adapter(self.request) #2.5、默認flashes和session為None self.flashes = None self.session = None #3、堆棧操作 def push(self): # _request_ctx_stack=LocalStack(),由文件導入過來,是一個字典 top = _request_ctx_stack.top#top是讀棧 if top is not None and top.preserved: top.pop(top._preserved_exc) #_app_ctx_stack = LocalStack() app_ctx = _app_ctx_stack.top if app_ctx is None or app_ctx.app != self.app: app_ctx = self.app.app_context() app_ctx.push() self._implicit_app_ctx_stack.append(app_ctx) else: self._implicit_app_ctx_stack.append(None) if hasattr(sys, 'exc_clear'): sys.exc_clear() #3.1 堆棧操作 _request_ctx_stack.push(self) #查看session,如果沒有的話賦予NullSession self.session = self.app.open_session(self.request) if self.session is None: self.session = self.app.make_null_session() #global.py: from functools import partial from werkzeug.local import LocalStack, LocalProxy _request_ctx_stack = LocalStack() _app_ctx_stack = LocalStack() current_app = LocalProxy(_find_app) request = LocalProxy(partial(_lookup_req_object, 'request')) session = LocalProxy(partial(_lookup_req_object, 'session')) g = LocalProxy(partial(_lookup_app_object, 'g')) #local.py: class LocalStack(object): def __init__(self): #_request_ctx_stack._local=self._local=__storage__: {線程或協程唯一標識: {"stack": [request]}, } self._local = Local()#形成牛逼的字典 def __release_local__(self): self._local.__release_local__() def _get__ident_func__(self): return self._local.__ident_func__ def _set__ident_func__(self, value): object.__setattr__(self._local, '__ident_func__', value) __ident_func__ = property(_get__ident_func__, _set__ident_func__) del _get__ident_func__, _set__ident_func__ def __call__(self): def _lookup(): rv = self.top if rv is None: raise RuntimeError('object unbound') return rv return LocalProxy(_lookup) #3.1、堆棧操作 def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, 'stack', None)#找牛逼的字典中有沒有叫stack的鍵,默認為None if rv is None:#如果是None的話,在牛逼的字典中創建"stack":[] self._local.stack = rv = [] rv.append(obj)#將obj放入[],真正的堆棧操作 return rv def pop(self): """Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty. """ stack = getattr(self._local, 'stack', None) if stack is None: return None elif len(stack) == 1: release_local(self._local) return stack[-1] else: return stack.pop() @property def top(self): """The topmost item on the stack. If the stack is empty, `None` is returned. """ try: return self._local.stack[-1] except (AttributeError, IndexError): return None class Local(object): __slots__ = ('__storage__', '__ident_func__') def __init__(self): #最后得到__storage__:{線程或協程唯一標識:{"stack":[request]},}.賦值給LocalStack()._local,即_request_ctx_stack object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) def __iter__(self): return iter(self.__storage__.items()) def __call__(self, proxy): """Create a proxy for a name.""" return LocalProxy(self, proxy) def __release_local__(self): self.__storage__.pop(self.__ident_func__(), None) def __getattr__(self, name): try: return self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name) def __setattr__(self, name, value): ident = self.__ident_func__() storage = self.__storage__ try: storage[ident][name] = value except KeyError: storage[ident] = {name: value} def __delattr__(self, name): try: del self.__storage__[self.__ident_func__()][name] except KeyError: raise AttributeError(name)
流程分析:
- 執行__call__方法時即執行Flask類的wsgi_app方法。
- 在該方法中調用request_context方法用於封裝request和session,默認flashed和session為None。
- 然后,在ctx.py中的RequestContext類中執行push堆棧操作,堆棧操作中會查看session,如果沒有的話會賦予NullSession。堆棧操作中會形成一個很大的字典,字典的形式為{線程或協程的唯一id: {"stack": [request]},...}。
- 堆棧操作完畢后執行full_dispatch_request方法,該方法主要執行裝飾器(中間件或信號)和視圖函數。首先會執行before_first_request方法,只執行一次。然后執行信號request_started.send(self)。
- 接下來執行preprocess_request(),其作用類似於Django的中間件。
- 若preprocess_request()沒有返回值即表明通過中間件,執行dispatch_request()即視圖函數。
- 視圖函數結束后執行finalize_request()方法,為自定義的裝飾器。
- 執行Flask類的process_response方法,處理session。
- 最后得到__storage__:{線程或協程唯一標識:{"stack":[request]},}.賦值給LocalStack()._local,即_request_ctx_stack
十四、信號 blinker
安裝 pip3 install blinker
Flask有10個內置信號,信號是什么呢,是請求執行時會自動執行的一些方法,沒有返回值。信號在源碼中靠send觸發。
內置信號:

2. request_started = _signals.signal('request-started') # 請求到來前執行 5. request_finished = _signals.signal('request-finished') # 請求結束后執行 3. before_render_template = _signals.signal('before-render-template') # 模板渲染前執行 4. template_rendered = _signals.signal('template-rendered') # 模板渲染后執行 2/3/4/5或不執行 got_request_exception = _signals.signal('got-request-exception') # 請求執行出現異常時執行 6. request_tearing_down = _signals.signal('request-tearing-down') # 請求執行完畢后自動執行(無論成功與否) 7. appcontext_tearing_down = _signals.signal('appcontext-tearing-down')# 請求上下文執行完畢后自動執行(無論成功與否) 1. appcontext_pushed = _signals.signal('appcontext-pushed') # 請求app上下文push時執行 8. appcontext_popped = _signals.signal('appcontext-popped') # 請求上下文pop時執行 最后.message_flashed = _signals.signal('message-flashed') # 調用flask在其中添加數據時,自動觸發
信號用於做什么?
主要是用於降低代碼之間的耦合
特殊的裝飾器和信號有什么區別?
裝飾器返回值有意義
自定義信號:
作用:發送短信,郵件,微信

from flask import Flask,flash from flask.signals import _signals app = Flask(__name__) mysignal = _signals.signal('mysignal')#實質上是一個列表 # 定義函數 def fun1(*args,**kwargs): print('函數一',args,kwargs) # 定義函數 def fun2(*args,**kwargs): print('函數二',args,kwargs) # 將函數注冊到request_started信號中: 添加到這個列表 mysignal.connect(fun1) mysignal.connect(fun2) @app.route('/index') def index(): # 觸發這個信號:執行注冊到列表中的所有函數 # 自定義信號的作用:發送短信,郵件,微信 mysignal.send(sender='xxx',a1=123,a2=456) return "xx" if __name__ == '__main__': app.__call__ app.run()
十五、Flask插件
- flask-script
- wtforms
- SQLAlchemy
- 等... http://flask.pocoo.org/extensions/
十六、項目須知