Search code examples
pythontornado

Syntax error in when trying to run a tornado main.py


This is my simple tornado project main.py file:

import os
import os.path
import tornado.ioloop
import tornado.web
import tornado.httpserver
import tornado.options
from tornado.options import options


class Index(tornado.web.RequestHandler):

    def get(self, *args, **kwargs):
        self.write('Hello')

url_patterns = {
    (r'/', Index),
}

if __name__ == "__main__":
    tornado.options.parse_command_line()
    app = tornado.web.Application(
        url_patterns,debug=True,
        cookie_secret="*****",
        xsrf_cookies= False,
        template_path=os.path.join(os.path.dirname(__file__), "templates"),
        static_path= os.path.join(os.path.dirname(__file__), "static"),

    )

    http_server = tornado.httpserver.HTTPServer(app)
    http_server.listen(8080)
    tornado.ioloop.IOLoop.instance().start()

When I want to run this file an error says that:

File "main.py", line 16
    (r'/', Index),
                 ^
SyntaxError: invalid syntax

I want to run this on centos 6 and python 2.7.8. This is a picture of my error:

enter image description here

What's wrong with my project?


Solution

  • I'm guessing you're on python2.6 as everything seems to be valid syntax for python2.7. On python2.7,

    url_patterns = {
        (r'/', Index),
    }
    

    will try to construct a set with a single member which is a 2-tuple. However, it will fail with a TypeError if Index isn't hashable. Set literals didn't exist until python2.7 though, so for earlier python versions, your code will throw a SyntaxError.

    Generally though, in my experience (with webapp2), the order of your handlers matters -- So you're better off using an ordered iterable rather than a set. Possibly a tuple or a list. e.g.:

    url_patterns = [
        (r'/', Index),
    ]
    

    And obviously if tornado.web.Application requires one or the other, use that ;-) (The docs show a list being used, so that's probably safe...)