简体   繁体   English

使用基本的 Flask 与 Flask-RESTful 进行 API 开发

[英]Using basic Flask vs Flask-RESTful for API development

I'm about to develop a REST API for our upcoming application.我即将为我们即将推出的应用程序开发 REST API。 I have decided to use Python Flask for it.我决定为此使用 Python Flask。 But at this point, I don't know which option to use.但在这一点上,我不知道使用哪个选项。 Should I be using the basic Flask package or Flask with Flask-RESTful extension.我应该使用基本的 Flask package 还是 Flask 和 Flask-RESTful 扩展。 I've found some advantages and disadvantages in both.我发现两者都有一些优点和缺点。

Below is an example of two APIs doing the same thing but in Flask and Flask-RESTful:下面是两个 API 做同样事情但在 Flask 和 Flask-RESTful 中的示例:

Flask version : Flask 版本

from flask import Flask, jsonify

app = Flask(__name__)

usersList = ['Aaron', 'Bianca', 'Cat', 'Danny', 'Elena']

@app.route('/users', methods=['GET'])
def users():
    return jsonify({ 'users': [user for user in usersList] })

@app.route('/user/<int:id>', methods=['GET'])
def userById(id):
    return jsonify({ 'username': usersList[id]  })

@app.route('/user/<string:name>', methods=['GET'])
def getUserByName(name):
    # Show some user information
    return "Some info"

@app.route('/user/<string:name>', methods=['POST'])
def addUserByName(name):
    usersList.append(name)
    return jsonify({ 'message': 'New user added'  })

app.run()

Flask-RESTful version : Flask-RESTful 版本

from flask import Flask
from flask_restful import Resource, Api

app = Flask(__name__)
api = Api(app)

usersList = ['Aaron', 'Bianca', 'Cat', 'Danny', 'Elena']

class UsersList(Resource):
    def get(self):
        return { 'users' : [ user for user in usersList  ] }, 200


class UserById(Resource):
    def get(self, id):
        return { 'username': usersList[id] }


class UserByName(Resource):
    def post(self, name):
        usersList.append(name)

        return { 'message': 'New user added'}


api.add_resource(UsersList, '/users')
api.add_resource(UserById, '/user/<int:id>')
api.add_resource(UserByName, '/user/<string:name>')

app.run()

Using Flask-RESTful, I cannot get a single resource to serve multiple related endpoints like GET /user/<int:id> , GET /user/<string:name> , GET /user/<int:id>/friends etc. And I don't know if creating new classes for simple sub-resources is a good practice because I'll probably end up with many classes.使用 Flask-RESTful,我无法获得单个资源来服务多个相关端点,例如GET /user/<int:id>GET /user/<string:name>GET /user/<int:id>/friends等。而且我不知道为简单的子资源创建新类是否是一种好习惯,因为我最终可能会得到很多类。 Due to this reason, I'm more inclined towards using just Flask since only functions are defined and the endpoints can be freely defined as per my needs.由于这个原因,我更倾向于只使用 Flask 因为只定义了函数并且可以根据我的需要自由定义端点。

Keeping the above in mind, is it okay to create many classes for sub-resources in Flask-RESTful?牢记以上几点,可以在 Flask-RESTful 中为子资源创建许多类吗? Or am I better of using Flask?还是我最好使用 Flask? Or Flask-RESTful provides some really good advantages over Flask?或者 Flask-RESTful 比 Flask 提供了一些非常好的优势?

REST is a pretty flexible architecture, but there's a few points worth thinking about in your approach using just Flask, which Flask-RESTful is encouraging you away from: REST 是一种非常灵活的架构,但在您仅使用 Flask 的方法中,有几点值得考虑,Flask-RESTful 鼓励您远离:

  1. By convention, a GET on a single resource (eg /users/1234) is by a unique identifier for the resource.按照惯例,对单个资源(例如 /users/1234)的 GET 是通过资源的唯一标识符。 The name of a user can't be guaranteed to be unique, so it would be risky to have it as an identifier within the URI (eg /users/joe).不能保证用户的名称是唯一的,因此将其作为 URI 中的标识符(例如 /users/joe)是有风险的。

  2. When you access users within a collection, it's better to stick with the plural noun throughout (not, as you show in your Flask example, /user/...).当您访问集合中的用户时,最好始终使用复数名词(而不是,正如您在 Flask 示例中所示,/user/...)。

  3. When you're creating and using POST, unless your client is specifying the id (in which case it has to be able to guarantee uniqueness, so pretty much the only valid id would be a UUID), you can post to just the collections URI (eg /users/).当您创建和使用 POST 时,除非您的客户端指定了 id(在这种情况下它必须能够保证唯一性,因此几乎唯一有效的 id 将是 UUID),您可以只发布到集合 URI (例如/用户/)。

Either will work, but with Flask-RESTful you'll find that when you follow those guidelines, your class matches your resources much more closely and you won't see the proliferation of classes you describe.两者都可以,但是使用 Flask-RESTful,您会发现当您遵循这些指南时,您的类与您的资源更加匹配,并且您不会看到您描述的类的激增。

A very similar use case is demonstrated at https://flask-restful.readthedocs.io/en/latest/quickstart.html#full-example . https://flask-restful.readthedocs.io/en/latest/quickstart.html#full-example演示了一个非常相似的用例。

I would recommend you to use Flask-RESTplus instead, that will give you full Swagger support.我建议您改用Flask-RESTplus ,这将为您提供全面的 Swagger 支持。

In regards of just using Flask, I would say getting the Swagger functionality is a big one to choose Flask-Restplus also.关于仅使用 Flask,我想说获得 Swagger 功能也是选择 Flask-Restplus 的一个重要因素。

Not sure why no one mentioned the fact that standard Flask is also REST-API enabled ie you really don't need to import the REST package to avail something that is missing in standard Flask package.不知道为什么没有人提到标准 Flask 也支持 REST-API 的事实,即你真的不需要导入 REST 包来利用标准 Flask 包中缺少的东西。

You are absolutely free to choose whichever you want depending upon your comfort level and any method chosen shouldn't affect your end-result functionality.您完全可以根据自己的舒适度自由选择所需的任何方法,并且选择的任何方法都不应影响最终结果的功能。

I understand that we can be inclined towards using something that is meant for a specific job but sometimes, in coding world, comfort matters regardless of how many extra lines of code you have to write.我知道我们可能倾向于使用适合特定工作的东西,但有时,在编码世界中,无论您必须编写多少额外的代码行,舒适度都很重要。

Hope this answers your query.希望这能回答您的疑问。

In my personal opinion, Flask-RESTful abuses the use of OOP, and it doesn't feel an intuitive approach for me.在我个人看来,Flask-RESTful 滥用了 OOP 的使用,对我来说感觉不是一种直观的方法。 I prefer "plain Flask" for REST API development over Flask-RESTful.我更喜欢 REST API 开发的“普通 Flask”,而不是 Flask-RESTful。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM