Separate Flask routes for GET and POST methods

huangapple go评论51阅读模式
英文:

Separate Flask routes for GET and POST methods

问题

在Flask中定义路由时,使用单个路由同时处理多个HTTP方法并在该单个路由内使用明确的逻辑来处理不同的HTTP方法是否是更好的做法,例如:

@app.route("/api/users/", methods=['GET', 'POST'])
def users():
    if request.method == 'GET':
        ...
    elif request.method == 'POST':
        ...

还是是否应该定义多个具有特定HTTP方法的路由,从而避免在每个路由内包含明确的HTTP请求方法逻辑,例如:

@app.route("/api/users/", methods=['GET'])
def users_get():
    ...

@app.route("/api/users/", methods=['POST'])
def users_post():
    ...

另外,由于Flask默认允许所有路由上的GET HTTP方法,那么为静态资源定义额外的路由的最佳做法是什么?HTTP方法应该被明确声明,如上述代码片段中的第一个示例:

@app.route("/api/users/")
def users_static():
    ...

还是应该省略HTTP方法并因此隐含,例如:

@app.route("/api/users/")
def users_static():
    ...
英文:

When defining routes in Flask, is it better practice to use a single route defined with multiple HTTP methods, and handle the different HTTP methods with explicit logic inside this single route, e.g.

@app.route("/api/users/", methods=['GET', 'POST'])
def users():
if request.method == 'GET':
    ...
elif request.method == 'POST':
    ...

or define multiple routes with specific HTTP methods, thus avoiding any explicit HTTP request method logic inside each route, e.g.

@app.route("/api/users/", methods=['GET'])
def users_get():
    ...


@app.route("/api/users/", methods=['POST'])
def users_post():
    ...

Also, as Flask allows the GET HTTP method on all routes by default, what would be best practice for defining an additional route for a static resource? Should the HTTP method be stated explicitly, as in the first example in the preceding code snippet, or omitted and therefore implied, e.g.

@app.route("/api/users/")
def users_static():
    ...

答案1

得分: 2

如果在处理路由的HTTP方法时有很多通用代码,你可以选择第一种方式。如果没有,你可以将它们分开成不同的函数。

英文:

If there is a lot of common code between how you handle the HTTP methods for a route, you can prefer the first way. If not, you can separate them out into different functions.

huangapple
  • 本文由 发表于 2020年1月3日 18:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577212.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定