-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlask_Internal.html
More file actions
402 lines (337 loc) · 7.89 KB
/
Flask_Internal.html
File metadata and controls
402 lines (337 loc) · 7.89 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta charset="utf-8">
<style>
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
</style>
</head>
<body>
<textarea id="source">
class: center, middle
# Flask 实现原理
archer.li@shopeemobile.com
---
## 目录
* #### 历史
* #### 通用网关接口
* #### 并发机制
* #### 处理流程
* #### 会话机制
* #### 路由机制
* #### 请求上下文
* #### 模板引擎
---
## 历史
* #### Armin Ronacher [@mitsuhiko](@mitsuhiko), Pocoo
* #### Deny
```python
# a deny application
from deny import *
@route('/')
def welcome():
return "welcome to deny"
if __name__ == '__main__':
run()
```
---
* ### Flask
```Python
from flask import Flask
app = Flask(__name__)
@app.route('/')
def welcome():
return "welcome to flask"
if __name__ == '__main__':
run()
```
---
### 问题
1, 请求是如何被传递,处理并且返回?
```bash
http://localhost/
```
```Python
def welcome():
return 'welcome to Flask'
```
2, 会话机制在Flask中是如何串通的?
```Python
from flask import Flask, session
app = Flask(__name__)
app.serect = 'secret'
session[user_id] = {}
```
---
## 通用网关接口
#### 网站服务器
* Gunicorn
* wsgiref
* Nginx + mod_wsgi
* etc
#### 网站应用
* Django
* Flask
* web.py
* etc
---
#### WSGI -- PEP333
> WSGI specifies a proposed standard interface between web servers and Python web applications or frameworks, to promote web application **portability** across a variety of web servers.
<br/>
<br/>
<br/>
#### Flask 的入口函数
```Python
def wsgi_app(environ, start_response):
with RequestContext(environ):
rv = dispatch_request()
response = make_response(rv)
response = process_response(response)
return response(environ, start_response)
```
---
## Flask处理流程
<!--  -->
<img src="https://user-images.githubusercontent.com/5053620/29756205-97236942-8bd4-11e7-9531-9d55c7033981.png" alt="Drawing" style="width: 400px;"/>
---
## 并发机制
* 线程全局变量
* 线程局部变量
* ThreadLocal
* Werkzeug.Local
```Python
_request_ctx_stack = LocalStack()
request = _request_ctx_stack.top.request
```
---
## Session 机制
#### 无状态的HTTP
```bash
GET /api/v1/orders/{order_id}/
```
A的订单信息
```json
{
'orderid': 13937,
'userid': 297045,
'buyer_address': {},
'seller_address': {},
...
}
```
B的订单信息
```json
{
'orderid': 13938,
'userid': 297043,
'buyer_address': {},
'seller_address': {},
...
}
```
---
登陆成功后
* session id
* 服务端端存储
* 客户端存储
```json
{
'9PhQ4YMRDwAcYjNyuZEyTeCslww': {
'user_name': 'kenseller',
'userid': 170854,
'avatar': 'https://s.sg/th.jpg',
'email': 'kenseller@shopeemobile.com'
....
}
}
```
```bash
http --session=/tmp/flask_session.json GET http://localhost:5000/login/archer
HTTP/1.0 200 OK
Content-Length: 16
Content-Type: text/html; charset=utf-8
Date: Tue, 08 Aug 2017 04:16:12 GMT
Server: Werkzeug/0.12.2 Python/2.7.6
Set-Cookie: session='9PhQ4YMRDwAcYjNyuZEyTeCslww'
```
---
### 数据模型
Werkzeug.Local类型的全局变量
```Python
# context locals, flask line 662
_request_ctx_stack = LocalStack()
session = _request_ctx_stack.top.session
```
```Python
from flask import session
app.secret_key = 'blablabla'
# set session
session[user_id] = {}
# remove session
session.pop(user_id)
```
---
#### 载入会话信息
```Python
class RequestContext(object):
def __init__(self, app, environ):
self.session = app.open_session(self.request)
def open_session(self, request):
key = self.secret_key
if key is not None:
return SecureCookie.load_cookie(request, self.session_cookie_name, secret_key)
```
#### 设置会话信息
```Python
def process_response(self, response):
session = _request_ctx_stack.top.session
if session is not None:
self.save_session(session, response)
return response
def save_session(self, session, response):
if session is not None:
session.save_cookie(response, self.session_cookie_name)
```
---
## 路由机制
#### 数据模型
```Python
class Flask(object):
def __init__(self, package_name):
self.view_functions = {}
self.url_map = Map()
```

---
#### 构建路由表 -- 装饰器
```Python
def route(self, rule, **options):
def decorator(f):
self.add_url_rule(rule, f.__name__, **options)
self.view_functions[f.__name__] = f
return decorator
```
```Python
@app.route('/')
def welcome():
return 'welcome ya'
```
```Python
url_map('/', 'welcome', **options)
view_functions = {
'welcome': welcome
}
```
---
#### 查找路由
```Python
def dispatch_request(self):
try:
endpoint, values = self.match_request()
return self.view_functions[endpoint](**values)
```
* 根据url从url_map中找到对应的视图函数名称
* 根据名称从view_functions里面找到函数对象
---
## 请求上下文
#### 数据模型
```Python
class _RequestContext(object):
def __init__(self, app, environ):
self.app = app
self.url_adapter = app.url_map.bind_to_environ(environ)
self.request = app.request_class(environ)
self.session = app.open_session(self.request)
self.g = _RequestGlobals()
self.flashes = None
def __enter__(self):
_request_ctx_stack.push(self)
def __exit__(self, exc_type, exc_value, tb):
if tb is None or not self.app.debug:
_request_ctx_stack.pop()
request = LocalProxy(lambda: _request_ctx_stack.top.request)
```
```Python
from flask import request
request.args.get('username')
```
---
## 模板引擎
#### 为什么需要模板引擎?
* 逻辑处理较多
* 文本处理较多
#### 目标
```html
<html>
<head><title>Template</title></head>
<body>
<h3>Hello {{username}}</h3>
</body>
</html>
```
```Python
{{%if%}}
{{%for%}}
{{%endif%}}
{{%endfor%}}
```
---
### 方法
* 字符串替换
* % operator
* .format
* .replace
* 代码执行
* 模板
* 字面量
* 对象
* 带参数执行
```Python
CodeBuilder.add_line('result.apend("<html>\nHello ") ')
CodeBuilder.add_line(str(username))
```
---
```Python
#!/usr/bin/env python
# string format
func_str = """
def render_function(**kwargs):
result = []
result.append('<html>\n<head><title>Template</title></head>\n<body>\n<h3>')
result.append(str(user_name))
result.append('</h3>\n</body>\n</html>')
return ''.join(result)
"""
namespace = {}
exec(func_str, namespace) # will put render_function as a function into namespace, like JS's evil eval which will execute a string as a statements
html = namespace.get('render_function')({'username': 'code execution'})
print html
```
---
class: center, middle
# 谢谢
---
## 参考
[Flask, A simple history](https://github.com/csrgxtu/Cocoa/wiki/Flask,-a-simple-history)
[Web server and web application](https://github.com/csrgxtu/Cocoa/wiki/Web-Server-and-Web-app)
[Flask Session](https://github.com/csrgxtu/Cocoa/wiki/Flask-Session)
[Flask URL Routing](https://github.com/csrgxtu/Cocoa/wiki/Flask-URL-Routing)
[Flask Context](https://github.com/csrgxtu/Cocoa/wiki/Flask-Request-Context)
[Template Engine](https://github.com/csrgxtu/TemplateEngine/issues/1)
</textarea>
<script src="https://remarkjs.com/downloads/remark-latest.min.js">
</script>
<script>
var slideshow = remark.create();
</script>
</body>
</html>