官术网_书友最值得收藏!

Twisted and Tornado

If you are building microservices where increasing the number of concurrent requests you can hold is important, it's tempting to drop the WSGI standard, and just use an asynchronous framework like Tornado (http://www.tornadoweb.org/) or Twisted (https://twistedmatrix.com/trac/).

Twisted has been around for ages. To implement the same microservices, you need to write a slightly more verbose code like this:

    import time  
import json
from twisted.web import server, resource
from twisted.internet import reactor, endpoints

class Simple(resource.Resource):
isLeaf = True
def render_GET(self, request):
request.responseHeaders.addRawHeader(b"content-type",
b"application/json")
return bytes(json.dumps({'time': time.time()}), 'utf8')

site = server.Site(Simple())
endpoint = endpoints.TCP4ServerEndpoint(reactor, 8080)
endpoint.listen(site)
reactor.run()

While Twisted is an extremely robust and efficient framework, it suffers from a few problems when building HTTP microservices, which are as follows:

  • You need to implement each endpoint in your microservice with a class derived from a Resource class, and that implements each supported method. For a few simple APIs, it adds a lot of boilerplate code.
  • Twisted code can be hard to understand and debug due to its asynchronous nature.
  • It's easy to fall into callback hell when you chain too many functions that get triggered successively one after the other--and the code can get messy.
  • Properly testing your Twisted application is hard, and you have to use a Twisted-specific unit testing model.

Tornado is based on a similar model, but does a better job in some areas. It has a lighter routing system, and does everything possible to make the code closer to plain Python. Tornado also uses a callback model, so debugging can be hard.

But both frameworks are working hard at bridging the gap to rely on the new async features introduced in Python 3.

主站蜘蛛池模板: 永福县| 吉隆县| 康乐县| 徐闻县| 二连浩特市| 神池县| 黑水县| 中卫市| 南平市| 修水县| 宁明县| 修文县| 高雄县| 丰镇市| 呼伦贝尔市| 扎鲁特旗| 金堂县| 湘乡市| 通河县| 锡林浩特市| 凉城县| 子长县| 桑植县| 克什克腾旗| 宁德市| 怀仁县| 吉木乃县| 山阳县| 雷州市| 南康市| 保亭| 尼玛县| 舞阳县| 东乌| 沂南县| 平利县| 锡林郭勒盟| 罗平县| 庄河市| 舟曲县| 玉山县|