允许 Flask URL 中存在多个可选参数

所以我有一个 Flask URL,其中有 2 个单独的参数。我想运行相同的函数,或者不带参数,只使用第一个或两个参数。如果没有设置特定值,我希望未说明的参数获得值None(而不是根本不存在)。我当前的解决方案涉及使用 3 个@app.route语句,我想知道是否有一些更有效的东西我错过了。


@app.route('/URL',defaults={'Arg1':None,'Arg2':None})

@app.route('/URL/<string:Arg1>',defaults={'Arg2':None})

@app.route('/URL/<string:Arg1>/<string:Arg2>')

谢谢!


天涯尽头无女友
浏览 61回答 1
1回答

噜噜哒

在这种情况下,只需创建简单的路由并访问这些变量,如下request.args所示:@app.route('/test', methods=['GET'])def test():&nbsp; &nbsp; arg1 = request.args.get('arg1', None)&nbsp; &nbsp; arg2 = request.args.get('arg2', None)&nbsp; &nbsp; if arg1:&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; # Do something with it&nbsp; &nbsp; elif arg2:&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; # Do something with it&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; pass&nbsp; # do something when no args given&nbsp; &nbsp; return jsonify()然后在 url 中你可以这样传递:/testor/test?arg2=321or/test?arg1=123or/test?arg1=123&arg2=321
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python