Skip to main content

Building a CRUD application with Tornado

Introduction

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. It's known for its high performance and ability to handle multiple concurrent connections. Today, we'll be using it to build a simple CRUD application.

Prerequisites

For this tutorial, you'll need a basic understanding of Python and a local installation of Python 3. Also, you'll need Tornado installed. If you don't have it yet, you can install it with pip:

pip install tornado

Setting Up

First, let's set up a new Tornado web application. Start by creating a new Python file, app.py, and import the necessary modules:

import tornado.ioloop
import tornado.web

Creating Handlers

In Tornado, a handler is a class that processes HTTP requests. For our CRUD application, we'll need four handlers: one for each operation.

The Read Handler

class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")

Here, we've added a get method to our handler. When a GET request is made to the server, this method will be called.

Setting Up Routing

Routing in Tornado involves mapping a URL to a RequestHandler. Let's add a route that maps the URL "/" to our MainHandler:

def make_app():
return tornado.web.Application([
(r"/", MainHandler),
])

if __name__ == "__main__":
app = make_app()
app.listen(8888)
tornado.ioloop.IOLoop.current().start()

Adding More Handlers

To complete our CRUD application, we need to add more handlers. Let's add handlers for creating, updating, and deleting items. For simplicity, we'll use an in-memory list to store our items:

class ItemHandler(tornado.web.RequestHandler):
items = []

def get(self):
self.write({'items': self.items})

def post(self):
new_item = self.get_argument('item')
self.items.append(new_item)
self.write({'items': self.items})

def put(self):
index = int(self.get_argument('index'))
new_value = self.get_argument('value')
self.items[index] = new_value
self.write({'items': self.items})

def delete(self):
index = int(self.get_argument('index'))
del self.items[index]
self.write({'items': self.items})

And let's update our routing to include the new handler:

def make_app():
return tornado.web.Application([
(r"/", MainHandler),
(r"/items", ItemHandler),
])

That's it! You now have a basic CRUD application with Tornado. To run it, just execute the app.py file:

python app.py

Then, in your browser, navigate to http://localhost:8888/items to see your application in action.

Remember, this is just a basic example. In a real-world application, you would likely use a database to store your items, and you would need to add error handling and validation to ensure that only valid requests are processed.


Be sure to continue learning and experimenting with Tornado. Good luck!