How To Add Static Files And Templates Folder In Python Tornado

In this program example we will use template_path=os.path.join(os.path.dirname(__file__), “templates”)

this code to set the templates folder location

In the same way we will set the static path

static_path=os.path.join(os.path.dirname(__file__), “static”)

And we will add this in the tornado application

tornado.web.Application()

This is the full app.py where templates folder and static folder added


import tornado.web
from tornado.options import define, options, parse_command_line
import tornado.ioloop
import os
import logging


define("port", default=5000, help="port number", type=int)
define("debug", default=True, help="debug mode")

class MainHandler(tornado.web.RequestHandler):
    async def get(self):
        return self.render('index.html')

def main():
    parse_command_line()
    app = tornado.web.Application(
        [
            (r"/", MainHandler),
        ],
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path=os.path.join(os.path.dirname(__file__), "static"),
        debug=options.debug,
    )
    app.listen(options.port)
    logging.info(f"Server running on port {options.port}, debug mode: {options.debug}")
    
    logging.info(f"http://localhost:{options.port}")
    
    tornado.autoreload.start()
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()



Project structure

├── app.py
├── static
│   ├── script.js
│   └── styles.css
└── templates
    └── index.html

In the program The debug mode is true, which is must for development and detecting the performance and issues Also We have used tornado.autoreload.start()

This feature automatically restart the server and updates the changes When code changes. So it’s best for when developing and testing application.

I have create a github repository for this post. You can Get the complete code from github