从Flask中的html表单获取请求的复杂路由 [英] Complex routing for get request from html form in flask
问题描述
我正在尝试为如下所示的get请求创建复杂的路由:
I'm trying to create complex routing for a get request that looks like this:
@app.route('/get-details?id=<int:id>&code=<int:code>', methods=['GET'])
@login_required
def get_details(id, code):
# Do something with code and id ....
在我的模板中,我有一个看起来像这样的表单:
And in my template I have a form that looks like this:
<form action="{{url_for('get_details')}}" method="get">
{{ form.hidden_tag() }}
{{ form.id() }}
{{ form.code() }}
<input type="submit">
</form>
但是当我尝试渲染我的页面时,出现了这个异常:
But when I try to render my page I get this exception:
File "/home/sharon/dev/wiseart/credixdealer/app/templates/dashboard/form-device.html", line 113, in block "content"
<form action="{{url_for('get_details')}}" method="get">
File "/usr/local/lib/python2.7/dist-packages/flask/helpers.py", line 332, in url_for
return appctx.app.handle_url_build_error(error, endpoint, values)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1811, in handle_url_build_error
reraise(exc_type, exc_value, tb)
File "/usr/local/lib/python2.7/dist-packages/flask/helpers.py", line 322, in url_for
force_external=external)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/routing.py", line 1758, in build
raise BuildError(endpoint, values, method, self)
BuildError: Could not build url for endpoint 'get_details'. Did you forget to specify values ['business_id', 'id']?
如何在url_for中指定应从表单本身中检索参数?
How can I specify in url_for that the parameters should be retrieved from the form itself?
推荐答案
不要在路由定义中添加查询参数.而是从request.args
获取它们. args.get
带有可选的type
参数,因此您仍然可以验证值的类型.
Don't put query args in the route definition. Instead, get them from request.args
. args.get
takes an optional type
argument, so you can still validate the type of the value.
@app.route('/get_details')
def get_details():
id = request.args.get('id', type=int)
code = request.args.get('code', type=int)
...
有关特定错误的解决方案,请阅读错误消息.您有一个带有两个URL组的路由,但是没有为它们提供值到url_for
.由于您仅在客户端上填写表单后才知道args,因此这成为为什么不将查询args放在路由中的一个很好的论据.
For the solution to your specific error, read the error message. You have a route with two url groups, but you don't supply values for them to url_for
. Since you only know the args after the form is filled out on the client, this becomes a good argument for why you don't put query args in the route.
url_for('get_details', id=2, code=108)
这篇关于从Flask中的html表单获取请求的复杂路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!