首页 > 解决方案 > Flask:使用表单操作的参数调用函数

问题描述

routes.py我有一个功能:

@app.route('/')
@app.route('/makecsc_relocation') 
def makecsc_relocation(csc_post_index):
    ... 
    makeCscRelocationRep(repname, csc_post_index)
    return send_file(repname+'.xlsx', as_attachment=True, attachment_filename=repname+' '+csc_post_index+'.xlsx')

index,我有以下内容:

@app.route('/')
@app.route('/index')
def index():
...
sForm = """<form action="makecsc_relocation">
                             Enter postal code here: <input type="text" name="post_index" value=""><br>
                             <input type="submit" value="Download report" ><br>
                             </form>"""

如果我使用没有参数的函数<form action="">并将空input值传递给它,一切正常,但是当我尝试input post_index作为参数传递给该函数时,我得到内部服务器错误,并带有以下 URL: http://myservername/makecsc_relocation?post_index=452680

我该如何解决?

标签: pythonflask

解决方案


函数参数始终是路径参数,即<parametername>您注册的路由路径中的组件@app.route()。你没有这样的参数,所以不要给你的函数任何参数。请参阅Flask 快速入门中的变量规则

查询参数(表单中的 key=value 对,放在?URL 中的后面)以request.args

@app.route('/makecsc_relocation') 
def makecsc_relocation():
    csc_post_index = request.args.get('post_index')  # can return None
    # ... 
    makeCscRelocationRep(repname, csc_post_index)
    return send_file(repname+'.xlsx', as_attachment=True, attachment_filename=repname+' '+csc_post_index+'.xlsx')

请参阅快速入门的请求对象部分。

  • 如果request.args.get(...)值是可选的,或者如果您需要将其从字符串转换为相同类型的不同类型,则使用此选项。
  • request.args[...]如果不提供值是错误的,请使用。如果缺少查询参数,则会向客户端提供 400 Bad Request HTTP 错误响应。

有关此映射如何工作的详细信息,请参阅WerkzeugMultiDict文档


推荐阅读