Python Tornado Webserver Simple Examples
Last Updated :
02 Feb, 2024
Tornado is a robust, open-source web framework designed for building scalable and non-blocking web applications in Python. It was developed by FriendFeed (later acquired by Facebook) to handle long-lived network connections efficiently. Tornado is known for its high performance, simplicity, and asynchronous capabilities, making it an excellent choice for building real-time web applications.
In this article, we will explore Tornado through three code examples, ranging from a simple "Hello World" application to more advanced features like form submission and file uploads.
Tornado -Web Framework
Below, are the example of Tornado -Web Framework in Python.
Example 1: Hello World in Tornado
In this example, below Python script below uses the Tornado web framework to create a basic web application. It defines a handler that responds with "Hello, Tornado!" to a GET request at the root ("/") URL. The application listens on port 8888 and starts the Tornado I/O loop when executed.
Python3
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, Tornado!")
def make_app():
return tornado.web.Application([(r"/", MainHandler)])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
Run the Server
run the tornado server using below command
python script_name.py
Ouput :

Example 2: Form Submission in Tornado
app.py : Now, let's look at a more advanced example that involves handling form submissions. In this example, we create a form with an input field for the user's name. The Tornado handler retrieves the submitted data using self.get_argument and responds with a personalized greeting.
Python3
import tornado.ioloop
import tornado.web
class FormHandler(tornado.web.RequestHandler):
def get(self):
self.render("form.html")
def post(self):
name = self.get_argument("name")
self.write(f"Hello, {name}!")
def make_app():
return tornado.web.Application([(r"/form", FormHandler)])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
index.html : This HTML document defines a simple form with a "Name" input field and a submit button. It links to an external stylesheet ("style.css") for styling, setting the form's width and styling labels and inputs. The form is set to submit data to "/form" using the POST method.
HTML
<!DOCTYPE html>
<html>
<head>
<title>Simple Form</title>
<link rel="stylesheet" type="text/css" href="/static/style.css">
</head>
<style>
/* style.css */
body {
font-family: Arial, sans-serif;
margin: 20px;
}
form {
width: 300px;
}
label {
display: block;
margin-bottom: 5px;
}
input {
width: 100%;
margin-bottom: 10px;
}
</style>
<body>
<h2>Simple Form</h2>
<form action="/form" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br>
<input type="submit" value="Submit">
</form>
</body>
</html>
Run the Server
run the tornado server using below command
python script_name.py
Output :
.gif)
Example 3: File Upload in Tornado
app.py :This Tornado script sets up a file upload server with a single "/upload" route. The `UploadHandler` class handles GET requests by rendering an HTML upload form and processes POST requests by saving uploaded files to a 'uploads' directory. The server runs on port 8888.
Python3
import tornado.ioloop
import tornado.web
class UploadHandler(tornado.web.RequestHandler):
def get(self):
self.render("upload.html")
def post(self):
file = self.request.files['file'][0]
filename = file['filename']
with open(f"uploads/{filename}", 'wb') as f:
f.write(file['body'])
self.write(f"File '{filename}' uploaded successfully!")
def make_app():
return tornado.web.Application([(r"/upload", UploadHandler)])
if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
upload.html : This HTML document creates a simple file upload form. It includes a title, a file input field within a form, and a submit button. The form is set to submit data to the "/upload" endpoint using the POST method, and the "enctype" attribute is set to "multipart/form-data" to handle file uploads.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Upload</title>
</head>
<body>
<h1>File Upload</h1>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit">Upload</button>
</form>
</body>
</html>
Run the Server
run the tornado server using below command
python script_name.py
Output:
Conclusion
Tornado's simplicity, performance, and asynchronous capabilities make it an excellent choice for developing modern web applications. Whether you are building a simple web service or a real-time application, Tornado's flexibility and scalability can meet your requirements. With its easy-to-understand syntax and powerful features, Tornado remains a popular choice among developers for creating efficient and responsive web applications in Python.
Similar Reads
Creating a Proxy Webserver in Python | Set 1
Socket programming in python is very user friendly as compared to c. The programmer need not worry about minute details regarding sockets. In python, the user has more chance of focusing on the application layer rather than the network layer. In this tutorial we would be developing a simple multi-th
5 min read
Python script to monitor website changes
In this article, we are going to discuss how to create a python script to monitor website changes. You can code a program to monitor a website and it will notify you if there are any changes. This program has many useful scenarios for example if your school website has updated something you will com
3 min read
How to Scrape Multiple Pages of a Website Using Python?
Web Scraping is a method of extracting useful data from a website using computer programs without having to manually do it. This data can then be exported and categorically organized for various purposes. Some common places where Web Scraping finds its use are Market research & Analysis Websites
6 min read
Python Script to Open a Web Browser
In this article we will be discussing some of the methods that can be used to open a web browser (of our choice) and visit the URL we specified, using python scripts. In the Python package, we have a module named webbrowser, which includes a lot of methods that we can use to open the required URL in
4 min read
How to write a simple Flask API for hello world?
Prerequisites: Introduction to REST API REST stands for Representational State Transfer and is an architectural style used in modern web development. It defines a set of rules/constraints for a web application to send and receive data. In this article, we are going to learn how to create a simple RE
3 min read
Python Web Scraping Tutorial
In todayâs digital world, data is the key to unlocking valuable insights, and much of this data is available on the web. But how do you gather large amounts of data from websites efficiently? Thatâs where Python web scraping comes in.Web scraping, the process of extracting data from websites, has em
12 min read
Python | Launch a Web Browser using webbrowser module
In Python, webbrowser module is a convenient web browser controller. It provides a high-level interface that allows displaying Web-based documents to users. webbrowser can also be used as a CLI tool. It accepts a URL as the argument with the following optional parameters: -n opens the URL in a new b
2 min read
How to Scrape Websites with Beautifulsoup and Python ?
Have you ever wondered how much data is created on the internet every day, and what if you want to work with those data? Unfortunately, this data is not properly organized like some CSV or JSON file but fortunately, we can use web scraping to scrape the data from the internet and can use it accordin
10 min read
Upload files in Python
In this article, we will be looking into the process of file uploading in Python using cgi environment. One often comes across various web applications in which the client or the users is required to upload data in the form of a file(eg. image file, an audio file, text file, etc). There are two aspe
3 min read
Weather app using Django | Python
In this tutorial, we will learn how to create a Weather app that uses Django as backend. Django provides a Python Web framework based web framework that allows rapid development and clean, pragmatic design. Basic Setup - Change directory to weather â cd weather Start the server - python manage.py ru
2 min read