Python Tornado provides a static directory

I am trying to serve a page from a static directory using the Tornado API in Python. This answer is similar to what I am trying to do , but I cannot get it to work.

My directory structure looks like this (all static files are inside a folder called web ):

directory file structure

I have a web server setup:

 class Application(tornado.web.Application): def __init__(self): handlers = [ (r'/ws', WSHandler), (r'/', IndexHandler), ] settings = { "debug": True, "static_path": os.path.join(os.path.dirname(__file__), "web") } tornado.web.Application.__init__(self, handlers, **settings) http_server = tornado.httpserver.HTTPServer(Application()) http_server.listen(8888) tornado.ioloop.IOLoop.instance().start() 

I thought this line:

 "static_path": os.path.join(os.path.dirname(__file__), "web") 

could fix the problem, but when I point to the index.html file:

 class IndexHandler(tornado.web.RequestHandler): @tornado.web.asynchronous def get(self): self.render('web/index.html') 

It serves the page as expected, but prints this error message on the console:

 WARNING:tornado.access:404 GET /css/reset.css (::1) 3.57ms WARNING:tornado.access:404 GET /js/lib/custom-marker.js (::1) 0.96ms WARNING:tornado.access:404 GET /js/map.js (::1) 2.08ms WARNING:tornado.access:404 GET /js/websocket-client.js (::1) 1.56ms WARNING:tornado.access:404 GET /css/index.css (::1) 0.89ms 

In this minimalistic example, how can I fix my problem? Where is he trying to point and cannot find the files?

Any help you could offer would be greatly appreciated!

+6
source share
2 answers

According to the documentation section Static files and aggressive file caching , prefixing your URLs “css” and “js” with “web” should solve your problem. For instance:

/css/reset.css should be /web/css/reset.css

Or just use the recommended static_url in your templates (if you use them):

 {{ static_url("css/reset.css") }} 
+4
source

Alternatively, you can specify a template for a static directory to display all the files from the specified directory while you initialize the application

 app = web.Application([ (r'/', IndexHandler), (r'/js/(.*)', web.StaticFileHandler, {'path': './static/js'}), (r'/css/(.*)', web.StaticFileHandler, {'path': './static/css'}), (r'/images/(.*)', web.StaticFileHandler, {'path': './static/images'}), ]) 

above code will display all static urls accordingly

 <script src="js/jquery-1.10.1.min.js"></script> 

will be mapped to /static/js dir,

 (r'/js/(.*)', web.StaticFileHandler, {'path': './static/js'}) 

So, all the css and images to their respective cartographers,

 (r'/css/(.*)', web.StaticFileHandler, {'path': './static/css'}), (r'/images/(.*)', web.StaticFileHandler, {'path': './static/images'}), 
+1
source

Source: https://habr.com/ru/post/980101/


All Articles