flask原理分析

主程序運行後:
1.裝飾函數app.route()會收集到uri和路由函數的地址,route()函數調用add_url_rule()形成url_map表:
app.py:

def route(self, rule, **options):
def decorator(f):
endpoint = options.pop(“endpoint”, None)
self.add_url_rule(rule, endpoint, f, **options)
return f
return decorator

def add_url_rule:
self.url_map.add(rule)

2.app.run()運行會接收uwsgi發送的uri請求:
run()會調用serving.run_simple()函數,根據uwsgi發送的uri查找url_map,並分配現場函數運行uri對應的函數
app.py:
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
try:
run_simple(host, port, self, **options)
finally:
self._got_first_request = False

werkzeug/serving.py
def run_simple(
hostname,
port,
application,
use_reloader=False,
use_debugger=False,
use_evalex=True,
extra_files=None,
reloader_interval=1,
reloader_type=“auto”,
threaded=False,
processes=1,
request_handler=None,
static_files=None,
passthrough_errors=False,
ssl_context=None,
):


run_with_reloader(inner, extra_files, reloader_interval, reloader_type)


return

def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type=“auto”):
“”“Run the given function in an independent python interpreter.”""
import signal

reloader = reloader_loops[reloader_type](extra_files, interval)
signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
try:
    if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
        ensure_echo_on()
        t = threading.Thread(target=main_func, args=())
        t.setDaemon(True)
        t.start()
        reloader.run()
    else:
        sys.exit(reloader.restart_with_reloader())
except KeyboardInterrupt:
    pass
return
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章