Flask 入口源码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#!/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)