|
Tornado is a Python web framework and a library for async networks. It is meant for non-blocking, highly effective apps. Tornado has become popular because it can handle large numbers of simultaneous connections easily. In this article, we will explain Tornado HTTP servers and clients. What are HTTP servers and clients?
Tornado- HTTP servers and clients ExamplesBelow, are the examples of Tornado- HTTP servers and clients in Python. Tornado – HTTP Server ExampleIn this example, below code sets up a Tornado web server with two handlers: MainHandler for root URL (“/”) returns “Hello, Tornado!” as text, and ApiHandler for “/api” returns a JSON response {“message”: “Hello, Tornado!”, “status”: “success”}. The server listens on port 8001 and starts running.
Output: tornado server Tornado – HTTP Client ExampleIn this example of a Tornado’s HTTP client that can make an asynchronous HTTP request. The function fetches data from a URL asynchronously and prints the response body. To run asynchronous code synchronously within the Tornado event loop, one can use run_sync method.
Output : b'{"message": "Hello, Tornado!", "status": "success"}' Another ExampleHere, we will create a form submission and successfully message flashing web app using Tornado – HTTP servers and clients. File Strcuture : myServer.py : below, code sets up a Tornado web server with a single request handler, MainHandler. When a GET request is made to the root URL (“/”), it renders a form HTML page. When a POST request is made, it retrieves the submitted form data (name and email), validates if both are provided, and responds accordingly.
myClient.py : Below, code imports the requests library to send an HTTP POST request to “http://localhost:8003” with JSON data containing a name and email. It then prints the response text returned from the server after the POST request.
Creating GUItemplates/form.html : Below HTML code defines a simple form with fields for entering a name and an email address. When submitted, the form sends a POST request to the root URL (“/”) of a server.
Output: ![]() Output demo ConclusionIn conclusion, Tornado provides a powerful solution for developing high-performance web applications and APIs. It has an asynchronous framework and simple request handling that allow developers to build scalable servers with high efficiency capable of handling many simultaneous connections. Moreover, Tornado can also easily work together with JSON serialization; hence creating a platform where data is communicated swiftly between clients and servers. |
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 14 |