Python的Web框架中Tornado以异步非阻塞而闻名。本篇将使用200行代码完成一个微型异步非阻塞Web框架:Snow。
一、源码
本文基于非阻塞的Socket以及IO多路复用从而实现异步非阻塞的Web框架,其中便是众多异步非阻塞Web框架内部原理。
snow.py
二、使用
1. 基本使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
from snow import Snow
from snow import HttpResponse
def index(request):
return HttpResponse( 'OK' )
routes = [
(r '/index/' , index),
] app = Snow(routes)
app.run(port = 8012 )
|
2.异步非阻塞:超时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
from snow import Snow
from snow import HttpResponse
from snow import TimeoutFuture
request_list = []
def async(request):
obj = TimeoutFuture( 5 )
yield obj
def home(request):
return HttpResponse( 'home' )
routes = [
(r '/home/' , home),
(r '/async/' , async),
] app = Snow(routes)
app.run(port = 8012 )
|
3.异步非阻塞:等待
基于等待模式可以完成自定制操作
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
|
from snow import Snow
from snow import HttpResponse
from snow import Future
request_list = []
def callback(request, future):
return HttpResponse(future.value)
def req(request):
obj = Future(callback = callback)
request_list.append(obj)
yield obj
def stop(request):
obj = request_list[ 0 ]
del request_list[ 0 ]
obj.set_result( 'done' )
return HttpResponse( 'stop' )
routes = [
(r '/req/' , req),
(r '/stop/' , stop),
] app = Snow(routes)
app.run(port = 8012 )
|
本文转自武沛齐博客园博客,原文链接:http://www.cnblogs.com/wupeiqi/p/6536518.html,如需转载请自行联系原作者