Sorry if this question seems basic, but I don't know how to google for what I want, so some explanation is required.
I am using tornado for my server/routing. Here is what I am attempting to do.
http = tornado.web.Application([
(r"/myroute/*", request_handlers.MyHandler, {}),
(r"/", request_handlers.defaultHandler, {}),
], **settings)
http.listen(port)
So to explain this, whenever a route beginning with "/myroute/" is called, whatever is immediately after the 2nd slash will be interpreted as the required 2nd portion of the path. This value can be empty string.
Some example of paths that I would need to be able to parse...
"/myroute/?var1=foo&var2=bar" ## the required portion is empty string
"/myroute/something?var1=foo" ## the required portion is "something"
"/myroute/something" ## same, without options
Now in my request handler, I am able to access my options pretty easily.
class MyHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
var1 = self.get_argument('var1')
print var1 ## 'foo'
var2 = self.get_argument('var2')
print var2 ## 'bar'
Basically, several questions.
1) However, how would I also access the "something" portion of the path, if we are sticking with my example?
2) Is there better terminology for what I am looking for? I have no doubt this is googleable if I only knew what to search for.
You can specify route with matches (regex) when you add handler to Application:
import tornado.httpserver
import tornado.ioloop
import tornado.web
class SomeHandler(tornado.web.RequestHandler):
def get(self, matched_part=None):
# if route won't match we set param to None
# different request params that my be handy for you
print('Host: %s' % self.request.host)
print('Entire uri: %s' % self.request.uri)
print('Uri path: %s' % self.request.path)
print('Query path w/o ?: %s' % self.request.query)
if matched_part is None:
print('Nothing matched')
else:
print('Matched part %s' % matched_part)
if __name__ == "__main__":
application = tornado.web.Application([
# match everything, but query part, after /myroute/ e.g.
# /myroute/ => None
# /myroute/test => test
# /myroute/test/aaa => test/aaa
# /myroute/test?ss=324 => test
("^\/myroute\/(.+)$", SomeHandler),
("/.*", SomeHandler),
])
http_server = tornado.httpserver.HTTPServer(application)
http_server.listen(8888)
tornado.ioloop.IOLoop.current().start()
Tornado gives you access to the path with self.request.path
. You can then split it up into the path components.
Let's say your path is /myroute/something
.
class MyHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
components = [x for x in self.request.path.split("/") if x]
# results in ['myroute', 'something']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.