Python Flask approute 中的多个参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15182696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiple parameters in in Flask approute
提问by user2058205
How to write the flask approute if I have multiple parameters in the URL call?
如果我在 URL 调用中有多个参数,如何编写flask approute?
Here is my URL I am calling from AJax
这是我从 AJax 调用的 URL
http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure
I was trying to write my flask approute like this.
我试图像这样编写我的烧瓶应用程序。
@app.route('/test/<summary,change> ,methods=['GET']
But this is not working. Can any one suggest me how to mention the approute?
但这是行不通的。任何人都可以建议我如何提及 approute 吗?
回答by Anorov
You're mixing up URL parameters and the URL itself.
您正在混淆 URL 参数和 URL 本身。
You can get access to the URL parameters with request.args.get("summary")and request.args.get("change").
您可以使用request.args.get("summary")和访问 URL 参数request.args.get("change")。
回答by Burhan Khalid
Routes do not match a query string, which is passed to your method directly.
路由与查询字符串不匹配,该字符串直接传递给您的方法。
from flask import request
@app.route('/createcm', methods=['GET'])
def foo():
print request.args.get('summary')
print request.args.get('change')
回答by Peng Xiao
@app.route('/createcm', methods=['GET'])
def foo():
print request.args.get('summary')
print request.args.get('change')
回答by Little Roys
You can try this:
你可以试试这个:
--- Curl request ---
--- 卷曲请求 ---
curl -i "localhost:5000/api/foo?a=hello&b=world"
--- flask server---
--- 烧瓶服务器---
from flask import Flask, request
app = Flask(__name__)
@app.route('/api/foo/', methods=['GET'])
def foo():
bar = request.args.to_dict()
print bar
return 'success', 200
if __name__ == '__main__':
app.run(debug=True)
---console output---
---控制台输出---
{'a': u'hello', 'b': u'world'}
P.S. Don't omit double quotation(" ") with curl option, or it not work in Linux cuz "&"
PS 不要省略带有 curl 选项的双引号 (" "),否则它在 Linux 中不起作用,因为 "&"
回答by Wei Huang
In your requesting url: http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure, the endpoint is /createcmand ?summary=VVV&change=Feauureis argspart of request. so you can try this:
在您的请求 url: 中http://0.0.0.0:8888/createcm?summary=VVV&change=Feauure,端点是/createcm并且?summary=VVV&change=Feauure是args请求的一部分。所以你可以试试这个:
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.route('/createcm', methods=['get'])
def create_cm():
summary = request.args.get('summary', None) # use default value repalce 'None'
change = request.args.get('change', None)
# do something, eg. return json response
return jsonify({'summary': summary, 'change': change})
if __name__ == '__main__':
app.run(debug=True)
httpieexamples:
httpie例子:
http get :5000/createcm summary==vvv change==bbb -v
GET /createcm?summary=vvv&change=bbb HTTP/1.1
Accept: */*
Accept-Encoding: gzip, deflate
Connection: keep-alive
Host: localhost:5000
User-Agent: HTTPie/0.9.8
HTTP/1.0 200 OK
Content-Length: 43
Content-Type: application/json
Date: Wed, 28 Dec 2016 01:11:23 GMT
Server: Werkzeug/0.11.13 Python/3.6.0
{
"change": "bbb",
"summary": "vvv"
}
回答by GMarsh
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)
A few notes. If you only need to support GET requests, no need to include the methods in your route decorator.
一些笔记。如果您只需要支持 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.
解释查询参数。除了“?”之外的一切 在您的示例中称为查询参数。Flask 将从 URL 中取出这些查询参数并将它们放入一个 ImmutableDict 中。您可以通过 访问它request.args,可以使用密钥,即,request.args['summary']或者使用我和其他一些评论者提到的 get 方法。这使您可以在默认值不存在的情况下为其添加默认值(例如无)。这对于查询参数很常见,因为它们通常是可选的。
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):
...
The url here would be: http://0.0.0.0:8888/createcm/VVV/Feauure
这里的网址是:http: //0.0.0.0: 8888/createcm/VVV/Feauure
With VVV and Feauure being passed into your function as variables.
将 VVV 和 Feauure 作为变量传递到您的函数中。
Hope that helps.
希望有帮助。
回答by Viraj Wadate
Simply we can do this in two stpes: 1] Code in flask [app.py]
简单地说,我们可以通过两个步骤来做到这一点:1] 烧瓶中的代码 [app.py]
from flask import Flask,request
app = Flask(__name__)
@app.route('/')
def index():
return "hello"
@app.route('/admin',methods=['POST','GET'])
def checkDate():
return 'From Date is'+request.args.get('from_date')+ ' To Date is '+ request.args.get('to_date')
if __name__=="__main__":
app.run(port=5000,debug=True)
2] Hit url in browser:
2]在浏览器中点击网址:
http://127.0.0.1:5000/admin?from_date=%222018-01-01%22&to_date=%222018-12-01%22

