3

The title question I met is when I runned a hello-world example with tornado like this:

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web

from tornado.options import define, options
define("port", default=9999, help="run on the given port", type=int)

class IndexHandler(tornado.web.RequestHandler):
    def get(self):
        greeting = self.get_argument('greeting', 'Hello')
        self.write(greeting + ', friendly user!')

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(handlers=[(r"/hello", IndexHandler)])
    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(options.port)
    tornado.ioloop.IOLoop.instance().start()

And I runned this code and runned the command like this: curl http://localhost:9999/hello, it got 200 HTTP status.

But when I runned the command closing the path with slash: curl http://localhost:9999/hello/,it got 404 HTTP status.

I know the problem in code maybe is this line:

app =  tornado.web.Application(handlers=[(r"/hello", IndexHandler)])

So I want to know if there is an easy way to fix it with http://localhost:9999/hello and http://localhost:9999/hello/ both accessed.

And I also really want to understand the difference in url path with the path closed with slash(/) or not, like the above http://localhost:9999/hello and http://localhost:9999/hello/ or sometimes when we put the file.

Tinple
  • 191
  • 1
  • 8

1 Answers1

4
  • Route path is a regex, so you can set it to r'/hello/?', and it will accept both trailing slash and no slash.
  • About a URL style, there's another question on SO which I just found with a search, sorted by votes: When should I use a trailing slash in my URL?
Community
  • 1
  • 1
Victor Sergienko
  • 13,115
  • 3
  • 57
  • 91
  • 1
    Note that while this is valid regex, and will do what you expect in regards to pattern matching, it WILL mess up URL reversing (the output of `reverse_url()` will include the trailing `?`). I found this answer while Googling to solve this reverse URL problem. :) – kitti Aug 17 '16 at 20:09