Mainly adds a bunch of blank lines.
# unwind, so just exit uncleanly.
os._exit(0)
+
_USAGE = """\
Usage:
python -m tornado.autoreload -m module.to.run [args...]
app_log.error('Future %r exception was never retrieved: %s',
self, ''.join(tb).rstrip())
+
TracebackFuture = Future
if futures is None:
def shutdown(self, wait=True):
pass
+
dummy_executor = DummyExecutor()
if curl_log.isEnabledFor(logging.DEBUG):
curl.setopt(pycurl.VERBOSE, 1)
curl.setopt(pycurl.DEBUGFUNCTION, self._curl_debug)
- if hasattr(pycurl,'PROTOCOLS'): # PROTOCOLS first appeared in pycurl 7.19.5 (2014-07-12)
- curl.setopt(pycurl.PROTOCOLS, pycurl.PROTO_HTTP|pycurl.PROTO_HTTPS)
- curl.setopt(pycurl.REDIR_PROTOCOLS, pycurl.PROTO_HTTP|pycurl.PROTO_HTTPS)
+ if hasattr(pycurl, 'PROTOCOLS'): # PROTOCOLS first appeared in pycurl 7.19.5 (2014-07-12)
+ curl.setopt(pycurl.PROTOCOLS, pycurl.PROTO_HTTP | pycurl.PROTO_HTTPS)
+ curl.setopt(pycurl.REDIR_PROTOCOLS, pycurl.PROTO_HTTP | pycurl.PROTO_HTTPS)
return curl
def _curl_setup_request(self, curl, request, buffer, headers):
)
return value.encode("utf-8")
+
_TO_UNICODE_TYPES = (unicode_type, type(None))
)
return value.decode("utf-8")
+
# to_unicode was previously named _unicode not because it was private,
# but to avoid conflicts with the built-in unicode() function/type
_unicode = to_unicode
else:
return obj
+
# I originally used the regex from
# http://daringfireball.net/2010/07/improved_regex_for_matching_urls
# but it gets all exponential on certain patterns (such as too many trailing
unicode_map[name] = unichr(value)
return unicode_map
+
_HTML_UNICODE_MAP = _build_unicode_map()
"""
return _make_coroutine_wrapper(func, replace_callback=True)
+
# Ties lifetime of runners to their result futures. Github Issue #1769
# Generators, like any object in Python, must be strong referenced
# in order to not be cleaned up by the garbage collector. When using
# Runner alive.
_futures_to_runners = weakref.WeakKeyDictionary()
+
def _make_coroutine_wrapper(func, replace_callback):
"""The inner workings of ``@gen.coroutine`` and ``@gen.engine``.
else:
return multi_future(children, quiet_exceptions=quiet_exceptions)
+
Multi = multi
self.stack_context_deactivate()
self.stack_context_deactivate = None
+
Arguments = collections.namedtuple('Arguments', ['args', 'kwargs'])
callback(None)
return wrapper
+
# Convert Awaitables into Futures. It is unfortunately possible
# to have infinite recursion here if those Awaitables assume that
# we're using a different coroutine runner and yield objects
else:
raise BadYieldError("yielded unknown object %r" % (yielded,))
+
if singledispatch is not None:
convert_yielded = singledispatch(convert_yielded)
print(native_str(response.body))
client.close()
+
if __name__ == "__main__":
main()
def _cleanup(self):
self.connection.context._unapply_xheaders()
+
HTTPRequest = httputil.HTTPServerRequest
del self[old_key]
return normalized
+
_normalized_headers = _NormalizedHeaderCache(1000)
port = None
return (host, port)
+
_OctalPatt = re.compile(r"\\[0-3][0-7][0-7]")
_QuotePatt = re.compile(r"[\\].")
_nulljoin = ''.join
+
def _unquote_cookie(str):
"""Handle double quotes and escaping in cookie values.
k = q_match.start(0)
if q_match and (not o_match or k < j): # QuotePatt matched
res.append(str[i:k])
- res.append(str[k+1])
+ res.append(str[k + 1])
i = k + 2
else: # OctalPatt matched
res.append(str[i:j])
- res.append(chr(int(str[j+1:j+4], 8)))
+ res.append(chr(int(str[j + 1:j + 4], 8)))
i = j + 4
return _nulljoin(res)
assert loc <= self._read_buffer_size
# Slice the bytearray buffer into bytes, without intermediate copying
b = (memoryview(self._read_buffer)
- [self._read_buffer_pos:self._read_buffer_pos + loc]
- ).tobytes()
+ [self._read_buffer_pos:self._read_buffer_pos + loc]
+ ).tobytes()
self._read_buffer_pos += loc
self._read_buffer_size -= loc
# Amortized O(1) shrink
sockets.append(sock)
return sockets
+
if hasattr(socket, 'AF_UNIX'):
def bind_unix_socket(file, mode=0o600, backlog=_DEFAULT_BACKLOG):
"""Creates a listening unix socket.
try:
# Import the real asyncio module for py33+ first. Older versions of the
# trollius backport also use this name.
- import asyncio # type: ignore
+ import asyncio # type: ignore
except ImportError as e:
# Asyncio itself isn't available; see if trollius is (backport to py26+).
try:
tornado.concurrent.chain_future(tornado_future, af)
return af
+
if hasattr(convert_yielded, 'register'):
convert_yielded.register(asyncio.Future, to_tornado_future) # type: ignore
from tornado.platform import interface
from tornado.util import errno_from_exception
+
def try_close(f):
# Avoid issue #875 (race condition when using the file in another
# thread).
"""Closes the waker's file descriptor(s)."""
raise NotImplementedError()
+
def monotonic_time():
raise NotImplementedError()
]
raise gen.Return(result)
+
if hasattr(gen.convert_yielded, 'register'):
@gen.convert_yielded.register(Deferred) # type: ignore
def _(d):
class _State(threading.local):
def __init__(self):
self.contexts = (tuple(), None)
+
+
_state = _State()
@gen.coroutine
def f():
yield gen.moment
- 1/0
+ 1 / 0
g = f()
except ImportError:
futures = None
+
class GenEngineTest(AsyncTestCase):
def setUp(self):
super(GenEngineTest, self).setUp()
"""Runners shouldn't GC if future is alive"""
# Create the weakref
weakref_scope = [None]
+
def callback():
gc.collect(2)
weakref_scope[0]().set_result(123)
tester()
)
+
if __name__ == '__main__':
unittest.main()
log_counter.warning_count, log_counter.error_count)
sys.exit(1)
+
if __name__ == '__main__':
main()
f1)
self.assertEqual(self.active_contexts, [])
+
if __name__ == '__main__':
unittest.main()
server.add_socket(sock)
server.stop()
server.stop()
-
response.headers.get('X-Consumed-Content-Encoding')),
'gzip')
-
def test_gzip(self):
response = self.fetch('/')
self.assert_compressed(response)
self.assertEqual([s.strip() for s in response.headers['Vary'].split(',')],
['Accept-Language', 'Cookie', 'Accept-Encoding'])
+
@wsgi_safe
class PathArgsInPrepareTest(WebTestCase):
class Handler(RequestHandler):
skipIfNonWindows = unittest.skipIf(os.name != 'nt', 'non-windows platform')
+
@skipIfNonWindows
class WindowsTest(unittest.TestCase):
def test_set_close_exec(self):
return WSGIContainer(validator(self.app))
result["WSGIApplication_" + cls.__name__] = WSGIApplicationWrappedTest
return result
+
+
globals().update(wrap_web_tests_application())
return WSGIContainer(validator(WSGIAdapter(self.app)))
result["WSGIAdapter_" + cls.__name__] = WSGIAdapterWrappedTest
return result
+
+
globals().update(wrap_web_tests_adapter())
gen_log.error('FAIL')
raise
+
if __name__ == '__main__':
main()
raise ValueError("cannot unescape '\\\\%s'" % group[0])
return group
+
_re_unescape_pattern = re.compile(r'\\(.)', re.DOTALL)
else:
return unmasked_arr.tostring()
+
if (os.environ.get('TORNADO_NO_EXTENSION') or
os.environ.get('TORNADO_EXTENSION') == '0'):
# These environment variables exist to make it easier to do performance
else:
raise ValueError("Unsupported version %d" % version)
+
# A leading version number in decimal
# with no leading zeros, followed by a pipe.
_signed_value_version_re = re.compile(br"^([1-9][0-9]*)\|(.*)$")
Added ``compression_level`` and ``mem_level``.
"""
- #TODO: Add wbits option.
+ # TODO: Add wbits option.
return None
def open(self, *args, **kwargs):
self.last_ping = 0
self.last_pong = 0
-
def accept_connection(self):
try:
self._handle_websocket_headers()
new_len = self._frame_length
if self._fragmented_message_buffer is not None:
new_len += len(self._fragmented_message_buffer)
- if new_len > (self.handler.max_message_size or 10*1024*1024):
+ if new_len > (self.handler.max_message_size or 10 * 1024 * 1024):
self.close(1009, "message too big")
return
self.stream.read_bytes(
if self.ping_interval > 0:
self.last_ping = self.last_pong = IOLoop.current().time()
self.ping_callback = PeriodicCallback(
- self.periodic_ping, self.ping_interval*1000)
+ self.periodic_ping, self.ping_interval * 1000)
self.ping_callback.start()
def periodic_ping(self):
now = IOLoop.current().time()
since_last_pong = now - self.last_pong
since_last_ping = now - self.last_ping
- if (since_last_ping < 2*self.ping_interval and
+ if (since_last_ping < 2 * self.ping_interval and
since_last_pong > self.ping_timeout):
self.close()
return