短小精悍 Falcon

之前一直是 Flask 的忠实粉丝,然后嘲讽下 Django 党;结果被 falcon 打脸,恩,下面是我的真机实际测试(i5-3230M 2.6G 8G RAM, SSD。乱码的是什么呢….):

1
2
3
4
5
6
7
8
9
10
11
12
Benchmarking, Trial 1 of 3......done.
Benchmarking, Trial 2 of 3......done.
Benchmarking, Trial 3 of 3......done.

Results:

1. falcon.........34,165 req/sec or 29.27 渭 s/req (9x)
2. falcon-ext.....25,752 req/sec or 38.83 渭 s/req (7x)
3. bottle.........17,043 req/sec or 58.67 渭 s/req (5x)
4. pecan...........7,915 req/sec or 126.34 渭 s/req (2x)
5. werkzeug........6,241 req/sec or 160.24 渭 s/req (2x)
6. flask...........3,762 req/sec or 265.81 渭 s/req (1x)

这样看起来,完全可以 flask 做前台,api 使用 falcon 来实现(或者 Beego,同时还能保证开发效率)。

Falcon 实在是太小巧了,没啥好讲的,一个例子就足够了:

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
import falcon
from gevent.wsgi import WSGIServer

class URLApi(object):

def on_get(self, req, resp):
"""Handles GET requests"""
result = {"errno": 0, "details": "hello"}
resp.status = falcon.HTTP_200
resp.body = json.dumps(result)

def on_post(self, req, resp):
"""Handles POST requests"""
data = json.load(req.stream,'utf-8')
result = {"errno": 0, "details": "hello"}
resp.status = falcon.HTTP_200
resp.body = json.dumps(result)

app = falcon.API()
api = URLApi()
app.add_route('/url/', api)

if __name__ == '__main__':
server = WSGIServer(('0.0.0.0', 5000), app)
server.serve_forever()

这个框架目标是提供高效的 API 接口,非常合适大量并发的 API 接口开发,同时借助 Python 的开发效率,还是不错的选择。