tornado自定义实现django include方法
- 自定义URLmethod模块
-
1 from Custom.errors import * 2 3 4 def include(base_url, expand_url): 5 # base_url必须是字符串类型 6 if not isinstance(base_url, str): 7 raise TypeError("base_url must be String type, but {} is not".format(str(base_url))) 8 9 # 必须在拓展的urls里面有一个urlpatterns的对象,如果没有就会引发AttributeError 10 getattr(expand_url, 'urlpatterns') 11 12 if not isinstance(expand_url.urlpatterns, (list, tuple)): 13 raise UrlError( 14 "expand_url.urlpatterns must be a list or tuple, but {} is not".format(str(expand_url.urlpatterns))) 15 16 urlpatterns = expand_url.urlpatterns 17 18 19 new_urlpatterns = [] 20 21 for url in urlpatterns: 22 23 items = [] 24 new_base_url = base_url + url[0] # 将原始的url和拓展的url拼接 25 items.append(new_base_url) 26 items.append(url[1]) 27 new_urlpatterns.append(tuple(items)) 28 29 return new_urlpatterns 30 31 32 def extend(*args): 33 # 将所有的include元素拓展成新的列表 34 urlpatterns = [] 35 for urlpattern in args: 36 if isinstance(urlpatterns, list): 37 urlpatterns.extend(urlpattern) 38 else: 39 raise UrlError 40 return urlpatterns
- 自定方法的使用
-
1 from tornado.web import Application 2 from tornado.ioloop import IOLoop 3 from tornado.httpserver import HTTPServer 4 from tornado.options import options, define 5 from Custom.URL_method import include, extend 6 from Robot import urls 7 8 9 define('port', default=80, type=int) 10 11 settings = { 12 'template_path': 'templates', 13 'static_path': 'static', 14 'debug': True 15 } 16 17 18 urlpatterns = extend( 19 include("", urls), 20 include(r'/qrcode', urls), 21 ) 22 23 24 25 26 27 28 app = Application(handlers=urlpatterns, **settings) 29 30 if __name__ == '__main__': 31 options.parse_command_line() 32 http = HTTPServer(app) 33 http.listen(options.port) 34 IOLoop.current().start()
- 自定义url模块
-
1 from . import views 2 3 4 urlpatterns = [ 5 (r'/index', views.IndexHandler), 6 (r'/test', views.TestHandler) 7 ]
- views模块
-
1 from tornado.web import RequestHandler 2 3 4 5 class IndexHandler(RequestHandler): 6 def get(self): 7 self.write("hello") 8 9 10 class TestHandler(RequestHandler): 11 def get(self): 12 self.write("test page")
- 效果展示