Python-me.org

Python Tornado, A Quick-Start Guide

What is Tornado?

Python tornado

Tornado is a Python web framework and asynchronous networking library. It’s most poular use is probably for web applications that require scalability, but it can be used for many other applications.

The key features of the library are supposed to be:


It is designed to be scalable, simple, and lightweight. Like all Python frameworks, Tornado is 100% event driven. Its in-memory cache and use of non-blocking sockets makes it ideal for applications that spend most of their time waiting on network requests or generating output.

You can easily Deploy a Python Web App online

Why use Tornado?

I use tornado a lot. And sometimes I get questions and people who asks me: “Why tornado? why Python? Why not Go?”. Well, the questions are easy to answer, I will try to answer them here.

There are two main reasons to use tornado for your next web application:

Tornado doesn’t get in your way

Tornado provides a set of libraries that make it easy to do the hard parts of building a web application. Since tornado provides only the libraries you need, your code remains clean. You don’t have to fight with a large framework as you would with other web development frameworks.

Ease to scale

By using non-blocking network I/O, Tornado can scale to tens of thousands of open connections, making it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each user.

Tornado is one of the most prominent libraries in Python for developers who build high-performance, low latency web applications.

If you are a Python developer and you haven’t heard of Tornado, then you are probably living under a rock (don’t worry, it’s cool). And there are more reasons why you should consider using Tornado instead of other frameworks, especially if your application has high demands on performance and scalability.

Tornado Example

Hello World

In python, it is very common to use the simple “hello world” example to learn how to code and create a program.

Below is an example of the simplest of web applications, hello world written in Python and using the Tornado web server.

Although the above code may look complicated at first, it actually is very simple. It makes use of the tornado module and tornado templates to create a program that when called will output a simple “hello world” message.

import tornado.ioloop
import tornado.web

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

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

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

It starts a web server at port 8888. This is accessible at your web browser using the url http://localhost:8888

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

The application is defined in the function make_app. This contains all URL routes. When you type a URL into your browser, the server then knows what web page to return to you. In Python, this web server is called the web framework. In this case it returns the get() function in the MainHandler class for the / route.

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

The function below is called whenever the / route is opened. It returns the text “Hello, world” to the browser or whatever you change it into.

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

Python tornado server running

API with Tornado

The API, or Application Programming Interface is how you communicate with an application or program. It’s a technical way to get data from another source directly in your app. The basics of APIs is how to make requests and get responses from other servers. An API is like a point of connection between two things.

The program below is a simple HTTP API with one end point called /. Whenever you open that endpoint, it returns a message in JSON format.

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

The JSON Data in this example:

{'message': 'hello world'}

The complete example:

# Load tornado module
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop

# URL request handler
class HelloHandler(RequestHandler):
  def get(self):
    self.write({'message': 'hello world'})

# define end points
def make_app():
  urls = [("/", HelloHandler)]
  return Application(urls)

# Start server  
if __name__ == '__main__':
    app = make_app()
    app.listen(3000)
    IOLoop.instance().start()

Run it in the terminal with the command:

pipenv run python app.py

It starts a web server on your computer on port 3000. The function app.listen() defines the port.

Open your web browser and type the url http://localhost:3000/ which has the end point /. It should output the json data.

Why Python

Why Python for web development?

Why Python for web development?

You can easily deploy your web app online with Python

Why Python?


Python is a general-purpose programming language, but it’s often referred to as a “scripting language.” Students coming from a Java, C++, or C# background are particularly skeptical. They’ve been taught to build large-scale industrial software. They’re used to writing code that has to run on hundreds of various configurations and thus needs to be perfect.

Python code, however, tends to be less error-prone because it is very short and simple (in fact, it’s often said that the average line of Python code has just five words ). This means that coding in Python is just easier than in other languages.

But what about web development? Isn’t that different? Shouldn’t I be writing object-oriented code?

No! For web development you should write mostly small chunks of procedural code, not object-oriented ones.

What is a Web Framework?

A web framework is a set of tools that helps you develop web applications more quickly. They ease the developer’s burden by providing a set of libraries that handle common tasks like data persistence, authentication, etc.

The Python Web Framework landscape is quite varied and there are many different tools available to developers today.

Web development frameworks provide a standard set of tools for quickly creating web apps, including everything from database support to user authentication.

In this way, a framework presents all the building blocks which allow you to create your own applications.

So here we have: Tornado, Django, Flask, Pyramid, Bottle. These are the different frameworks available to you as well as their respective libraries.

The choice of framework is a crucial decision. It is as important as the choice of platform (Ruby on Rails, Python etc.) and the choice of database (postgresql, mysql etc.).

The framework will have a profound impact on productivity and on the ease of development. It will also make a difference to performance. So, it is important to take some time to understand the different Python frameworks in detail.

These frameworks are all good tools, but there is no one-size fits all. The best Python framework for your project depends on the requirements and your team’s development experience.

Python Tornado vs Flask

Tornado is a python web framework and Flask is a python micro framework. Tornado is very well established while Flask, on the other hand, is pretty new. Both frameworks are designed for different uses. However, when it comes to the performance of these frameworks, many people wonder which one really stands out.

Flask is designed to build rapid development web applications. It relies on the Werkzeug WSGI toolkit which provides a simple and fast Python web application, which uses its own internal HTTP server for serving the application.

from flask import Flask
app = Flask(__name__)

@app.route("/")
    def hello():
        return "Hello World!"

if __name__ == "__main__":
    app.run()

Tornado is designed to build scalable real-time web applications. It relies on asynchronous programming, non-blocking sockets and a pretty fast HTTP server. It’s easy to write, runs on Windows and Linux, and has all the features you need for modern traffic handling, including fast HTTP 2 support.

Tornado vs Django

First off, I love both frameworks. They’re both fantastic, and either one would be great for a lot of applications. If you’re looking to get started with something new, I highly recommend either of them.

Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. By using non-blocking network I/O, Tornado can scale to tens of thousands of open connections, making it ideal for long polling, WebSockets, and other applications that require a long-lived connection to each user. It’s written in Python and uses a few C libraries.

While Tornado ships with its own version of a web server, it is also able to act as a WSGI server (using the wsgiref.simple_server). This means that any WSGI-compliant application can act as a web server for Tornado. For example, you could use mod_wsgi to serve Tornado applications from Apache.

For those who haven’t seen it already, Tornado is an asynchronous networking Python framework based on the event loop / libevent model. It is designed for scalability and concurrency.

django

Django is a popular web framework written in Python. It is ambitious, and most of its goals (especially simplicity) are achieved very well. It’s straightforward to get started with it, and you don’t have to think about much but your problem domain right from the start.

Undoubtly, one of the reasons why Django gets so much love - among programmers - is that it eliminates all of the boilerplate code that’s associated with frameworks such as Rails. It’s all there, pre-made, and all you have to do is to take it and run with it.

Tornado vs Node.js

As a backend developer, you have probably heard of Node.js. It has been gaining popularity lately and its use is spreading like wild fire, especially for web applications. It is advertised as a very fast server side technology that uses less memory and handles high concurrency well. Unfortunately, it does not always perform as well as advertised.

This is mostly due to the fact that Node.js was built with JavaScript in mind. Node.js is not suited for Python, a language that has its roots in C and which is often used for scientific computations (numpy). Tornado, Python web framework, outperforms Node.js when it comes to handling real time applications.

Node.js

Tornado’s biggest feature is its non-blocking, asynchronous IO. This was a revelation when it was first introduced, and it has since been copied by pretty much every major web framework. But why is asynchronous IO so important?

The secret to a scalable server is to keep the event loop full. If your event loop can’t keep up with the incoming requests, then you have several problems:

You can’t serve any async requests at all. You must respond in series, which means that you will probably drop some of the incoming requests. (This is “starvation”).

Losing one request may not sound like a big deal, but remember that each request takes some work to process - bytes to read from the socket, network round-trips to the database, etc. If you’re dealing with many thousands of requests per second, dropping each one makes a huge difference!

There is one form of input where asynchronous processing really pays off: real-time data.

Quickly, point-by-point:

While Node.js does provide non-blocking I/O, it lacks an HTTP server framework. If you’re only developing with Node, you’ll have to rely on third-party modules or build your own framework from scratch. In contrast, Python comes with Tornado which is an in-house framework developed by the Python community for developing robust and scalable production web servers.

With a focus on ease of use and simplicity, Tornado makes it easy to get started and learn. As the simplicity of the language makes it an excellent teaching tool, it also has a small learning curve which allows for quick prototyping.

Web development

Web Application Basics

What is a web browser?

A web browser is a program for accessing information on the World Wide Web. You can think of a web browser as a window into the Internet. When you point your browser to http://www.python.org you see the content on our website. Without a browser, such as WebKit, and without a connection to the internet, you wouldn’t be able to see our site.

The most popular web browsers today are Chrome, Firefox, Safari and Internet Explorer/Edge, but some other browsers are available, such as Opera.

It is hard to believe now, but when the Web was first conceived and developed in 1989 by Tim Berners Lee, there was no way for people to open a browser and just “surf” to any website they wanted to see.

What is a server?

A web server is a computer that serves your website to the guests. Each website lives on a special folder on your computer and every time someone requests this folder (for example http://www.website.com) - the server sends the contents of this folder back to that guest using Apache (or Nginx) web server software.

Almost every website in existence runs on a web server, sometimes more than one. Some websites have a single web server that serves the whole site, some web services like blogs might have one web server per user account.

With Python you can build your own server (comes by default with many web frameworks) and serve your web application. It is commonly referred to as back-end.

What is an API?

An API is a programmatic interface that allows a program to talk to other programs. APIs can be used by developers to make programs that share data or functionality. This is how apps like Twitter, Facebook and Gmail can share information with each other.

A popular way to think of an API is the “back door” of a website. Websites often have “back doors” so they can share information with programs.

While APIs have existed for decades, they’ve only recently become a core part of the web, powering everything from your Twitter feed and Gmail inbox to your Facebook newsfeed and route to the Instagram photos of your favorite singers. By creating an API, developers are able to provide a programmatic interface to resources of various kinds.

What is web sockets?

Web sockets allow two-way real time communication between the browser and a server. With this, pages can update their content instantly from the server without refreshing the page. It’s like polling, but more efficient.

Web sockets give your web browser and the web server an ongoing two-way connection, rather than the usual single request/response interaction. This is useful when you want to send continuous updates from the server to the client as it happens, without having to send a bunch of individual messages or keep the connection open continuously. You

Web sockets is an emerging web technology that allows real-time bidirectional communication between a browser and a server.

What is WSGI?

WSGI is a Python standard for web servers to talk to web applications.

A Web Server Gateway Interface (WSGI) is a standard interface between the web server and the Python web application framework. WSGI allows Python developers to design and implement web applications independent of the deployment environment.

What is HTTP?

HTTP is a protocol for transferring information between a web browser and a server. The protocol is designed for quick access to the resource on the web, such as text, graphics, sound, and video.

A HTTP stands for HyperText Transfer Protocol. HTTP is the protocol that powers the web, and in particular, the world wide web. It’s an application layer protocol designed to transfer files from one computer to another across networks and the internet.

In a nutshell, here’s how it works: when you request something from a server, the server sends you back a response. This response contains three things:

· The requested resource (the file) · The HTTP status code (e.g. 200 OK) · Any other metadata or headers that the server might need to convey

Each time you type an URL, you request something from a server.