Tornado Web App with Random Number Generator

  • Share this:

Code introduction


This function creates a simple web application based on Tornado that can handle GET requests and return a random number between 1 and 100.


Technology Stack : Tornado, Python's standard library (random, ioloop, web.RequestHandler)

Code Type : Web Application

Code Difficulty : Intermediate


                
                    
import tornado.ioloop
import tornado.web
import random

def random_tornado_function():
    # Function to handle GET requests
    class MainHandler(tornado.web.RequestHandler):
        def get(self):
            # Generate a random number between 1 and 100
            self.write(f"Your random number is: {random.randint(1, 100)}")

    # Define the application
    application = tornado.web.Application([
        (r"/random", MainHandler),
    ])

    # Start the server
    def start_server():
        application.listen(8888)
        tornado.ioloop.IOLoop.current().start()

    return start_server