Search code examples
pythontornado

Tornado reverse_url()


I'm trying to use reverse_url() in tornado and as far as I could understand to use the reverse url I need to add a name to the urls list (just like Django) but from some reason I get Invalid syntax when I'm trying to run the server:

This is my URLS list:

urls = [
    (r"/", IndexHandler, name="home"),
]

and this is my html:

<a class="navbar-brand navbar-right" href="{{reverse_url('home')}}">

and this is the traceback:

Traceback (most recent call last):
File "tornado_server.py", line 4, in <module>
  from urls import urls
File "C:\Users\elong\Desktop\reblaze\4. ReactJS\react_tornado\urls.py", line 4
  (r"/", IndexHandler, name="home"),
                         ^
SyntaxError: invalid syntax

Any ideas what am I doing wrong?


Solution

  • To name the urls it's not enough just to pass a list of tuples, instead you need full URLSpec objects -- see http://www.tornadoweb.org/en/stable/web.html#tornado.web.URLSpec

    In your particular example, you can easily use the helper tornado.web.url function:

    from tornado.web import url
    
    urls = [
        url(r"/", IndexHandler, name="home"),
    ]