Turn from: Http://my.oschina.net/jiemachina/blog/204878tornado (ii)-–handler URL regular Handler URL regular match, Get/post1. Simple
application = tornado.web.Application([ (r‘/‘, MainHandler)
2. With parameters
class ProfileHandler(RequestHandler): def initialize(self, database): self.database = database def get(self, username): print username app = Application([ (r‘/user/(.*)‘, ProfileHandler, dict(database=database)), ])
This code comes to Tornado.web.RequestHandler's initialize comment, which (.*) is used to match the parameters in the Get method, such as: The first (.*) match username ; If you want get to have multiple arguments: get(self, username, password) ; Then the configuration r‘/user/(.*)/(.*)‘ can be the (.*) value of the second regular matching group; Let's cite a few examples:
As follows:
url: localhost:9002/user/hander_parse: (r‘/user/‘, ProfileHandler)get(self):-------------------------------------------url:localhost:9002/user/username/passwordhander_parse: (r‘/user/(.*)/(.*)‘, ProfileHandler)#这里主要正则匹配url,get(self, username, password): print username, ‘ ‘, password-------------------------------------------url:localhost:9002/user/username_passwordhander_parse: (r‘/user/(.*)_(.*)‘, ProfileHandler)get(self, username, password): print username, ‘ ‘, password
If you like to pass a lot of parameters in the URL, so the Get method does not have a lot of parameters??? So there's an easy way
get(self, *args): print str(args)
So the above said so much nonsense, after all use this bar;
3. Understanding the process of regular matching
Debug in application, you can view the source code of tornado.web.py.
From:
(r‘/profile/(.*)‘, ProfileHandler, dict(database="mysql"))
--Convert into
URLSpec(r‘/profile/(.*)‘, ProfileHandler, dict(database="mysql"))# 会把所有的URLSpec放到self.handlers 中
Then the RequestHandler subclasses will
-
Call Requesthandler.initialize (**kwargs)
So when there is Dict (database=database)
(r‘/user/(.*)‘, ProfileHandler, dict(database=database)),
, you can have:
def initialize(self, database): self.database = database
Tornado-–handler URL Regular