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``.
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
import errno
import os
+import multiprocessing
import signal
import subprocess
import sys
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
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
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):
@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)
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
import errno
import os
import socket
+import ssl
from tornado import gen
from tornado.log import app_log
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.
from __future__ import absolute_import, division, print_function
import datetime
+from io import StringIO
import linecache
import os.path
import posixpath
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()
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",
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):
# 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):
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.
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
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
import gzip
import hashlib
import hmac
+import http.cookies
+from inspect import isclass
+from io import BytesIO
import mimetypes
import numbers
import os.path
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
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
# 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
.. 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
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:
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
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