2025年7月17日 11:41:33 星期四

tornado:构造一个分级路由

前言

在tornado中,并没有django那样NB的设计,很多东西要我们自己动手。比如django中司空见惯的分级路由。

构建

url_routers.py

提供两个函数用来做处理,代码:

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. from importlib import import_module
  4. def include(module):
  5. res = import_module(module)
  6. urls = getattr(res, 'urls')
  7. return urls
  8. def url_wrapper(urls):
  9. wrapper_list = []
  10. for url in urls:
  11. path, handles = url
  12. if isinstance(handles, (tuple, list)):
  13. for handle in handles:
  14. pattern, handle_class = handle
  15. wrap = ('{0}{1}'.format(path, pattern), handle_class)
  16. wrapper_list.append(wrap)
  17. else:
  18. wrapper_list.append((path, handles))
  19. print(wrapper_list)
  20. return wrapper_list

项目文件

controllers/test/urls.py

  1. from __future__ import unicode_literals
  2. from index import IndexHandler, Reverse
  3. urls = [
  4. (r'hello/(\w+)', IndexHandler),
  5. (r'reverse/(\w+)', Reverse),
  6. ]



controllers/test/index.py

  1. import tornado.web
  2. class IndexHandler(tornado.web.RequestHandler):
  3. def get(self, name):
  4. greeting = self.get_argument('greeting', 'Hello')
  5. self.write(greeting + '{}, friendly user!'.format(name))
  6. class Reverse(tornado.web.RequestHandler):
  7. def get(self, input_str):
  8. self.write(input_str[::-1])

最后,run.py启动项目

在这个项目中,其实只是用两个函数巧妙的拆分了urls路由。让代码帮我们拼接所有的urls。

  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import tornado.httpserver
  4. import tornado.ioloop
  5. import tornado.web
  6. from url_router import include, url_wrapper
  7. from controllers.test_hello.index import IndexHandler
  8. from tornado.options import define, options
  9. define("port", default=8000, help="run on the given port", type=int)
  10. application = tornado.web.Application(url_wrapper([
  11. (r"/(\w+)", IndexHandler),
  12. (r"/test/", include('controllers.test_hello.urls')),
  13. ]))
  14. if __name__ == "__main__":
  15. http_server = tornado.httpserver.HTTPServer(application)
  16. http_server.listen(options.port)
  17. tornado.ioloop.IOLoop.instance().start()

来自 大脸猪 写于 2017-04-21 19:21 -- 更新于2020-10-19 13:06 -- 1 条评论

1条评论

字体
字号


评论:

● 来自 movingheart000@gmail.com 写于 2019-08-09 16:37 回复

不错,值得借鉴!