Created
May 16, 2013 11:37
-
-
Save nakamuray/5591129 to your computer and use it in GitHub Desktop.
twisted 上で tornado を web application framework として利用するテスト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# try to use tornado as a web application framework on twisted | |
# http://twistedmatrix.com/pipermail/twisted-python/2011-January/023296.html | |
from concurrent.futures import Future | |
from twisted.internet import defer | |
def futureFromDeferred(deferred): | |
assert isinstance(deferred, defer.Deferred) | |
f = Future() | |
f.set_running_or_notify_cancel() | |
def callback(result): | |
f.set_result(result) | |
return result | |
def errback(failure): | |
f.set_exception(failure.value) | |
return failure | |
deferred.addCallbacks(callback, errback) | |
return f | |
import functools | |
def inlineCallbacks(func): | |
@gen.coroutine | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs): | |
try: | |
g = func(*args, **kwargs) | |
r = g.next() | |
while True: | |
if isinstance(r, defer.Deferred): | |
r = futureFromDeferred(r) | |
try: | |
input = yield r | |
except Exception as e: | |
r = g.throw(e) | |
else: | |
r = g.send(input) | |
except defer._DefGen_Return as e: | |
raise gen.Return(e.value) | |
return wrapper | |
from tornado import gen, web | |
from twisted.web import client | |
class MyHandler(web.RequestHandler): | |
@web.asynchronous | |
@inlineCallbacks | |
def get(self): | |
self.write('hello world\n') | |
try: | |
html = yield client.getPage('http://localhost/') | |
except Exception as e: | |
print e | |
return | |
self.write('{0}\n'.format(len(html))) | |
application = web.Application([ | |
(r'/', MyHandler), | |
]) | |
def main(): | |
from tornado.platform.twisted import TwistedIOLoop | |
from twisted.internet import reactor | |
TwistedIOLoop().install() | |
from tornado import log | |
log.enable_pretty_logging() | |
from twisted.python import log | |
import sys | |
log.startLogging(sys.stderr) | |
application.listen(8888) | |
reactor.run() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment