隨著功能越拆越細
有一天就會發現寫最多的code就是在到處import
像下面這個API的狀況
/routes/resource/
| login.py
| api1.py
| api2.py
| ....
在flask裡面就要做成
from flask import Blueprint
from flask_restful import Api
api_bp = Blueprint('api', __name__)
api = Api(api_bp)
@api_bp.route('/')
def show():
return "this is scarabaeus API"
# login
api.add_resource(Login, '/login')
# API1
api.add_resource(API1, '/api1')
# API2
api.add_resource(API2, '/api1')
# API3
api.add_resource(API3, '/api1')
# API4
api.add_resource(API4, '/api1')
...etc.
而且每個開發API的人都要記得維護route檔案
這時候就要考慮auto discover了
具體的範例如下
IGNORE_MODULES = ['__init__']
folder = os.path.dirname(os.path.abspath(__file__))
target = folder.replace('routes', 'resource')
modules = os.listdir(target)
resource_list = get_module_resource_list(modules, IGNORE_MODULES)
for module, resource_name in resource_list:
resource_class = getattr(module, resource_name)
try:
url = getattr(resource_class, 'url')
except AttributeError:
# the path will be not work as not setting url
continue
api.add_resource(resource_class, url)
Auto Discover通常會用在那種隨著時間過去
邏輯會越來越多的情境,或是專案型情境,每多一個專案就會多寫一個
就很適合Auto Discover