Flask approute 中的多个参数 [英] Multiple parameters in Flask approute

查看:42
本文介绍了Flask approute 中的多个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果URL调用中有多个参数,如何编写flask app.route?

How to write the flask app.route if I have multiple parameters in the URL call?

这是我从 AJax 调用的 URL:

Here is my URL I am calling from AJax:

http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure

我试图像这样编写我的烧瓶 app.route:

I was trying to write my flask app.route like this:

@app.route('/test/<summary,change>', methods=['GET']

但这行不通.谁能建议我如何提及 app.route?

But this is not working. Can anyone suggest me how to mention the app.route?

推荐答案

如果您确实想使用查询参数,其他答案有正确的解决方案.类似的东西:

The other answers have the correct solution if you indeed want to use query params. Something like:

@app.route('/createcm')
def createcm():
   summary  = request.args.get('summary', None)
   change  = request.args.get('change', None)

一些注意事项.如果您只需要支持 GET 请求,则无需在您的路由装饰器中包含这些方法.

A few notes. If you only need to support GET requests, no need to include the methods in your route decorator.

解释查询参数.除了?"之外的一切在您的示例中称为查询参数.Flask 将从 URL 中取出这些查询参数并将它们放入一个 ImmutableDict 中.您可以通过 request.args 访问它,可以使用密钥,即 request.args['summary'] 或使用我和其他一些评论者提到的 get 方法.这使您能够在默认值不存在的情况下为其提供默认值(例如无).这对于查询参数很常见,因为它们通常是可选的.

To explain the query params. Everything beyond the "?" in your example is called a query param. Flask will take those query params out of the URL and place them into an ImmutableDict. You can access it by request.args, either with the key, ie request.args['summary'] or with the get method I and some other commenters have mentioned. This gives you the added ability to give it a default value (such as None), in the event it is not present. This is common for query params since they are often optional.

现在,您似乎在示例中尝试了另一个选项,那就是使用路径参数.这看起来像:

Now there is another option which you seemingly were attempting to do in your example and that is to use a Path Param. This would look like:

@app.route('/createcm/<summary>/<change>')
def createcm(summary=None, change=None):
    ...

这里的网址是:http://0.0.0.0:8888/createcm/VVV/Feauure

将 VVV 和 Feauure 作为变量传递到您的函数中.

With VVV and Feauure being passed into your function as variables.

希望有所帮助.

这篇关于Flask approute 中的多个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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