From: Ben Darnell Date: Mon, 4 Mar 2013 04:09:57 +0000 (-0500) Subject: Re-apply autopep8. X-Git-Tag: v3.0.0~58 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=955085492c32d57d91b5d7b3c2ec8f67b96e8819;p=thirdparty%2Ftornado.git Re-apply autopep8. --- diff --git a/tornado/auth.py b/tornado/auth.py index 7ffe8e8f6..b2b7e1653 100644 --- a/tornado/auth.py +++ b/tornado/auth.py @@ -72,9 +72,11 @@ try: except ImportError: import urllib as urllib_parse # py2 + class AuthError(Exception): pass + def _auth_future_to_callback(callback, future): try: result = future.result() @@ -83,6 +85,7 @@ def _auth_future_to_callback(callback, future): result = None callback(result) + def _auth_return_future(f): """Similar to tornado.concurrent.return_future, but uses the auth module's legacy callback interface. @@ -91,6 +94,7 @@ def _auth_return_future(f): inside the function will actually be a future. """ replacer = ArgReplacer(f, 'callback') + @functools.wraps(f) def wrapper(*args, **kwargs): future = Future() @@ -102,6 +106,7 @@ def _auth_return_future(f): return future return wrapper + class OpenIdMixin(object): """Abstract implementation of OpenID and Attribute Exchange. @@ -192,8 +197,8 @@ class OpenIdMixin(object): def _on_authentication_verified(self, future, response): if response.error or b"is_valid:true" not in response.body: future.set_exception(AuthError( - "Invalid OpenID response: %s" % (response.error or - response.body))) + "Invalid OpenID response: %s" % (response.error or + response.body))) return # Make sure we got back at least an email from attribute exchange @@ -315,13 +320,13 @@ class OAuthMixin(object): request_cookie = self.get_cookie("_oauth_request_token") if not request_cookie: future.set_exception(AuthError( - "Missing OAuth request token cookie")) + "Missing OAuth request token cookie")) return self.clear_cookie("_oauth_request_token") cookie_key, cookie_secret = [base64.b64decode(escape.utf8(i)) for i in request_cookie.split("|")] if cookie_key != request_key: future.set_exception(AuthError( - "Request token does not match cookie")) + "Request token does not match cookie")) return token = dict(key=cookie_key, secret=cookie_secret) if oauth_verifier: @@ -617,8 +622,8 @@ class TwitterMixin(OAuthMixin): def _on_twitter_request(self, future, response): if response.error: future.set_exception(AuthError( - "Error response %s fetching %s" % (response.error, - response.request.url))) + "Error response %s fetching %s" % (response.error, + response.request.url))) return future.set_result(escape.json_decode(response.body)) @@ -738,8 +743,8 @@ class FriendFeedMixin(OAuthMixin): def _on_friendfeed_request(self, future, response): if response.error: future.set_exception(AuthError( - "Error response %s fetching %s" % (response.error, - response.request.url))) + "Error response %s fetching %s" % (response.error, + response.request.url))) return future.set_result(escape.json_decode(response.body)) diff --git a/tornado/concurrent.py b/tornado/concurrent.py index 1779fed39..6b0121d7d 100644 --- a/tornado/concurrent.py +++ b/tornado/concurrent.py @@ -26,9 +26,11 @@ try: except ImportError: futures = None + class ReturnValueIgnoredError(Exception): pass + class _DummyFuture(object): def __init__(self): self._done = False @@ -143,6 +145,7 @@ def run_on_executor(fn): _NO_RESULT = object() + def return_future(f): """Decorator to make a function that returns via callback return a `Future`. @@ -177,6 +180,7 @@ def return_future(f): consider using ``@gen.coroutine`` instead of this combination. """ replacer = ArgReplacer(f, 'callback') + @functools.wraps(f) def wrapper(*args, **kwargs): future = TracebackFuture() @@ -221,6 +225,7 @@ def return_future(f): return future return wrapper + def chain_future(a, b): """Chain two futures together so that when one completes, so does the other. @@ -229,7 +234,7 @@ def chain_future(a, b): def copy(future): assert future is a if (isinstance(a, TracebackFuture) and isinstance(b, TracebackFuture) - and a.exc_info() is not None): + and a.exc_info() is not None): b.set_exc_info(a.exc_info()) elif a.exception() is not None: b.set_exception(a.exception()) diff --git a/tornado/gen.py b/tornado/gen.py index bd58de197..ec5648ae1 100644 --- a/tornado/gen.py +++ b/tornado/gen.py @@ -373,7 +373,7 @@ class Multi(YieldPoint): def is_ready(self): finished = list(itertools.takewhile( - lambda i: i.is_ready(), self.unfinished_children)) + lambda i: i.is_ready(), self.unfinished_children)) self.unfinished_children.difference_update(finished) return not self.unfinished_children diff --git a/tornado/httpclient.py b/tornado/httpclient.py index a9ac0e70a..b5a4debc9 100644 --- a/tornado/httpclient.py +++ b/tornado/httpclient.py @@ -83,7 +83,7 @@ class HTTPClient(object): If an error occurs during the fetch, we raise an `HTTPError`. """ response = self._io_loop.run_sync(functools.partial( - self._async_client.fetch, request, **kwargs)) + self._async_client.fetch, request, **kwargs)) response.rethrow() return response @@ -177,6 +177,7 @@ class AsyncHTTPClient(Configurable): future = Future() if callback is not None: callback = stack_context.wrap(callback) + def handle_future(future): exc = future.exception() if isinstance(exc, HTTPError) and exc.response is not None: @@ -189,6 +190,7 @@ class AsyncHTTPClient(Configurable): response = future.result() self.io_loop.add_callback(callback, response) future.add_done_callback(handle_future) + def handle_response(response): if response.error: future.set_exception(response.error) diff --git a/tornado/httputil.py b/tornado/httputil.py index 85a86a6cd..b9cd10658 100644 --- a/tornado/httputil.py +++ b/tornado/httputil.py @@ -318,6 +318,8 @@ def format_timestamp(ts): # _parseparam and _parse_header are copied and modified from python2.7's cgi.py # The original 2.7 version of this code did not correctly support some # combinations of semicolons and double quotes. + + def _parseparam(s): while s[:1] == ';': s = s[1:] diff --git a/tornado/ioloop.py b/tornado/ioloop.py index 09e2c955b..2c5152215 100644 --- a/tornado/ioloop.py +++ b/tornado/ioloop.py @@ -308,6 +308,7 @@ class IOLoop(Configurable): IOLoop.instance().run_sync(main) """ future_cell = [None] + def run(): try: result = func() @@ -331,7 +332,6 @@ class IOLoop(Configurable): raise TimeoutError('Operation timed out after %s seconds' % timeout) return future_cell[0].result() - def time(self): """Returns the current time according to the IOLoop's clock. diff --git a/tornado/netutil.py b/tornado/netutil.py index e60bfedf1..86a3fa437 100644 --- a/tornado/netutil.py +++ b/tornado/netutil.py @@ -197,16 +197,19 @@ class ExecutorResolver(Resolver): results.append((family, address)) return results + class BlockingResolver(ExecutorResolver): def initialize(self, io_loop=None): super(BlockingResolver, self).initialize(io_loop=io_loop) + class ThreadedResolver(ExecutorResolver): def initialize(self, io_loop=None, num_threads=10): from concurrent.futures import ThreadPoolExecutor super(ThreadedResolver, self).initialize( io_loop=io_loop, executor=ThreadPoolExecutor(num_threads)) + class OverrideResolver(Resolver): """Wraps a resolver with a mapping of overrides. @@ -227,13 +230,13 @@ class OverrideResolver(Resolver): return self.resolver.resolve(host, port, *args, **kwargs) - # These are the keyword arguments to ssl.wrap_socket that must be translated # to their SSLContext equivalents (the other arguments are still passed # to SSLContext.wrap_socket). _SSL_CONTEXT_KEYWORDS = frozenset(['ssl_version', 'certfile', 'keyfile', 'cert_reqs', 'ca_certs', 'ciphers']) + def ssl_options_to_context(ssl_options): """Try to Convert an ssl_options dictionary to an SSLContext object. @@ -247,7 +250,7 @@ def ssl_options_to_context(ssl_options): if isinstance(ssl_options, dict): assert all(k in _SSL_CONTEXT_KEYWORDS for k in ssl_options), ssl_options if (not hasattr(ssl, 'SSLContext') or - isinstance(ssl_options, ssl.SSLContext)): + isinstance(ssl_options, ssl.SSLContext)): return ssl_options context = ssl.SSLContext( ssl_options.get('ssl_version', ssl.PROTOCOL_SSLv23)) @@ -294,7 +297,6 @@ else: class SSLCertificateError(ValueError): pass - def _dnsname_to_pat(dn): pats = [] for frag in dn.split(r'.'): @@ -308,7 +310,6 @@ else: pats.append(frag.replace(r'\*', '[^.]*')) return re.compile(r'\A' + r'\.'.join(pats) + r'\Z', re.IGNORECASE) - def ssl_match_hostname(cert, hostname): """Verify that *cert* (in decoded format as returned by SSLSocket.getpeercert()) matches the *hostname*. RFC 2818 rules diff --git a/tornado/platform/caresresolver.py b/tornado/platform/caresresolver.py index b2b43b443..f0052f159 100644 --- a/tornado/platform/caresresolver.py +++ b/tornado/platform/caresresolver.py @@ -5,6 +5,7 @@ from tornado import gen from tornado.ioloop import IOLoop from tornado.netutil import Resolver, is_valid_ip + class CaresResolver(Resolver): """Name resolver based on the c-ares library. diff --git a/tornado/platform/twisted.py b/tornado/platform/twisted.py index a95b009fd..240997f0c 100644 --- a/tornado/platform/twisted.py +++ b/tornado/platform/twisted.py @@ -540,5 +540,5 @@ class TwistedResolver(Resolver): (family, resolved_family)) result = [ (resolved_family, (resolved, port)), - ] + ] raise gen.Return(result) diff --git a/tornado/tcpserver.py b/tornado/tcpserver.py index 41a5eceab..e0c5f3b64 100644 --- a/tornado/tcpserver.py +++ b/tornado/tcpserver.py @@ -28,6 +28,7 @@ from tornado.iostream import IOStream, SSLIOStream from tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket from tornado import process + class TCPServer(object): r"""A non-blocking, single-threaded TCP server. diff --git a/tornado/test/auth_test.py b/tornado/test/auth_test.py index 9808a0c28..f26e03673 100644 --- a/tornado/test/auth_test.py +++ b/tornado/test/auth_test.py @@ -108,7 +108,6 @@ class TwitterClientHandler(RequestHandler, TwitterMixin): self._OAUTH_AUTHORIZE_URL = test.get_url('/oauth1/server/authorize') self._TWITTER_BASE_URL = test.get_url('/twitter/api') - def get_auth_http_client(self): return self.settings['http_client'] diff --git a/tornado/test/concurrent_test.py b/tornado/test/concurrent_test.py index 3eca29632..854f1160e 100644 --- a/tornado/test/concurrent_test.py +++ b/tornado/test/concurrent_test.py @@ -166,6 +166,8 @@ class ReturnFutureTest(AsyncTestCase): # The following series of classes demonstrate and test various styles # of use, with and without generators and futures. + + class CapServer(TCPServer): def handle_stream(self, stream, address): logging.info("handle_stream") diff --git a/tornado/test/curl_httpclient_test.py b/tornado/test/curl_httpclient_test.py index bc0c2daab..10e3e83fb 100644 --- a/tornado/test/curl_httpclient_test.py +++ b/tornado/test/curl_httpclient_test.py @@ -14,6 +14,7 @@ except ImportError: if pycurl is not None: from tornado.curl_httpclient import CurlAsyncHTTPClient + @unittest.skipIf(pycurl is None, "pycurl module not present") class CurlHTTPClientCommonTestCase(httpclient_test.HTTPClientCommonTestCase): def get_http_client(self): diff --git a/tornado/test/gen_test.py b/tornado/test/gen_test.py index f76f9324e..bfe92d739 100644 --- a/tornado/test/gen_test.py +++ b/tornado/test/gen_test.py @@ -561,7 +561,7 @@ class GenCoroutineTest(AsyncTestCase): # can be caught and replaced. @gen.coroutine def f2(): - self.io_loop.add_callback(lambda: 1/ 0) + self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) @@ -579,7 +579,7 @@ class GenCoroutineTest(AsyncTestCase): # can be caught and ignored. @gen.coroutine def f2(): - self.io_loop.add_callback(lambda: 1/ 0) + self.io_loop.add_callback(lambda: 1 / 0) try: yield gen.Task(self.io_loop.add_timeout, self.io_loop.time() + 10) @@ -591,7 +591,6 @@ class GenCoroutineTest(AsyncTestCase): self.finished = True - class GenSequenceHandler(RequestHandler): @asynchronous @gen.engine diff --git a/tornado/test/httpclient_test.py b/tornado/test/httpclient_test.py index 02fb4f18d..36f312d72 100644 --- a/tornado/test/httpclient_test.py +++ b/tornado/test/httpclient_test.py @@ -26,6 +26,7 @@ try: except ImportError: from cStringIO import StringIO as BytesIO + class HelloWorldHandler(RequestHandler): def get(self): name = self.get_argument("name", "world") diff --git a/tornado/test/iostream_test.py b/tornado/test/iostream_test.py index 1aa85a6fa..138282dc7 100644 --- a/tornado/test/iostream_test.py +++ b/tornado/test/iostream_test.py @@ -151,6 +151,7 @@ class TestIOStreamMixin(object): server.read_until(b"\r\n", self.stop) data = self.wait() self.assertEqual(data, b"abcd\r\n") + def closed_callback(chunk): self.fail() server.read_until_close(callback=closed_callback, diff --git a/tornado/test/netutil_test.py b/tornado/test/netutil_test.py index e83189fc0..245ef096f 100644 --- a/tornado/test/netutil_test.py +++ b/tornado/test/netutil_test.py @@ -25,6 +25,7 @@ except ImportError: else: from tornado.platform.twisted import TwistedResolver + class _ResolverTestMixin(object): def test_localhost(self): self.resolver.resolve('localhost', 80, callback=self.stop) diff --git a/tornado/test/simple_httpclient_test.py b/tornado/test/simple_httpclient_test.py index 0c243e94c..1c24dc570 100644 --- a/tornado/test/simple_httpclient_test.py +++ b/tornado/test/simple_httpclient_test.py @@ -367,10 +367,10 @@ class HostnameMappingTestCase(AsyncHTTPTestCase): hostname_mapping={ 'www.example.com': '127.0.0.1', ('foo.example.com', 8000): ('127.0.0.1', self.get_http_port()), - }) + }) def get_app(self): - return Application([url("/hello", HelloWorldHandler),]) + return Application([url("/hello", HelloWorldHandler), ]) def test_hostname_mapping(self): self.http_client.fetch( diff --git a/tornado/test/util_test.py b/tornado/test/util_test.py index 038602a8e..5df54f5e5 100644 --- a/tornado/test/util_test.py +++ b/tornado/test/util_test.py @@ -11,6 +11,7 @@ try: except ImportError: from io import StringIO # py3 + class RaiseExcInfoTest(unittest.TestCase): def test_two_arg_exception(self): # This test would fail on python 3 if raise_exc_info were simply diff --git a/tornado/test/web_test.py b/tornado/test/web_test.py index 0f9364433..17a6c67c8 100644 --- a/tornado/test/web_test.py +++ b/tornado/test/web_test.py @@ -20,10 +20,12 @@ import sys wsgi_safe_tests = [] + def wsgi_safe(cls): wsgi_safe_tests.append(cls) return cls + class WebTestCase(AsyncHTTPTestCase): """Base class for web tests that also supports WSGI mode. diff --git a/tornado/test/websocket_test.py b/tornado/test/websocket_test.py index ca10b4a13..5cd7f0f97 100644 --- a/tornado/test/websocket_test.py +++ b/tornado/test/websocket_test.py @@ -2,15 +2,17 @@ from tornado.testing import AsyncHTTPTestCase, gen_test from tornado.web import Application from tornado.websocket import WebSocketHandler, WebSocketConnect + class EchoHandler(WebSocketHandler): def on_message(self, message): self.write_message(message, isinstance(message, bytes)) + class WebSocketTest(AsyncHTTPTestCase): def get_app(self): return Application([ - ('/echo', EchoHandler), - ]) + ('/echo', EchoHandler), + ]) @gen_test def test_websocket_gen(self): diff --git a/tornado/testing.py b/tornado/testing.py index 3fc38c1bb..a3b448ec2 100644 --- a/tornado/testing.py +++ b/tornado/testing.py @@ -378,6 +378,7 @@ def gen_test(f): """ f = gen.coroutine(f) + @functools.wraps(f) def wrapper(self): return self.io_loop.run_sync(functools.partial(f, self), timeout=5) @@ -406,7 +407,7 @@ class LogTrapTestCase(unittest.TestCase): logging.basicConfig() handler = logger.handlers[0] if (len(logger.handlers) > 1 or - not isinstance(handler, logging.StreamHandler)): + not isinstance(handler, logging.StreamHandler)): # Logging has been configured in a way we don't recognize, # so just leave it alone. super(LogTrapTestCase, self).run(result) diff --git a/tornado/web.py b/tornado/web.py index 3cccba564..fa3089f15 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -228,10 +228,10 @@ class RequestHandler(object): def clear(self): """Resets all headers and content for this response.""" self._headers = httputil.HTTPHeaders({ - "Server": "TornadoServer/%s" % tornado.version, - "Content-Type": "text/html; charset=UTF-8", - "Date": httputil.format_timestamp(time.gmtime()), - }) + "Server": "TornadoServer/%s" % tornado.version, + "Content-Type": "text/html; charset=UTF-8", + "Date": httputil.format_timestamp(time.gmtime()), + }) self.set_default_headers() if not self.request.supports_http_1_1(): if self.request.headers.get("Connection") == "Keep-Alive": diff --git a/tornado/websocket.py b/tornado/websocket.py index a63860183..4bff6cd03 100644 --- a/tornado/websocket.py +++ b/tornado/websocket.py @@ -45,6 +45,7 @@ try: except NameError: xrange = range # py3 + class WebSocketHandler(tornado.web.RequestHandler): """Subclass this class to create a basic WebSocket handler. @@ -511,7 +512,6 @@ class WebSocketProtocol13(WebSocketProtocol): return WebSocketProtocol13.compute_accept_value( self.request.headers.get("Sec-Websocket-Key")) - def _accept_connection(self): subprotocol_header = '' subprotocols = self.request.headers.get("Sec-WebSocket-Protocol", '') @@ -729,11 +729,11 @@ class _WebSocketClientConnection(simple_httpclient._HTTPConnection): scheme = {'ws': 'http', 'wss': 'https'}[scheme] request.url = scheme + sep + rest request.headers.update({ - 'Upgrade': 'websocket', - 'Connection': 'Upgrade', - 'Sec-WebSocket-Key': self.key, - 'Sec-WebSocket-Version': '13', - }) + 'Upgrade': 'websocket', + 'Connection': 'Upgrade', + 'Sec-WebSocket-Key': self.key, + 'Sec-WebSocket-Version': '13', + }) super(_WebSocketClientConnection, self).__init__( io_loop, None, request, lambda: None, lambda response: None, @@ -742,7 +742,6 @@ class _WebSocketClientConnection(simple_httpclient._HTTPConnection): def _on_close(self): self.on_message(None) - def _handle_1xx(self, code): assert code == 101 assert self.headers['Upgrade'].lower() == 'websocket'