### Tornado 'Hello, world' Example Web App Source: https://tornado-doc.readthedocs.io/en/latest/_sources/index A basic Tornado web application that serves 'Hello, world' on the root URL. It demonstrates setting up a request handler and starting the IOLoop. This example does not utilize asynchronous features. ```python import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Starting TCPServer with add_sockets (Advanced Multi-Process) Source: https://tornado-doc.readthedocs.io/en/latest/tcpserver This example demonstrates an advanced multi-process server setup using 'add_sockets'. It involves pre-binding sockets, forking processes using tornado.process.fork_processes, and then adding the pre-bound sockets to the TCPServer instance. ```python sockets = bind_sockets(8888) tornado.process.fork_processes(0) server = TCPServer() server.add_sockets(sockets) IOLoop.instance().start() ``` -------------------------------- ### Basic HTTP Server Example in Python Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/httpserver This example demonstrates how to create a simple HTTP server using Tornado. It defines a request handler function that echoes back the requested URI and starts the server listening on a specified port. It requires the `tornado.httpserver` and `tornado.ioloop` modules. ```python import tornado.httpserver import tornado.ioloop def handle_request(request): message = "You requested %s\n" % request.uri request.write("HTTP/1.1 200 OK\r\nContent-Length: %d\r\n\r\n%s" % ( len(message), message)) request.finish() http_server = tornado.httpserver.HTTPServer(handle_request) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Tornado IOLoop TCP Server Example Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/ioloop Demonstrates setting up a basic TCP server using Tornado's IOLoop. It involves creating a socket, binding it to a port, listening for connections, and adding a callback to handle incoming connections when they are ready for reading. This example highlights the use of `IOLoop.instance()`, `add_handler`, and `start`. ```python import errno import functools import ioloop import socket def connection_ready(sock, fd, events): while True: try: connection, address = sock.accept() except socket.error, e: if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return connection.setblocking(0) handle_connection(connection, address) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", port)) sock.listen(128) io_loop = ioloop.IOLoop.instance() callback = functools.partial(connection_ready, sock) io_loop.add_handler(sock.fileno(), callback, io_loop.READ) io_loop.start() ``` -------------------------------- ### HTTPClient Fetch Example (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/httpclient Demonstrates a basic usage of Tornado's HTTPClient to fetch a URL. It includes parsing command-line arguments to specify fetch behavior and handling potential errors during the fetch process. This example requires Tornado to be installed. ```Python def main(): from tornado.options import define, options, parse_command_line define("print_headers", type=bool, default=False) define("print_body", type=bool, default=True) define("follow_redirects", type=bool, default=True) define("validate_cert", type=bool, default=True) args = parse_command_line() client = HTTPClient() for arg in args: try: response = client.fetch(arg, ``` -------------------------------- ### Basic Tornado Web Application Setup Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Demonstrates the fundamental structure for creating a Tornado web application and starting the HTTP server. It involves defining URL routes and listening on a specific port. ```python application = web.Application([ (r"/", MainPageHandler), ]) http_server = httpserver.HTTPServer(application) http_server.listen(8080) ioloop.IOLoop.instance().start() ``` -------------------------------- ### Basic Tornado Application Setup Source: https://tornado-doc.readthedocs.io/en/latest/web This snippet demonstrates the fundamental setup of a Tornado web application. It initializes an Application instance with a list of URL specifications, creates an HTTPServer, and starts the I/O loop to listen for incoming requests on port 8080. ```python application = web.Application([ (r"/", MainPageHandler), ]) http_server = httpserver.HTTPServer(application) http_server.listen(8080) ioloop.IOLoop.instance().start() ``` -------------------------------- ### GET Method Example Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Example of how to implement a GET method in a RequestHandler. ```APIDOC ## GET Method ### Description Handles HTTP GET requests. ### Method GET ### Endpoint Custom endpoint defined by the URL spec. ### Parameters (No specific parameters documented for the method itself, relies on URL spec) ### Request Example (GET request, no body typically) ### Response #### Success Response (200) - **Content** (string) - The response body written by the handler. #### Response Example "Hello, world" ``` -------------------------------- ### Install Twisted Reactor on Tornado IOLoop (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_sources/twisted Implements the Twisted reactor interface on top of the Tornado IOLoop. Call install() at the beginning of the application. Use IOLoop.instance().start() to start the application instead of reactor.run(). ```python import tornado.platform.twisted tornado.platform.twisted.install() from twisted.internet import reactor # ... application setup ... # Instead of reactor.run(), use: tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Manual Tornado Installation Source: https://tornado-doc.readthedocs.io/en/latest/_sources/index Steps for manually installing Tornado from a downloaded source tarball. This involves extracting the archive, building the package, and then installing it. ```bash tar xvzf tornado-|version|.tar.gz cd tornado-|version| python setup.py build sudo python setup.py install ``` -------------------------------- ### Install Tornado using pip Source: https://tornado-doc.readthedocs.io/en/latest/_sources/index Command to install the Tornado web framework using the pip package installer. This is the recommended and automatic method for installation. ```bash pip install tornado ``` -------------------------------- ### Python: Third-party authentication example (Google) Source: https://tornado-doc.readthedocs.io/en/latest/_sources/overview An example of implementing third-party authentication using Tornado's `auth` module, specifically for Google. This handler inherits from `tornado.web.RequestHandler` and `tornado.auth.GoogleMixin`. The `get` method initiates the authentication flow and saves credentials in a cookie. ```python class GoogleHandler(tornado.web.RequestHandler, tornado.auth.GoogleMixin): @tornado.web.asynchronous def get(self): if self.get_argument("openid.mode", None): # Authentication callback logic would go here pass else: self.authenticate_google() ``` -------------------------------- ### Shell: Manual Installation of Tornado Source: https://tornado-doc.readthedocs.io/en/latest/index Installs Tornado manually by downloading the source tarball, extracting it, building the package, and then installing it. This method allows access to demo applications not included in pip installations. ```shell tar xvzf tornado-3.2.dev1.tar.gz cd tornado-3.2.dev1 python setup.py build sudo python setup.py install ``` -------------------------------- ### Start and Fetch with AsyncHTTPTestCase Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/testing Provides methods to start an HTTP server, fetch URLs synchronously, and configure HTTPServer options. It relies on Tornado's IOLoop for asynchronous operations and AsyncHTTPClient for fetching. ```python def get_http_server(self): return HTTPServer(self._app, io_loop=self.io_loop, **self.get_httpserver_options()) def fetch(self, path, **kwargs): """Convenience method to synchronously fetch a url. The given path will be appended to the local server's host and port. Any additional kwargs will be passed directly to `.AsyncHTTPClient.fetch` (and so could be used to pass ``method="POST"``, ``body="..."``, etc). """ self.http_client.fetch(self.get_url(path), self.stop, **kwargs) return self.wait() def get_httpserver_options(self): """May be overridden by subclasses to return additional keyword arguments for the server. """ return {} def get_http_port(self): """Returns the port used by the server. A new port is chosen for each test. """ return self.__port def get_protocol(self): return 'http' def get_url(self, path): """Returns an absolute url for the given path on the test server.""" return '%s://localhost:%s%s' % (self.get_protocol(), self.get_http_port(), path) def tearDown(self): self.http_server.stop() if ( not IOLoop.initialized() or self.http_client.io_loop is not IOLoop.instance() ): self.http_client.close() super(AsyncHTTPTestCase, self).tearDown() ``` -------------------------------- ### POST Method Example Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Example of how to implement a POST method in a RequestHandler. ```APIDOC ## POST Method ### Description Handles HTTP POST requests. ### Method POST ### Endpoint Custom endpoint defined by the URL spec. ### Parameters #### Request Body (Details depend on the specific implementation and expected data) ### Request Example ```json { "key": "value" } ``` ### Response #### Success Response (200) - **Content** (string/object) - The response body written by the handler. #### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Tornado IOLoop Instance Management Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/ioloop Provides Python code for managing the global instance of Tornado's IOLoop. It includes methods to get the singleton instance, check if it has been initialized, and install a custom instance. This is crucial for ensuring consistent IOLoop behavior across an application. ```python from tornado.ioloop import IOLoop # Get the global instance io_loop = IOLoop.instance() # Check if the instance has been created if IOLoop.initialized(): print("IOLoop has been initialized.") # Install a custom instance (usually done by subclasses) # IOLoop._instance = MyCustomIOLoop() # Or using the install method: # custom_loop = MyCustomIOLoop() # custom_loop.install() ``` -------------------------------- ### Starting TCPServer with listen (Single-Process) Source: https://tornado-doc.readthedocs.io/en/latest/tcpserver This code shows the basic pattern for starting a TCPServer in a single-process mode using the 'listen' method. It binds the server to a specified port and then starts the IOLoop to begin accepting connections. ```python server = TCPServer() server.listen(8888) IOLoop.instance().start() ``` -------------------------------- ### Tornado RequestHandler initialize Method Example Source: https://tornado-doc.readthedocs.io/en/latest/overview This example demonstrates overriding the `initialize` method in a Tornado `RequestHandler`. The `initialize` method is called when a handler instance is created and is used to set up initial state, often by accepting configuration parameters passed during application setup, such as a database connection. ```python class ProfileHandler(tornado.web.RequestHandler): def initialize(self, database): self.database = database def get(self, username): ... # Handler logic using self.database # Assuming 'database' is an initialized database object # application = tornado.web.Application([ # (r'/user/(.*)', ProfileHandler, dict(database=database)), # ]) ``` -------------------------------- ### Serving Static Files with Tornado Source: https://tornado-doc.readthedocs.io/en/latest/web This example shows how to configure a Tornado application to serve static files. It uses the `StaticFileHandler` and specifies a path for the static files. The configuration allows requests starting with `/static/` to be served from the `/var/www` directory. ```python application = web.Application([ (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}), ]) ``` -------------------------------- ### Starting TCPServer with bind/start (Multi-Process) Source: https://tornado-doc.readthedocs.io/en/latest/tcpserver This snippet illustrates the pattern for starting a TCPServer in a multi-process mode. It first binds the server to a port using 'bind', then uses 'start(0)' to fork multiple child processes for handling connections. The default IOLoop is used. ```python server = TCPServer() server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.instance().start() ``` -------------------------------- ### Tornado RedirectHandler Example Source: https://tornado-doc.readthedocs.io/en/latest/web Illustrates the usage of RedirectHandler to redirect clients to a specified URL for all GET requests. The 'url' keyword argument must be provided when configuring the handler in the application routes. ```python application = web.Application([ (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}), ]) ``` -------------------------------- ### HTTP Client Example using IOStream Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/iostream This Python code snippet demonstrates how to create a simple HTTP client using Tornado's IOStream. It shows how to connect to a host, send an HTTP GET request, read response headers and body, and then close the connection. It requires tornado.ioloop, tornado.iostream, and socket modules. ```python import tornado.ioloop import tornado.iostream import socket def send_request(): stream.write(b"GET / HTTP/1.0\r\nHost: friendfeed.com\r\n\r\n") stream.read_until(b"\r\n\r\n", on_headers) def on_headers(data): headers = {} for line in data.split(b"\r\n"): parts = line.split(b":") if len(parts) == 2: headers[parts[0].strip()] = parts[1].strip() stream.read_bytes(int(headers[b"Content-Length"]), on_body) def on_body(data): print data stream.close() tornado.ioloop.IOLoop.instance().stop() s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) stream = tornado.iostream.IOStream(s) stream.connect(("friendfeed.com", 80), send_request) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Start Tornado HTTP Server on a Port Source: https://tornado-doc.readthedocs.io/en/latest/web Starts an HTTP server for a Tornado application on the specified port. This is a convenience method that wraps the creation of an HTTPServer object. It requires calling `IOLoop.instance().start()` afterwards to begin the server's event loop. Keyword arguments not directly supported by `HTTPServer.listen` are passed to the `HTTPServer` constructor. ```python tornado.web.Application.listen(_port_, _address='', _**kwargs_) ``` -------------------------------- ### Template Handling Source: https://tornado-doc.readthedocs.io/en/latest/web Methods for creating template loaders and getting template paths. ```APIDOC ## Template Handling ### Description Methods for managing template loading and path configuration. ### Methods - `create_template_loader(template_path)` - `get_template_path()` ### Endpoint N/A ### Parameters #### `create_template_loader` - **template_path** (str) - The path to the directory containing templates. ### Request Example ```python # Create a template loader for a specific path template_loader = self.create_template_loader('/path/to/templates') # Get the default template path template_path = self.get_template_path() ``` ### Response #### Success Response - **create_template_loader()** (tornado.web.BaseLoader) - A template loader instance. - **get_template_path()** (str or None) - The template path for the handler, or `None` to load relative to the calling file. ### Notes - `create_template_loader` by default returns a directory-based loader using the `autoescape` application setting. If `template_loader` application setting is supplied, it uses that instead. - `get_template_path` can be overridden to customize the template path per handler. By default, it uses the `template_path` application setting. ``` -------------------------------- ### Hello, world Example Source: https://tornado-doc.readthedocs.io/en/latest/overview A basic 'Hello, world' application using Tornado's web server and I/O loop. ```APIDOC ## GET / ### Description This endpoint serves a simple 'Hello, world' message. ### Method GET ### Endpoint / ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **message** (string) - The 'Hello, world' message. #### Response Example ``` Hello, world ``` ``` -------------------------------- ### Set up HTTP Server for Testing (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/testing The setUp method for AsyncHTTPTestCase initializes an unused port, creates an HTTP client, and sets up an HTTP server using the application returned by get_app(). This prepares the test environment for making HTTP requests to the server under test. ```python def setUp(self): super(AsyncHTTPTestCase, self).setUp() sock, port = bind_unused_port() self.__port = port self.http_client = self.get_http_client() self._app = self.get_app() self.http_server = self.get_http_server() self.http_server.add_sockets([sock]) ``` -------------------------------- ### Install Tornado IOLoop on Twisted Reactor Source: https://tornado-doc.readthedocs.io/en/latest/twisted Installs the TwistedIOLoop, which implements the Tornado IOLoop interface on top of the Twisted reactor. This setup requires the global Twisted reactor and is recommended for running Tornado applications within a Twisted event loop. ```python from tornado.platform.twisted import TwistedIOLoop from twisted.internet import reactor TwistedIOLoop().install() # Set up your tornado application as usual using `IOLoop.instance` reactor.run() ``` -------------------------------- ### HTTPServer Initialization Patterns in Python Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/httpserver Illustrates the three primary methods for initializing and running an `HTTPServer` in Tornado for single-process or multi-process applications. These patterns involve `listen`, `bind`/`start`, and `add_sockets`, offering flexibility in deployment. ```python # 1. Simple single-process: server = HTTPServer(app) server.listen(8888) IOLoop.instance().start() ``` ```python # 2. Simple multi-process: server = HTTPServer(app) server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.instance().start() ``` ```python # 3. Advanced multi-process: sockets = tornado.netutil.bind_sockets(8888) tornado.process.fork_processes(0) server = HTTPServer(app) server.add_sockets(sockets) IOLoop.instance().start() ``` -------------------------------- ### Install Twisted Reactor on Tornado IOLoop Source: https://tornado-doc.readthedocs.io/en/latest/twisted Installs the TornadoReactor, which implements the Twisted reactor interface on top of the Tornado IOLoop. This is typically done at the application's start. Cleanup may be required for short-lived IOLoops in unit tests by calling specific reactor shutdown methods. ```python import tornado.platform.twisted tornado.platform.twisted.install() from twisted.internet import reactor # When the app is ready to start, call IOLoop.instance().start() instead of reactor.run() # For short-lived IOLoops (e.g., unit tests): # reactor.fireSystemEvent('shutdown') # reactor.disconnectAll() ``` -------------------------------- ### Tornado IOLoop TCP Server Example (Python) Source: https://tornado-doc.readthedocs.io/en/latest/ioloop This Python code demonstrates how to set up a simple TCP server using Tornado's IOLoop. It involves creating a socket, binding it, listening for connections, and adding a handler to the IOLoop to accept incoming connections asynchronously. Dependencies include the `socket`, `functools`, and `errno` modules. ```python import errno import functools import ioloop import socket def connection_ready(sock, fd, events): while True: try: connection, address = sock.accept() except socket.error, e: if e.args[0] not in (errno.EWOULDBLOCK, errno.EAGAIN): raise return connection.setblocking(0) handle_connection(connection, address) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) sock.bind(("", port)) sock.listen(128) io_loop = ioloop.IOLoop.instance() callback = functools.partial(connection_ready, sock) io_loop.add_handler(sock.fileno(), callback, io_loop.READ) io_loop.start() ``` -------------------------------- ### Tornado Redirect Example Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web A simple `get` method in a Tornado RequestHandler that performs a permanent redirect to a specified URL. This is commonly used for URL rewriting or moving resources. ```python def get(self): self.redirect(self._url, permanent=self._permanent) ``` -------------------------------- ### Get Current Task ID Source: https://tornado-doc.readthedocs.io/en/latest/process Returns the ID of the current task if the process was created by `fork_processes`. Returns None if the process was not started using `fork_processes`. ```python tornado.process.task_id() ``` -------------------------------- ### AsyncTestCase Setup (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/testing Sets up the `AsyncTestCase` by initializing and making a new `IOLoop` current for the test. This ensures that each test has its own isolated IOLoop instance. ```python [docs] class AsyncTestCase(unittest.TestCase): ""`~unittest.TestCase` subclass for testing `.IOLoop`-based asynchronous code. The unittest framework is synchronous, so the test must be complete by the time the test method returns. This means that asynchronous code cannot be used in quite the same way as usual. To write test functions that use the same ``yield``-based patterns used with the `tornado.gen` module, decorate your test methods with `tornado.testing.gen_test` instead of `tornado.gen.coroutine`. This class also provides the `stop()` and `wait()` methods for a more manual style of testing. The test method itself must call ``self.wait()``, and asynchronous callbacks should call ``self.stop()`` to signal completion. By default, a new `.IOLoop` is constructed for each test and is available as ``self.io_loop``. This `.IOLoop` should be used in the construction of HTTP clients/servers, etc. If the code being tested requires a global `.IOLoop`, subclasses should override `get_new_ioloop` to return it. The `.IOLoop`'s ``start`` and ``stop`` methods should not be called directly. Instead, use `self.stop ` and `self.wait `. Arguments passed to ``self.stop`` are returned from ``self.wait``. It is possible to have multiple ``wait``/``stop`` cycles in the same test. Example:: # This test uses coroutine style. class MyTestCase(AsyncTestCase): @tornado.testing.gen_test def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) response = yield client.fetch("http://www.tornadoweb.org") # Test contents of response self.assertIn("FriendFeed", response.body) # This test uses argument passing between self.stop and self.wait. class MyTestCase2(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.stop) response = self.wait() # Test contents of response self.assertIn("FriendFeed", response.body) # This test uses an explicit callback-based style. class MyTestCase3(AsyncTestCase): def test_http_fetch(self): client = AsyncHTTPClient(self.io_loop) client.fetch("http://www.tornadoweb.org/", self.handle_fetch) self.wait() def handle_fetch(self, response): # Test contents of response (failures and exceptions here # will cause self.wait() to throw an exception and end the # test). # Exceptions thrown here are magically propagated to # self.wait() in test_http_fetch() via stack_context. self.assertIn("FriendFeed", response.body) self.stop() """ def __init__(self, *args, **kwargs): super(AsyncTestCase, self).__init__(*args, **kwargs) self.__stopped = False self.__running = False self.__failure = None self.__stop_args = None self.__timeout = None def setUp(self): super(AsyncTestCase, self).setUp() self.io_loop = self.get_new_ioloop() self.io_loop.make_current() ``` -------------------------------- ### Tornado Application Listen Method Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Provides a convenience method to start an HTTP server for the application on a given port. It abstracts the creation of an `HTTPServer` instance and its listening process. Note that `IOLoop.instance().start()` must still be called. ```python def listen(self, port, address="", **kwargs): """Starts an HTTP server for this application on the given port. This is a convenience alias for creating an `.HTTPServer` object and calling its listen method. Keyword arguments not supported by `HTTPServer.listen <.TCPServer.listen>` are passed to the `.HTTPServer` constructor. For advanced uses (e.g. multi-process mode), do not use this method; create an `.HTTPServer` and call its `.TCPServer.bind`/`.TCPServer.start` methods directly. Note that after calling this method you still need to call ``IOLoop.instance().start()`` to start the server. """ # 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) ``` -------------------------------- ### Tornado HTTPServer Initialization: listen Source: https://tornado-doc.readthedocs.io/en/latest/httpserver The 'listen' method for simple single-process Tornado HTTP server setup. It initializes an HTTPServer with an application and binds it to a specified port. The IOLoop is then started to handle incoming connections. ```python server = HTTPServer(app) server.listen(8888) IOLoop.instance().start() ``` -------------------------------- ### Tornado Hello World Web Application Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web A basic Tornado web application demonstrating a simple "Hello, world" response. It sets up a handler for the root URL and starts the server on port 8888. This requires the tornado library. ```python import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") if __name__ == "__main__": application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Tornado Application Initialization with Settings Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Shows the initialization of a Tornado `web.Application` with various settings, including transformations like gzip encoding and static file serving configurations. It also includes the automatic reload functionality for debugging. ```python def __init__(self, handlers=None, default_host="", transforms=None, wsgi=False, **settings): if transforms is None: self.transforms = [] if settings.get("gzip"): self.transforms.append(GZipContentEncoding) self.transforms.append(ChunkedTransferEncoding) else: self.transforms = transforms self.handlers = [] self.named_handlers = {} self.default_host = default_host self.settings = settings self.ui_modules = {'linkify': _linkify, 'xsrf_form_html': _xsrf_form_html, 'Template': TemplateModule, } self.ui_methods = {} self._wsgi = wsgi self._load_ui_modules(settings.get("ui_modules", {})) self._load_ui_methods(settings.get("ui_methods", {})) if self.settings.get("static_path"): path = self.settings["static_path"] handlers = list(handlers or []) static_url_prefix = settings.get("static_url_prefix", "/static/") static_handler_class = settings.get("static_handler_class", StaticFileHandler) static_handler_args = settings.get("static_handler_args", {}) static_handler_args['path'] = path for pattern in [re.escape(static_url_prefix) + r"(.*)", r"/(favicon.ico)", r"/(robots.txt)"]: handlers.insert(0, (pattern, static_handler_class, static_handler_args)) if handlers: self.add_handlers(".*$", handlers) # Automatically reload modified modules if self.settings.get("debug") and not wsgi: from tornado import autoreload autoreload.start() ``` -------------------------------- ### Shell: Install Tornado using pip Source: https://tornado-doc.readthedocs.io/en/latest/index Installs the Tornado Python package using pip, the standard package installer for Python. This is the recommended method for automatic installation. ```shell pip install tornado ``` -------------------------------- ### Python: Tornado 'Hello, world' Web App Source: https://tornado-doc.readthedocs.io/en/latest/index A basic 'Hello, world' web application using the Tornado framework. It sets up a simple request handler to respond with 'Hello, world' and listens on port 8888. This example demonstrates the fundamental structure of a Tornado application but does not utilize its asynchronous features. ```python import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") application = tornado.web.Application([ (r"/", MainHandler), ]) if __name__ == "__main__": application.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### IOLoop Configuration Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/ioloop Methods for configuring the IOLoop, including determining the appropriate IOLoop implementation based on the system and initializing the IOLoop. ```APIDOC ## IOLoop Configuration ### `IOLoop.configurable_base()` Returns the base class for configurable IOLoop implementations. ### `IOLoop.configurable_default()` Returns the default IOLoop implementation for the current platform (e.g., EPollIOLoop, KQueueIOLoop, SelectIOLoop). ### `IOLoop.initialize()` Initializes the IOLoop instance. This method is intended for subclasses to override. ``` -------------------------------- ### Get Content of a Resource (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/web Retrieves the content of a resource from a given absolute path. This method can return content as a byte string or an iterator of byte strings, with the latter being preferred for large files to minimize memory usage. It supports reading content within a specified byte range (start and end). ```python def get_content(cls, abspath, start=None, end=None): """Retrieve the content of the requested resource which is located at the given absolute path. This class method may be overridden by subclasses. Note that its signature is different from other overridable class methods (no ``settings`` argument); this is deliberate to ensure that ``abspath`` is able to stand on its own as a cache key. This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation. .. versionadded:: 3.1 """ with open(abspath, "rb") as file: if start is not None: file.seek(start) if end is not None: remaining = end - (start or 0) else: remaining = None while True: chunk_size = 64 * 1024 if remaining is not None and remaining < chunk_size: chunk_size = remaining chunk = file.read(chunk_size) if chunk: if remaining is not None: remaining -= len(chunk) yield chunk else: if remaining is not None: assert remaining == 0 return ``` -------------------------------- ### Tornado Form Handling with get_argument Source: https://tornado-doc.readthedocs.io/en/latest/overview This example demonstrates how to handle HTML form submissions in Tornado. The `get` method displays a form, and the `post` method processes the submitted data using `self.get_argument("message")` to retrieve the value of the 'message' input field. It also shows how to set response headers. ```python class MyFormHandler(tornado.web.RequestHandler): def get(self): self.write('
' \ ' ' \ ' ' \ '
') def post(self): self.set_header("Content-Type", "text/plain") self.write("You wrote " + self.get_argument("message")) ``` -------------------------------- ### Create a Simple 'Hello, world' Tornado Web App Source: https://tornado-doc.readthedocs.io/en/latest/web This Python snippet demonstrates the basic structure of a Tornado web application. It defines a RequestHandler to respond with 'Hello, world' and sets up the Application to listen on port 8888. It requires the tornado library. ```python import tornado.ioloop import tornado.web class MainHandler(tornado.web.RequestHandler): def get(self): self.write("Hello, world") if __name__ == "__main__": application = tornado.web.Application([ (r"/", MainHandler), ]) application.listen(8888) tornado.ioloop.IOLoop.instance().start() ``` -------------------------------- ### Tornado HTTP Request Initialization Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/httpserver Initializes an HTTP request object with details such as method, URI, version, headers, body, remote IP, protocol, host, files, and connection information. It parses GET/POST arguments from the query string and sets up protocol and host based on headers and connection details. Dependencies include `httputil`, `iostream`, `netutil`, `time`, and `Cookie`. ```python def __init__(self, method, uri, version="HTTP/1.0", headers=None, body=None, remote_ip=None, protocol=None, host=None, files=None, connection=None): self.method = method self.uri = uri self.version = version self.headers = headers or httputil.HTTPHeaders() self.body = body or "" # set remote IP and protocol self.remote_ip = remote_ip if protocol: self.protocol = protocol elif connection and isinstance(connection.stream, iostream.SSLIOStream): self.protocol = "https" else: self.protocol = "http" # xheaders can override the defaults if connection and connection.xheaders: # Squid uses X-Forwarded-For, others use X-Real-Ip ip = self.headers.get("X-Forwarded-For", self.remote_ip) ip = ip.split(',')[-1].strip() ip = self.headers.get( "X-Real-Ip", ip) if netutil.is_valid_ip(ip): self.remote_ip = ip # AWS uses X-Forwarded-Proto proto = self.headers.get( "X-Scheme", self.headers.get("X-Forwarded-Proto", self.protocol)) if proto in ("http", "https"): self.protocol = proto self.host = host or self.headers.get("Host") or "127.0.0.1" self.files = files or {} self.connection = connection self._start_time = time.time() self._finish_time = None self.path, sep, self.query = uri.partition('?') self.arguments = parse_qs_bytes(self.query, keep_blank_values=True) ``` -------------------------------- ### GET Request Handler Source: https://tornado-doc.readthedocs.io/en/latest/web Handles HTTP GET requests. Define this method to respond to GET requests for a specific endpoint. ```APIDOC ## `RequestHandler.get()` ### Description Implement this method to handle HTTP GET requests. Can be made asynchronous. ### Method `GET` ### Endpoint As defined in the `Application` URL specs. ### Parameters - ***args**: (any) - Positional arguments captured from the URL regex. - ****kwargs**: (any) - Keyword arguments captured from the URL regex or passed via `initialize`. ### Request Example ```python class MyHandler(RequestHandler): def get(self, user_id): self.write(f"Fetching data for user: {user_id}") # URL spec: (r'/users/([0-9]+)', MyHandler) ``` ### Response #### Success Response (200) Content determined by the handler's `write()` calls. #### Response Example ```json "Fetching data for user: 123" ``` ``` -------------------------------- ### Tornado Test Runner with Option Parsing Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/testing The `main` function provides a simple test runner for Tornado projects, analogous to `unittest.main`. It integrates Tornado's option parsing and log formatting capabilities. Tests can be run from the command line using `python -m tornado.testing ` or by defining an `all()` method in a test script to return a test suite. Additional keyword arguments are passed directly to `unittest.main`. ```python import logging import unittest from tornado.options import define, options, parse_command_line # Assuming gen_log and AsyncHTTPTestCase are defined elsewhere in Tornado # from tornado import gen_log # from tornado.testing import AsyncHTTPTestCase # Placeholder for gen_log if not available in this context class MockGenLog: def info(self, message): print(f"INFO: {message}") gen_log = MockGenLog() # Placeholder for AsyncHTTPTestCase if not available in this context class AsyncHTTPTestCase(unittest.TestCase): pass basestring_type = str # Define basestring_type for Python 3 compatibility class LogTrapTestCase(unittest.TestCase): """A test case that captures and discards all logging output if the test passes. Some libraries can produce a lot of logging output even when the test succeeds, so this class can be useful to minimize the noise. Simply use it as a base class for your test case. It is safe to combine with AsyncTestCase via multiple inheritance (``class MyTestCase(AsyncHTTPTestCase, LogTrapTestCase):``) This class assumes that only one log handler is configured and that it is a `~logging.StreamHandler`. This is true for both `logging.basicConfig` and the "pretty logging" configured by `tornado.options`. It is not compatible with other log buffering mechanisms, such as those provided by some test runners. """ def run(self, result=None): logger = logging.getLogger() if not logger.handlers: logging.basicConfig() handler = logger.handlers[0] if (len(logger.handlers) > 1 or 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) return old_stream = handler.stream try: handler.stream = StringIO() gen_log.info("RUNNING TEST: " + str(self)) old_error_count = len(result.failures) + len(result.errors) super(LogTrapTestCase, self).run(result) new_error_count = len(result.failures) + len(result.errors) if new_error_count != old_error_count: old_stream.write(handler.stream.getvalue()) finally: handler.stream = old_stream class ExpectLog(logging.Filter): """Context manager to capture and suppress expected log output. Useful to make tests of error conditions less noisy, while still leaving unexpected log entries visible. *Not thread safe.* Usage:: with ExpectLog('tornado.application', "Uncaught exception"): error_response = self.fetch("/some_page") """ def __init__(self, logger, regex, required=True): """Constructs an ExpectLog context manager. :param logger: Logger object (or name of logger) to watch. Pass an empty string to watch the root logger. :param regex: Regular expression to match. Any log entries on the specified logger that match this regex will be suppressed. :param required: If true, an exeption will be raised if the end of the ``with`` statement is reached without matching any log entries. """ if isinstance(logger, basestring_type): logger = logging.getLogger(logger) self.logger = logger self.regex = re.compile(regex) self.required = required self.matched = False def filter(self, record): message = record.getMessage() if self.regex.match(message): self.matched = True return False return True def __enter__(self): self.logger.addFilter(self) def __exit__(self, typ, value, tb): self.logger.removeFilter(self) if not typ and self.required and not self.matched: raise Exception("did not get expected log message") def main(**kwargs): """A simple test runner. This test runner is essentially equivalent to `unittest.main` from the standard library, but adds support for tornado-style option parsing and log formatting. The easiest way to run a test is via the command line:: python -m tornado.testing tornado.test.stack_context_test See the standard library unittest module for ways in which tests can be specified. Projects with many tests may wish to define a test script like ``tornado/test/runtests.py``. This script should define a method ``all()`` which returns a test suite and then call `tornado.testing.main()`. Note that even when a test script is used, the ``all()`` test suite may be overridden by naming a single test on the command line:: # Runs all tests python -m tornado.test.runtests # Runs one test python -m tornado.test.runtests tornado.test.stack_context_test Additional keyword arguments passed through to ``unittest.main()``. For example, use ``tornado.testing.main(verbosity=2)`` to show many test details as they are run. See http://docs.python.org/library/unittest.html#unittest.main for full argument list. """ from tornado.options import define, options, parse_command_line define('exception_on_interrupt', type=bool, default=True, help=("If true (default), ctrl-c raises a KeyboardInterrupt " "exception. This prints a stack trace but cannot interrupt ``` -------------------------------- ### Group and Use Application Settings (Python) Source: https://tornado-doc.readthedocs.io/en/latest/options Illustrates how to define options that belong to a specific group, named 'application' in this case. It then shows how to parse command-line arguments and use the `group_dict` method to extract these grouped options to initialize a Tornado `Application`. ```Python from tornado.options import define, parse_command_line, options define('template_path', group='application') define('static_path', group='application') parse_command_line() application = Application( handlers, **options.group_dict('application')) ``` -------------------------------- ### Listen on a Port with TCPServer (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/tcpserver Shows the basic method to start a TCPServer listening on a specific port. This method immediately starts accepting connections and requires the IOLoop to be started separately. It internally uses bind_sockets and add_sockets. ```python from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop server = TCPServer() server.listen(8888) IOLoop.instance().start() ``` -------------------------------- ### Bind and Start a Multi-Process TCPServer (Python) Source: https://tornado-doc.readthedocs.io/en/latest/_modules/tornado/tcpserver Illustrates the pattern for starting a TCPServer in a multi-process environment. The server is bound to a port, and then `start(0)` forks multiple child processes to handle connections. The default IOLoop is always used. ```python from tornado.tcpserver import TCPServer from tornado.ioloop import IOLoop server = TCPServer() server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.instance().start() ``` -------------------------------- ### Tornado HTTPServer Initialization: bind/start Source: https://tornado-doc.readthedocs.io/en/latest/httpserver The 'bind' and 'start' methods for multi-process Tornado HTTP server deployment. The server is bound to a port, and then 'start(0)' forks multiple sub-processes to handle requests. The default IOLoop is always started. ```python server = HTTPServer(app) server.bind(8888) server.start(0) # Forks multiple sub-processes IOLoop.instance().start() ``` -------------------------------- ### HTML Template for Localization Source: https://tornado-doc.readthedocs.io/en/latest/_sources/overview An example of an HTML template demonstrating localized strings using Tornado's `_()` function and request path placeholders. This helps in creating multi-language web pages. ```html FriendFeed - {{ _("Sign in") }}
{{ _("Username") }}
{{ _("Password") }}
{% module xsrf_form_html() %}
``` -------------------------------- ### Tornado Form Handling with GET and POST Source: https://tornado-doc.readthedocs.io/en/latest/_sources/overview Demonstrates handling both GET and POST requests for a form using Tornado. The GET method serves an HTML form, and the POST method processes the submitted data, specifically retrieving a form argument named 'message'. ```python class MyFormHandler(tornado.web.RequestHandler): def get(self): self.write('
' \ ' ' \ ' ' \ '
') def post(self): self.set_header("Content-Type", "text/plain") self.write("You wrote " + self.get_argument("message")) ``` -------------------------------- ### Application Constructor and Handlers Source: https://tornado-doc.readthedocs.io/en/latest/web Demonstrates the basic structure of a Tornado application, including how to define request handlers and serve static files. ```APIDOC ## POST /api/users ### Description Creates a new user in the system. ### Method POST ### Endpoint /api/users ### Parameters #### Query Parameters - **fields** (string) - Optional - Comma-separated list of fields to include in the response. #### Request Body - **username** (string) - Required - The desired username for the new user. - **email** (string) - Required - The email address of the new user. - **password** (string) - Required - The password for the new user. ### Request Example ```json { "username": "testuser", "email": "test@example.com", "password": "securepassword" } ``` ### Response #### Success Response (201) - **id** (integer) - The unique identifier of the newly created user. - **username** (string) - The username of the new user. - **email** (string) - The email address of the new user. #### Response Example ```json { "id": 123, "username": "testuser", "email": "test@example.com" } ``` #### Error Response (400) - **error** (string) - A message describing the error. #### Error Example ```json { "error": "Username already exists." } ``` ```