【问题标题】:Flask: same endpoints of routesFlask:路由的相同端点
【发布时间】:2019-01-02 21:46:58
【问题描述】:

我正在开发一个 Flask API,我有这两个端点:

  • /length
  • /length?morethan={value}

如何将它们分开?它们具有相同的开头(在“?”之前),因此在路由时我必须引用相同的端点。

@app.route('/length', methods=['GET'])
def func1():
    //code

@app.route('/length', methods=['GET'])
def func2():
    value = request.args.get('morethan')
    //code

此代码适用于我的 API 的第二个版本(如果我写 /length?morethan=3,我会得到我想要的),但对于第一个,我只会得到一个空列表,它不会显示我的数据库内容。

【问题讨论】:

  • 是否有任何特殊原因需要拆分端点?我希望将这些视为单个端点,也许在没有提供参数时会提前返回。
  • 为什么不在 'value = request.args.get('morethan')' 之后添加条件?例如' if value: ... else: ...
  • 我应该把条件放在哪里?条件应该是什么?

标签: python flask


【解决方案1】:

找到解决方案。感谢评论的人。

value = request.args.get('morethan')
if value is not None:
    //code for /tweets?morethan={value}
else:
    //code for /tweets

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 2019-05-23
    相关资源
    最近更新 更多