使用基本的Flask vs Flask-RESTful进行API开发 [英] Using basic Flask vs Flask-RESTful for API development

查看:242
本文介绍了使用基本的Flask vs Flask-RESTful进行API开发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将为即将到来的应用程序开发一个REST API.我决定为此使用Python Flask.但是目前,我不知道要使用哪个选项.我应该使用基本的Flask软件包还是带有Flask-RESTful扩展名的Flask.我发现两者都有优点和缺点.

I'm about to develop a REST API for our upcoming application. I have decided to use Python Flask for it. 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. I've found some advantages and disadvantages in both.

以下是在Flask和Flask-RESTful中两个API做同样事情的示例:

Below is an example of two APIs doing the same thing but in Flask and Flask-RESTful:

烧瓶版本:

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版本:

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()

使用Flask-RESTful,我无法获得单个资源来服务多个相关端点,例如GET /user/<int:id>GET /user/<string:name>GET /user/<int:id>/friends等.而且我不知道是否为简单子资源创建新类是好的做法,因为我可能会结束很多课.由于这个原因,我更倾向于仅使用Flask,因为仅定义了函数,并且可以根据需要自由定义端点.

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. 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-RESTful中为子资源创建许多类吗?还是我最好使用Flask?还是Flask-RESTful比Flask提供了一些非常好的优势?

Keeping the above in mind, is it okay to create many classes for sub-resources in Flask-RESTful? Or am I better of using Flask? Or Flask-RESTful provides some really good advantages over Flask?

推荐答案

REST是一种非常灵活的体系结构,但是在仅使用Flask的方法中有几点值得考虑,Flask-RESTful鼓励您远离:

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:

  1. 按照惯例,单个资源(例如/users/1234)上的GET是通过该资源的唯一标识符来实现的.不能保证用户名是唯一的,因此将其用作URI中的标识符(例如/users/joe)会很冒险.

  1. By convention, a GET on a single resource (e.g. /users/1234) is by a unique identifier for the resource. 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 (e.g. /users/joe).

当您访问集合中的用户时,最好始终使用复数名词(而不是像Flask示例中所示的/user/...).

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/...).

在创建和使用POST时,除非客户端指定ID(在这种情况下,它必须能够保证唯一性,所以几乎唯一的有效ID是UUID),您可以仅发布到集合URI(例如/users/).

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 (e.g. /users/).

这两种方法都可以使用,但是使用Flask-RESTful,您会发现,遵循这些准则,您的课程将更加紧密地匹配您的资源,并且您不会看到所描述的课程的泛滥.

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.

https://上展示了一个非常相似的用例flask-restful.readthedocs.io/zh-CN/latest/quickstart.html#full-example .

这篇关于使用基本的Flask vs Flask-RESTful进行API开发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆