]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
*: Remove unnecessary conditional imports
authorBen Darnell <ben@bendarnell.com>
Sat, 7 Jul 2018 23:34:55 +0000 (19:34 -0400)
committerBen Darnell <ben@bendarnell.com>
Sat, 14 Jul 2018 20:58:48 +0000 (16:58 -0400)
tornado/autoreload.py
tornado/platform/auto.py
tornado/process.py
tornado/simple_httpclient.py
tornado/tcpserver.py
tornado/template.py
tornado/test/httpserver_test.py
tornado/test/template_test.py
tornado/util.py
tornado/web.py
tornado/websocket.py

index 7d69474a390ac2164749ab81ff0775007e39a007..9c5b2326bc8e670640fb81d9e16ccca137849700 100644 (file)
@@ -33,9 +33,8 @@ This combination is encouraged as the wrapper catches syntax errors and
 other import-time failures, while debug mode catches changes once
 the server has started.
 
-This module depends on `.IOLoop`, so it will not work in WSGI applications
-and Google App Engine.  It also will not work correctly when `.HTTPServer`'s
-multi-process mode is used.
+This module will not work correctly when `.HTTPServer`'s multi-process
+mode is used.
 
 Reloading loses any Python interpreter command-line arguments (e.g. ``-u``)
 because it re-executes Python using ``sys.executable`` and ``sys.argv``.
index 553b70e3614efc6c1f88ec521c61955fa7990db7..16ee9091a5063ab09cac7dac9590bdaa475aa08f 100644 (file)
@@ -26,10 +26,7 @@ from __future__ import absolute_import, division, print_function
 
 import os
 
-if 'APPENGINE_RUNTIME' in os.environ:
-    def set_close_exec(fd):
-        pass
-elif os.name == 'nt':
+if os.name == 'nt':
     from tornado.platform.windows import set_close_exec
 else:
     from tornado.platform.posix import set_close_exec
index 96f1f4539ee3cc408b7e91b633a7e6a31320338a..7a5fbaed0b1c805b5d86bb024aa97cf587c45e49 100644 (file)
@@ -21,6 +21,7 @@ from __future__ import absolute_import, division, print_function
 
 import errno
 import os
+import multiprocessing
 import signal
 import subprocess
 import sys
@@ -35,12 +36,6 @@ from tornado.log import gen_log
 from tornado.platform.auto import set_close_exec
 from tornado.util import errno_from_exception
 
-try:
-    import multiprocessing
-except ImportError:
-    # Multiprocessing is not available on Google App Engine.
-    multiprocessing = None
-
 # Re-export this exception for convenience.
 CalledProcessError = subprocess.CalledProcessError
 
index 851ebb61f95d022d5448bcddf98c20071e8c5d74..bf41abbf1dcae3f9a9cfe9c563cb1e92faa45ac9 100644 (file)
@@ -10,7 +10,6 @@ from tornado.iostream import StreamClosedError
 from tornado.netutil import Resolver, OverrideResolver, _client_ssl_defaults
 from tornado.log import gen_log
 from tornado.tcpclient import TCPClient
-from tornado.util import PY3
 
 import base64
 import collections
@@ -18,21 +17,11 @@ import copy
 import functools
 import re
 import socket
+import ssl
 import sys
 import time
 from io import BytesIO
-
-
-if PY3:
-    import urllib.parse as urlparse
-else:
-    import urlparse
-
-try:
-    import ssl
-except ImportError:
-    # ssl is not available on Google App Engine.
-    ssl = None
+import urllib.parse
 
 
 class HTTPTimeoutError(HTTPError):
@@ -235,7 +224,7 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
     @gen.coroutine
     def run(self):
         try:
-            self.parsed = urlparse.urlsplit(_unicode(self.request.url))
+            self.parsed = urllib.parse.urlsplit(_unicode(self.request.url))
             if self.parsed.scheme not in ("http", "https"):
                 raise ValueError("Unsupported url scheme: %s" %
                                  self.request.url)
@@ -504,8 +493,8 @@ class _HTTPConnection(httputil.HTTPMessageDelegate):
         if self._should_follow_redirect():
             assert isinstance(self.request, _RequestProxy)
             new_request = copy.copy(self.request.request)
-            new_request.url = urlparse.urljoin(self.request.url,
-                                               self.headers["Location"])
+            new_request.url = urllib.parse.urljoin(self.request.url,
+                                                   self.headers["Location"])
             new_request.max_redirects = self.request.max_redirects - 1
             del new_request.headers["Host"]
             # http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.4
index 4f5d6f03300d8b691408a8e5a2cb5c2e52a8e7d7..31e16b8df37670384b6c5beda8d122d2064c43d6 100644 (file)
@@ -19,6 +19,7 @@ from __future__ import absolute_import, division, print_function
 import errno
 import os
 import socket
+import ssl
 
 from tornado import gen
 from tornado.log import app_log
@@ -28,12 +29,6 @@ from tornado.netutil import bind_sockets, add_accept_handler, ssl_wrap_socket
 from tornado import process
 from tornado.util import errno_from_exception
 
-try:
-    import ssl
-except ImportError:
-    # ssl is not available on Google App Engine.
-    ssl = None
-
 
 class TCPServer(object):
     r"""A non-blocking, single-threaded TCP server.
index 61b987462cc7c1799234671704f56abd9c52027f..382f08f4059df86c1f385f91b431347d92b96045 100644 (file)
@@ -198,6 +198,7 @@ if you need to include a literal ``{{``, ``{%``, or ``{#`` in the output.
 from __future__ import absolute_import, division, print_function
 
 import datetime
+from io import StringIO
 import linecache
 import os.path
 import posixpath
@@ -206,12 +207,7 @@ import threading
 
 from tornado import escape
 from tornado.log import app_log
-from tornado.util import ObjectDict, exec_in, unicode_type, PY3
-
-if PY3:
-    from io import StringIO
-else:
-    from cStringIO import StringIO
+from tornado.util import ObjectDict, exec_in, unicode_type
 
 _DEFAULT_AUTOESCAPE = "xhtml_escape"
 _UNSET = object()
index 68ba51777806a1940c349c372cbfe10787412b86..8d21bbdc946969057ed5369f64fcb751684e904b 100644 (file)
@@ -365,11 +365,7 @@ class HTTPServerTest(AsyncHTTPTestCase):
 
     def test_malformed_body(self):
         # parse_qs is pretty forgiving, but it will fail on python 3
-        # if the data is not utf8.  On python 2 parse_qs will work,
-        # but then the recursive_unicode call in EchoHandler will
-        # fail.
-        if str is bytes:
-            return
+        # if the data is not utf8.
         with ExpectLog(gen_log, 'Invalid x-www-form-urlencoded body'):
             response = self.fetch(
                 '/echo', method="POST",
index c19728e1366e19f2561290cb0e8391902cec3a00..0aaee67c2a35bb5665641667a239854d333e7071 100644 (file)
@@ -7,7 +7,7 @@ import traceback
 from tornado.escape import utf8, native_str, to_unicode
 from tornado.template import Template, DictLoader, ParseError, Loader
 from tornado.test.util import unittest
-from tornado.util import ObjectDict, unicode_type
+from tornado.util import ObjectDict
 
 
 class TemplateTest(unittest.TestCase):
@@ -80,12 +80,7 @@ class TemplateTest(unittest.TestCase):
         # test simulates unicode characters appearing directly in the
         # template file (with utf8 encoding), i.e. \u escapes would not
         # be used in the template file itself.
-        if str is unicode_type:
-            # python 3 needs a different version of this test since
-            # 2to3 doesn't run on template internals
-            template = Template(utf8(u'{{ "\u00e9" }}'))
-        else:
-            template = Template(utf8(u'{{ u"\u00e9" }}'))
+        template = Template(utf8(u'{{ "\u00e9" }}'))
         self.assertEqual(template.generate(), utf8(u"\u00e9"))
 
     def test_custom_namespace(self):
index d5ce0c43ff206beb0dc51810f9dcb09f04ff6aa6..01bf4a1113265fe66acf1d278290d7bc9efde796 100644 (file)
@@ -17,11 +17,8 @@ import atexit
 from inspect import getfullargspec
 import os
 import re
-import sys
 import zlib
 
-PY3 = sys.version_info >= (3,)
-
 # Aliases for types that are spelled differently in different Python
 # versions. bytes_type is deprecated and no longer used in Tornado
 # itself but is left in case anyone outside Tornado is using it.
@@ -46,11 +43,7 @@ else:
     from typing import Any, AnyStr, Union, Optional, Dict, Mapping  # noqa
     from typing import Tuple, Match, Callable  # noqa
 
-    if PY3:
-        _BaseString = str
-    else:
-        _BaseString = Union[bytes, unicode_type]
-
+    _BaseString = str
 
 try:
     from sys import is_finalizing
@@ -440,13 +433,7 @@ def _websocket_mask_python(mask, data):
     unmasked_arr = array.array("B", data)
     for i in range(len(data)):
         unmasked_arr[i] = unmasked_arr[i] ^ mask_arr[i % 4]
-    if PY3:
-        # tostring was deprecated in py32.  It hasn't been removed,
-        # but since we turn on deprecation warnings in our tests
-        # we need to use the right one.
-        return unmasked_arr.tobytes()
-    else:
-        return unmasked_arr.tostring()
+    return unmasked_arr.tobytes()
 
 
 if (os.environ.get('TORNADO_NO_EXTENSION') or
index a490ea9a928394aba495415d88fbb67b05eaf761..de9bd94806477aea9d6b846cc3c28bd72ab862bc 100644 (file)
@@ -67,6 +67,9 @@ import functools
 import gzip
 import hashlib
 import hmac
+import http.cookies
+from inspect import isclass
+from io import BytesIO
 import mimetypes
 import numbers
 import os.path
@@ -78,12 +81,13 @@ import time
 import tornado
 import traceback
 import types
-from inspect import isclass
-from io import BytesIO
+import urllib.parse
+from urllib.parse import urlencode
 
 from tornado.concurrent import Future, future_set_result_unless_cancelled
 from tornado import escape
 from tornado import gen
+from tornado.httpserver import HTTPServer
 from tornado import httputil
 from tornado import iostream
 from tornado import locale
@@ -93,20 +97,10 @@ from tornado.escape import utf8, _unicode
 from tornado.routing import (AnyMatches, DefaultHostMatches, HostMatches,
                              ReversibleRouter, Rule, ReversibleRuleRouter,
                              URLSpec)
-from tornado.util import (ObjectDict,
-                          unicode_type, _websocket_mask, PY3)
+from tornado.util import ObjectDict, unicode_type, _websocket_mask
 
 url = URLSpec
 
-if PY3:
-    import http.cookies as Cookie
-    import urllib.parse as urlparse
-    from urllib.parse import urlencode
-else:
-    import Cookie
-    import urlparse
-    from urllib import urlencode
-
 try:
     import typing  # noqa
 
@@ -556,7 +550,7 @@ class RequestHandler(object):
             # Don't let us accidentally inject bad stuff
             raise ValueError("Invalid cookie %r: %r" % (name, value))
         if not hasattr(self, "_new_cookie"):
-            self._new_cookie = Cookie.SimpleCookie()
+            self._new_cookie = http.cookies.SimpleCookie()
         if name in self._new_cookie:
             del self._new_cookie[name]
         self._new_cookie[name] = value
@@ -1936,9 +1930,6 @@ class Application(ReversibleRouter):
         .. versionchanged:: 4.3
            Now returns the `.HTTPServer` object.
         """
-        # import is here rather than top level because HTTPServer
-        # is not importable on appengine
-        from tornado.httpserver import HTTPServer
         server = HTTPServer(self, **kwargs)
         server.listen(port, address)
         return server
@@ -2895,7 +2886,7 @@ def authenticated(method):
             if self.request.method in ("GET", "HEAD"):
                 url = self.get_login_url()
                 if "?" not in url:
-                    if urlparse.urlsplit(url).scheme:
+                    if urllib.parse.urlsplit(url).scheme:
                         # if login url is absolute, make next absolute too
                         next_url = self.request.full_url()
                     else:
index 0b994fc123c4a3ee88a23a95a50300873b1e2992..bba00d1eefb979b079db561f16fe044ab7186c6f 100644 (file)
@@ -25,6 +25,7 @@ import sys
 import struct
 import tornado.escape
 import tornado.web
+from urllib.parse import urlparse
 import zlib
 
 from tornado.concurrent import Future, future_set_result_unless_cancelled
@@ -36,13 +37,7 @@ from tornado.log import gen_log
 from tornado import simple_httpclient
 from tornado.queues import Queue
 from tornado.tcpclient import TCPClient
-from tornado.util import _websocket_mask, PY3
-
-if PY3:
-    from urllib.parse import urlparse  # py2
-    xrange = range
-else:
-    from urlparse import urlparse  # py3
+from tornado.util import _websocket_mask
 
 _default_max_message_size = 10 * 1024 * 1024