以前用Tornado开发过不少接口,都是每个项目一个服务,规划了一下,打算写一个公共的程序,后续开发的功能只需要将程序放入指定目录即可,使用装饰器来配置路由功能
环境如下
目录结构如下
├── produce #接口文件夹
│ ├── __init__.py #包、模块导入控制
│ ├── read_pdf.py #功能代码
│ └── test.py #功能代码
└── web_pdf.py #主程序
实现方法
按照网上的教程,修改了N多次,单文件没有问题,涉及到多目录和文件就各种问题,无奈换了一种思路使用了一个tornadotools的工具
pip3 install tornadotools
导入 Route 对象,配置路由和初始化字典,tornado.web.RequestHandler 的装饰器。 Route 装饰器将所有路由存储在类别列表中。然后就可以使用 Route.routes 方法将所有路由添加到应用程序
核心代码如下
###test.py===
from tornadotools.route import Route
@Route(r'/fu')
class api(tornado.web.RequestHandler):
async def get(self):
self.write("hello fu")
@Route(r'/test', host="www\.example\.com")
class api2(tornado.web.RequestHandler):
async def get(self):
self.write("test test")
##web_pdf.py
from tornadotools.route import Route
class Application2(tornado.web.Application):
def __init__(self):
settings = dict(
static_path="static",
debug=True,
cookie_secret="61oETzKXQAxxxxxxxxxxxxxxxxxxxxxx",
login_url="/"
)
handlers = Route.routes() + [
(r"/.*", other), #默认的路由路径
]
tornado.web.Application.__init__(self, handlers, **settings)
测试
[root@localhost ~ -> ]# curl http://127.0.0.1:8888/test
test test#
[root@localhost ~ -> ]# curl http://127.0.0.1:8888/fu
hello fu#
[root@localhost ~ -> ]# curl http://127.0.0.1:8888/fddf
参数错误#
测试无误,实现了预计的目标
注意一下produce目录 下的自动加载模块的__init__.py
__init__.py
留言与评论(共有 0 条评论) “” |