flask多app和栈的应用
一、简介
flask的蓝图可以实现url的分发,当有多个app时也可以利用app进行url分发,这里介绍下使用方式和内部原理以及栈的应用。
二、多app使用
使用示例
from werkzeug.wsgi import dispatchermiddleware from werkzeug.serving import run_simple from flask import flask app01 = flask('app01') app02 = flask('app02') @app01.route('/index') def index(): return "app01" @app02.route('/index') def index2(): return "app02" app = dispatchermiddleware(app01, { '/app01': app01, '/app02': app02, }) #默认使用app01的路由,也就是访问 http://127.0.0.1:5000/index 返回app01 #当以app01开头时候使用app01的路由,也就是http://127.0.0.1:5000/app01/index 返回app01 #当以app02开头时候使用app02的路由,也就是http://127.0.0.1:5000/app02/index 返回app02 if __name__ == "__main__": run_simple('127.0.0.1', 5000, app)
实现原理
多app使用借助于dispatchermiddleware,让我们看看其源码类的定义:
class dispatchermiddleware(object): """allows one to mount middlewares or applications in a wsgi application. this is useful if you want to combine multiple wsgi applications:: app = dispatchermiddleware(app, { '/app2': app2, '/app3': app3 }) """ def __init__(self, app, mounts=none): self.app = app self.mounts = mounts or {} def __call__(self, environ, start_response): script = environ.get('path_info', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('script_name', '') environ['script_name'] = original_script_name + script environ['path_info'] = path_info return app(environ, start_response)
def __call__(self, environ, start_response): script = environ.get('path_info', '') path_info = '' while '/' in script: if script in self.mounts: app = self.mounts[script] break script, last_item = script.rsplit('/', 1) path_info = '/%s%s' % (last_item, path_info) else: app = self.mounts.get(script, self.app) original_script_name = environ.get('script_name', '') environ['script_name'] = original_script_name + script environ['path_info'] = path_info return app(environ, start_response)
当script = /index是,while条件成立,同时对判断 /index是否在self.mounts,显然此时不在,分割/index,修改script为空,此时while不成立,执行app = self.mounts.get(script, self.app),返回self.app也就是app01,接着运行app01(),这也就是和在上下文中流程一样了。究其本质,就是通过url匹配出是哪个app,在运行该app的__call__方法。
三、栈是使用
flask中的请求数据存放实际利用列表构造的栈来存储的,每次pop都从最后pop出栈。当我们在进行测试或者写flask离线脚本时候可能会使用到上下文嵌套,例如:
from flask import flask, current_app, _app_ctx_stack app1 = flask('app01') app1.debug = false app2 = flask('app02') app2.debug = true with app1.app_context(): print(_app_ctx_stack._local.__storage__) #{<greenlet.greenlet object at 0x10dc79e88>: {'stack': [<flask.ctx.appcontext object at 0x10dda7b00>]}} print(current_app.config['debug']) # false with app2.app_context(): print(_app_ctx_stack._local.__storage__) #{<greenlet.greenlet object at 0x10dc79e88>: {'stack': [<flask.ctx.appcontext object at 0x10dda7b00>, <flask.ctx.appcontext object at 0x10dda7c18>]}} print(current_app.config['debug']) # true print(current_app.config['debug']) # false
在以上示例中在app01的上下文中嵌套了app02的上下文,所以在栈中会有两个app_ctx,但是在各自取上下文的时候都不会冲突,因为app02的上下文在最后,也就是第二个with中top是app02的app_ctx。
四、关于with
class foo(object): def __init__(self,name): self.name=name def __enter__(self): print('run __enter__') return self.name def __exit__(self, exc_type, exc_val, exc_tb): print('run __exit__') with foo('wd') as myname: print("vars:",myname) 结果: run __enter__ vars: wd run __exit__
可能你会注意在到,在以上的demo中__exit__方法中多了三个参数,即exc_type、exc_val、exc_tb这是对应着在with语句中代码出现异常时也会执行__exit__并接受异常,分别对应着:异常类型、异常值、以及异常的traceback。示例:
class foo(object): def __init__(self,name): self.name=name def __enter__(self): print('run __enter__') return self.name def __exit__(self, exc_type, exc_val, exc_tb): print('run __exit__') print('exc_type:',exc_type) print('exc_val:',exc_val) print('exc_tb:',exc_tb) with foo('wd') as myname: print("vars:", myname) a=[] v=a[1] print(v) 结果: run __enter__ vars: wd run __exit__ exc_type: <class 'indexerror'> exc_val: list index out of range exc_tb: <traceback object at 0x10ec98508> traceback (most recent call last): file "dbapi.py", line 21, in <module> v=a[1] indexerror: list index out of range
最后我们回过头来看看app_context()对象中的__enter__方法和__exit__方法:
def __enter__(self): self.push() return self def __exit__(self, exc_type, exc_value, tb): self.pop(exc_value) if broken_pypy_ctxmgr_exit and exc_type is not none: reraise(exc_type, exc_value, tb)
实际上非常简单,执行__enter__时候调用push压栈,执行__exit__时pop出栈,这样就使得每个with里面都是当前app的上下文,而不会冲突。