Reputation: 4859
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:
What's wrong with my project?
Upvotes: 2
Views: 1668
Reputation: 310099
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...)
Upvotes: 3
Reputation: 102902
The curly braces { }
you're using mean you're trying to define either a dictionary or a set. I assume url_patterns
, like its counterpart in Django, is a tuple, so you'll need to use parentheses ( )
instead:
url_patterns = (
(r'/', Index),
)
Upvotes: 3