klein is a micro-framework built out of widely used components that aims to be production ready out of the box.
from klein import run, route @route('/') def hello(request): return 'Hello, world!' run('localhost', 8080)
This is the most simple example possible. It’s actually simpler than the first bottle example. This is the example you want to use in the “how fast can I serve a hard coded static string” benchmark you post to Hacker News
This post will not contain one of those benchmarks. Lets break it down.
from klein import run, route
route are the most basic APIs and it should be pretty clear what they are for. In this example we’ve imported the top-level functions which actually operate on a global instance of a the class
This class may be used directly to facilitate a more flask-like usage. For example:
from klein import Klein app = Klein() @app.route('/') def hello(request): return 'Hello, world!' app.run('localhost', 8080)
Next we have the actual handler definition:
@route('/') def hello(request): return 'Hello, world!'
route decorator is built on top of Werkzeug and passes all unknown arguments directly to
You may have noticed that unlike both flask and bottle handler functions in klein take an explicit request argument, which is an IRequest provider. This is primarily because “Explicit is better than Implicit”, but also because anything else would greatly complicate the implementation.
At this point we have our feet firmly planted in the world of Twisted. Though our example does not do anything asynchronous, or Twisted specific the full power of Twisted is available to us. You may return a
twisted.web.resource.IResource, and klein will handle all of them for you. You may of course also return a
twisted.internet.defer.Deferred which fires with any of the above as it’s result and we will handle that as well. The README of course has examples covering the full range of return values.
Finally we are ready to run the server.
This starts up a twisted web server listening on port 8080 and only accessible to localhost. You can listen any specific IP address, or ‘0.0.0.0’ for all IP addresses. As a bonus logging to stdout is set up for you.
klein is of course not complete, as no software is ever complete. It does however have a comprehensive test suite and builds on Twisted’s own heroicly extensive tests. We have lots of ideas about how to improve it and don’t plan to stop developing it. It is not currently used in production anywhere but it’s only a matter of time.
If you try it give us feedback in #twisted.web on freenode. And of course fork it on github.