Reputation: 139
I need to set up a project which contains HTML, CSS, and JS files. Currently, my structure is:
project/:
But When I run app.py i.e
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
# self.write("Hello, world")
self.render("/full/path/to/file.html")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8050)
tornado.ioloop.IOLoop.current().start()
I get this:
WARNING:tornado.access:404 GET /static/style.css (127.0.0.1) WARNING:tornado.access:404 GET /static/scriptfile.js (127.0.0.1)
I'm not sure what am I doing wrong. I even changed the relative path to full paths of the JS and CSS files.
Upvotes: 0
Views: 758
Reputation: 8673
Tornado Project Structure :
project
├── app.py
├── common
│ ├── db_manip.py
│ └── utils.py
├── handlers
│ ├── base_handler.py
│ ├── news_handlers.py
│ └── user_handlers.py
├── static
│ ├── favicon.ico
│ ├── images
│ │ ├── favicon.ico
│ │ └── logo1.png
│ └── index.js
├── templates
│ ├── index.html
│ ├── login.html
│ ├── main.html
│ ├── profile.html
│ ├── signin.html
│ └── sources.html
└── requirements.txt
Ok, since we have static in template folders in the root then:
static_path
and template_path
in your settings, it is directory from which static files will be served:settings = {
"template_path": os.path.join(os.path.dirname(__file__), "templates"),
"static_path": os.path.join(os.path.dirname(__file__), "static"),
...
}
app = tornado.web.Application(settings=settings, **kwargs)
static_url
for your JS files in templates (see RequestHandler.static_url
):<script src="{{ static_url('index.js') }}" type="text/javascript"></script>
This is what a complete main
would look like:
if __name__ == '__main__':
tornado.options.parse_command_line()
settings = {
"template_path": os.path.join(os.path.dirname(__file__), "templates"),
"static_path": os.path.join(os.path.dirname(__file__), "static"),
"cookie_secret": "_GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__",
"login_url": "/login",
"db": db,
"debug": True,
"xsrf_cookies": True
}
app = tornado.web.Application(
handlers=[(r'/', MainHandler),
(r'/sources', SourceHandler),
(r'/login', LoginHandler),
(r'/signin', SigninHandler),
(r'/profile', ProfileHandler),
(r'/favicon.ico', tornado.web.StaticFileHandler, dict(path=settings['static_path'])),
],
**settings
)
http_server = tornado.httpserver.HTTPServer(app)
http_server.listen(options.port)
try:
tornado.ioloop.IOLoop.instance().start()
except KeyboardInterrupt:
print('Server has shut down.')
The same goes for css
files.
Upvotes: 2
Reputation: 96
You should add a StaticFileHandler
to your application
application = tornado.web.Application([
(r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])
and here is the documentation tornado.web.StaticFileHandler
Upvotes: 1