Update dummyserver to work with newer Tornado
The tornado.web.asynchronous decorator was deprecated in Tornado 5, and
removed in Tornado 6. This commit rewrites the dummyserver to work on
newer Tornado.
import sys
import socket
+import tornado.gen
import tornado.httpserver
import tornado.ioloop
import tornado.iostream
@@ -40,7 +41,7 @@ __all__ = ["ProxyHandler", "run_proxy"]
class ProxyHandler(tornado.web.RequestHandler):
SUPPORTED_METHODS = ["GET", "POST", "CONNECT"]
- @tornado.web.asynchronous
+ @tornado.gen.coroutine
def get(self):
def handle_response(response):
if response.error and not isinstance(
@@ -76,52 +77,45 @@ class ProxyHandler(tornado.web.RequestHandler):
client = tornado.httpclient.AsyncHTTPClient()
try:
- client.fetch(req, handle_response)
+ response = yield client.fetch(req)
+ yield handle_response(response)
except tornado.httpclient.HTTPError as e:
if hasattr(e, "response") and e.response:
- self.handle_response(e.response)
+ yield handle_response(e.response)
else:
self.set_status(500)
self.write("Internal server error:\n" + str(e))
self.finish()
- @tornado.web.asynchronous
+ @tornado.gen.coroutine
def post(self):
- return self.get()
+ yield self.get()
- @tornado.web.asynchronous
+ @tornado.gen.coroutine
def connect(self):
host, port = self.request.uri.split(":")
client = self.request.connection.stream
- def read_from_client(data):
- upstream.write(data)
-
- def read_from_upstream(data):
- client.write(data)
-
- def client_close(data=None):
- if upstream.closed():
- return
- if data:
- upstream.write(data)
- upstream.close()
-
- def upstream_close(data=None):
- if client.closed():
- return
- if data:
- client.write(data)
- client.close()
-
- def start_tunnel():
- client.read_until_close(client_close, read_from_client)
- upstream.read_until_close(upstream_close, read_from_upstream)
- client.write(b"HTTP/1.0 200 Connection established\r\n\r\n")
+ @tornado.gen.coroutine
+ def start_forward(reader, writer):
+ while True:
+ try:
+ data = yield reader.read_bytes(4096, partial=True)
+ except tornado.iostream.StreamClosedError:
+ break
+ if not data:
+ break
+ writer.write(data)
+ writer.close()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
upstream = tornado.iostream.IOStream(s)
- upstream.connect((host, int(port)), start_tunnel)
+ yield upstream.connect((host, int(port)))
+
+ client.write(b"HTTP/1.0 200 Connection established\r\n\r\n")
+ fu1 = start_forward(client, upstream)
+ fu2 = start_forward(upstream, client)
+ yield [fu1, fu2]
def run_proxy(port, start_ioloop=True):
