Flask 入口源码

作者: ropon 分类: Flask 发布时间: 2019-07-25 11:30
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/6/28 9:37
# @Author  : Ropon
# @File    : test.py

from werkzeug.wrappers import Response
from werkzeug.serving import run_simple

class Flask(object):
    def __call__(self, environ, start_response):
        ret = Response("hello world")
        # 从原始信息获取请求方式
        print(environ.get('REQUEST_METHOD'))
        rip = environ.get('REMOTE_ADDR')
        if rip == '192.168.3.20':
            ret = Response("黑客 禁止访问")
        return ret(environ, start_response)

    def run(self):
        run_simple("192.168.3.20", 5002, self)

app = Flask()

if __name__ == '__main__':
    app.run()


# from flask import Flask
#
# app = Flask(__name__)
#
#
# @app.route("/index")
# def index():
#     print("index")
#     return "index"
#
# class MiddleWare(object):
#     def __init__(self, old_app):
#         self.old_app = old_app
#     def __call__(self, environ, start_response):
#         print("执行前")
#         ret = self.old_app(environ, start_response)
#         print("执行后")
#         return ret
#
#
# if __name__ == '__main__':
#     app.wsgi_app = MiddleWare(app.wsgi_app)
#     app.run(host="192.168.3.20")

# 类()  执行__int__方法
# 对象() 执行__call__方法

app.run() => 
    self是app
    run_simple(host, port, self, **options) =>
        对象加() 执行__call__方法 实际执行app.wsgi_app()方法 environ请求原始信息 start_response用于设置响应
        app.wsgi_app(environ, start_response) =>
            ctx = app.request_context(environ) = RequestContext(app, environ) 类实例化执行__init__方法 =>
                request_class是类Request
                request = app.request_class(environ) 类实例化执行__init__方法 将请求原始信息作为参数转入
                ctx.request = request 二次加工的请求信息
                ctx.session = None =>
                    ctx.push()
                    session_interface = ctx.app.session_interface = ctx.app.SecureCookieSessionInterface()
                        ctx.session = session_interface.open_session(ctx.app, ctx.request)
                            若cookie有session就读取 解密 反序列化
                            val = request.cookies.get(app.session_cookie_name) app.session_cookie_name="session"
                            data = s.loads(val, max_age=max_age)
                            ctx.session = session_interface.session_class(data)
                    response = app.full_dispatch_request() 执行视图函数
                        rv = self.dispatch_request() 真正调用视图函数
                            process_response(self, response)
                                将session写入cookie
                                self.session_interface.save_session(self, ctx.session, response)

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!