我尝试使用带有通用URL路由的Flask为RESTFull CRUD服务实现单个入口点。 拥有像' / api / book / 1'这样的网址应加载我的BookController(app / controllers / book.py)并调用read()方法。 我希望实现的示例代码,但实际上它无法加载我的模块:
@app.route('/api/<controller>/<id>')
@app.route('/api/<controller>')
def api(controller, id = None):
try:
if request.method == 'GET':
if id is None:
action = 'list'
else:
action = 'read'
elif request.method == 'POST':
action = 'create'
elif request.method == 'PUT':
action = 'update'
elif request.method == 'DELETE':
action = 'delete'
else:
page_not_found()
module = importlib.import_module('app.controllers.' + controller)
ctrl = getattr(module, controller.capitalize() + 'Controller')
instance = ctrl()
method = getattr(instance, action)
return method()
except ImportError as e:
page_not_found('Invalid request')
与Python和Flask相当n00b,我知道: - )
编辑:
我得到一个&#34; ImportError:无法导入名称&#39; Book&#39; &#34;
编辑2:
在app / controllers /里面我有两个文件:
初始化的.py
# __init__.py
__all__ = ["book"]
book.py
from app.models import Book
import json
class BookController():
data = [Book('Awesome Title', '', 'fa-bar').toJson(), Book('Once upon a time', 'foo', 'fa-paper').toJson()]
def list(self):
return json.dumps(self.data)
编辑3:
这可能是路由API请求的好方法吗?