创建werkzeug服务
通过实例化flask app,调用__call__注册wsgi_app
#生成
app = Flask(__name__)
#flask app.py
def __call__(self, environ, start_response):
"""The WSGI server calls the Flask application object as the
WSGI application. This calls :meth:`wsgi_app` which can be
wrapped to applying middleware."""
return self.wsgi_app(environ, start_response)
启动werkzeug服务
启动flask app实例的run方法
app.run(host='0.0.0.0', port=settings.FLASK_SERVER_PORT, debug=settings.FLASK_DEBUG)
请求入口
flask app实例的full_dispatch_request是所有请求入口
def wsgi_app(self, environ, start_response):
ctx = self.request_context(environ)
error = None
try:
try:
ctx.push()
response = self.full_dispatch_request() #请求入口
except Exception as e:
error = e
加资源
1.声明一个API对象
api = Api(version='1.0', title=' Bladed API',
description='仿真平台 API')
- 向这个API对象增加一个namespace
ns = api.namespace('bi/time-series', description='BI 时序分析接口')
- 通过namespace的route方法向这个namespace对象增加请求资源Resource
@ns.route('/run-list')
class RunListCollection(Resource):
pass
- 向flask app注册请求资源
# api.py 向这个API对象增加一个namespace时,向flask app注册资源
def add_namespace(self, ns, path=None):
for r in ns.resources:
urls = self.ns_urls(ns, r.urls)
self.register_resource(ns, r.resource, *urls, **r.kwargs)
- 向flask app注册资源时,向flask app增加url对应的rule,全都注册到app的view_functions集合中
#api.py _register_view
app.add_url_rule(rule, view_func=resource_func, **kwargs)
#app.py add_url_rule
self.view_functions[endpoint] = view_func
请求调用资源
从统一请求入口,dispatch_request函数,通过rule的endpoint得到view_functions集合中的资源,在finalize_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) #