默认路由规则
代码
由下述代码可知,路由规则都在放在 tornado.web.Application 中,强迫症的我看着不舒服不说,而且如果有多级路由的话就很难搞了,比如说用户模块、不同视图模块等等,前一级路由是固定的,后面是变动的,比如说 /user/add 、/user/delete、/user/update,类似这种的,如果数量多了,某一天user要变成users了,一个个改费时费力,看着还不优雅
import tornado.web
import tornado.ioloop
import tornado.httpserver
from APISets.weatherAPI import *import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
handler = logging.FileHandler("./logs/log.txt")
handler.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)class MainHandler(tornado.web.RequestHandler):"""主路由处理类"""@tornado.web.asynchronousdef get(self, *args, **kwargs):"""对应HTTP的请求方式"""try:print('----------开始进入程序-------------')logger.info("[Request]:" + self.request.query)data = search_api(self)# self.write(data)self.finish(data)except Exception as e:logger.error("[Response]:" + str(e))class IndexHandler(tornado.web.RequestHandler):def get(self):self.write("node health check success!")application = tornado.web.Application([(r'/checkinfo/', MainHandler),(r'/index/', IndexHandler)
])if __name__ == '__main__':server = tornado.httpserver.HTTPServer(application)server.listen(8000)tornado.ioloop.IOLoop.current().start()
方案
根据之前写gin框架项目得到的灵感,将路由单独拎出来,通过组装列表来得到各个分组的路由
层级
server.py
import tornado.web
import tornado.ioloop
import tornado.httpserver
from route import routerapplication = tornado.web.Application(router.InitRoute()
)if __name__ == '__main__':server = tornado.httpserver.HTTPServer(application)server.listen(8000)tornado.ioloop.IOLoop.current().start()
router.py
from handler.user.user_handler import IndexHandlerrouter = list()user_r = "/user/" # 用户模块def user_router():"""用户模块路由:return:"""print("加载用户模块路由")r = [(r'', IndexHandler),]user_router = [(user_r + _[0], _[1]) for _ in r]print('user_router = ', user_router)return user_routerdef InitRoute():"""初始化路由:return:"""print('初始化路由')router.extend(user_router())return router
user_handler.py
import tornado.webclass IndexHandler(tornado.web.RequestHandler):def get(self):self.finish({'code': 200, 'msg': "成功"})