From: Ben Darnell Date: Sat, 7 Jul 2018 23:34:55 +0000 (-0400) Subject: *: Remove unnecessary conditional imports X-Git-Tag: v6.0.0b1~48^2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e1d24ac6f03e28aa66789c49bc7e917990e7a9bb;p=thirdparty%2Ftornado.git *: Remove unnecessary conditional imports --- diff --git a/tornado/autoreload.py b/tornado/autoreload.py index 7d69474a3..9c5b2326b 100644 --- a/tornado/autoreload.py +++ b/tornado/autoreload.py @@ -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``. diff --git a/tornado/platform/auto.py b/tornado/platform/auto.py index 553b70e36..16ee9091a 100644 --- a/tornado/platform/auto.py +++ b/tornado/platform/auto.py @@ -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 diff --git a/tornado/process.py b/tornado/process.py index 96f1f4539..7a5fbaed0 100644 --- a/tornado/process.py +++ b/tornado/process.py @@ -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 diff --git a/tornado/simple_httpclient.py b/tornado/simple_httpclient.py index 851ebb61f..bf41abbf1 100644 --- a/tornado/simple_httpclient.py +++ b/tornado/simple_httpclient.py @@ -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 diff --git a/tornado/tcpserver.py b/tornado/tcpserver.py index 4f5d6f033..31e16b8df 100644 --- a/tornado/tcpserver.py +++ b/tornado/tcpserver.py @@ -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. diff --git a/tornado/template.py b/tornado/template.py index 61b987462..382f08f40 100644 --- a/tornado/template.py +++ b/tornado/template.py @@ -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() diff --git a/tornado/test/httpserver_test.py b/tornado/test/httpserver_test.py index 68ba51777..8d21bbdc9 100644 --- a/tornado/test/httpserver_test.py +++ b/tornado/test/httpserver_test.py @@ -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", diff --git a/tornado/test/template_test.py b/tornado/test/template_test.py index c19728e13..0aaee67c2 100644 --- a/tornado/test/template_test.py +++ b/tornado/test/template_test.py @@ -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): diff --git a/tornado/util.py b/tornado/util.py index d5ce0c43f..01bf4a111 100644 --- a/tornado/util.py +++ b/tornado/util.py @@ -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 diff --git a/tornado/web.py b/tornado/web.py index a490ea9a9..de9bd9480 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -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: diff --git a/tornado/websocket.py b/tornado/websocket.py index 0b994fc12..bba00d1ee 100644 --- a/tornado/websocket.py +++ b/tornado/websocket.py @@ -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