【发布时间】:2015-03-17 21:50:26
【问题描述】:
Flask 教程网站here 说,要创建一个 RESTful API,您需要编写扩展 restful.Resource 的类,然后通过以下方式将它们添加到 API:
app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
但是,我看过很多教程,它们都只是使用带有 @app.route('/path') 装饰器的函数,我更习惯于在 Flask 应用程序中看到这些函数。例如here,他们有:
@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
return jsonify({'tasks': tasks})
还有here:
@app.route('/')
def api_root():
return 'Welcome'
使用restful.Resource 类与仅使用修饰函数(如果有)有什么区别?如果没有差异,我应该按照惯例做什么来创建 RESTful API?
【问题讨论】:
-
restful.Resource源自 Flask 扩展。app.route是基于纯 Flask 的解决方案(您可以通过这种方式非常轻松地实现简单的 API)。添加 simple API exceptions 之类的基本解决方案后,对于简单的 API 来说已经足够了。 -
@ujvl Flask Tuto 的链接已失效。