M07
M07

Reputation: 1131

How to handle static files handler in Tornado with several static folders?

My current routing tables is like below:

routing_table = [
        ("/api/ping", PingHandler),
        ("/css/(.*)", StaticFileHandler, {
             "path": "my-website-path/css"
        }),
        ("/js/(.*)", StaticFileHandler, {
             "path": "my-website-path/js"
        }),
        ("/fonts/(.*)", StaticFileHandler, {
             "path": "my-website-path/fonts"
        })

I would like to use only one regex to handle my static files. Something like below ?

routing_table = [
        ("/api/ping", PingHandler),
        ("/(css|js|fonts)/(.*)", StaticFileHandler, {
             "path": "my-website-path/$1"
        })

How can I do that? Thank you in advance.

Upvotes: 0

Views: 714

Answers (1)

kwarunek
kwarunek

Reputation: 12577

A RequestHandler pass all matches as a positional arguments to the http-verb function. Since the StaticFileHandler extends it and you have 2 captured groups, your code won't work as expected. So the regex needs to be changed, step by step:

  1. match entire path: /(.*)
  2. first part should be fonts, js or css: ((jss|css|fonts)/.*
  3. the inner group should not be captured - make use of ?:: ((?:jss|css|fonts)/.*

The code

routing_table = [
        ("/api/ping", PingHandler),
        ("/((?:css|js|fonts)/.*)", StaticFileHandler, {
             "path": "my-website-path"
        }

Keep in mind, that the StaitcFileHandler (as @cricket_007 mentioned)...

This handler is intended primarily for use in development and light-duty file serving; for heavy traffic it will be more efficient to use a dedicated static file server (such as nginx or Apache). We support the HTTP Accept-Ranges mechanism to return partial content (because some browsers require this functionality to be present to seek in HTML5 audio or video).

Upvotes: 3

Related Questions