Flask:从form action调用带有参数的函数

2024-05-28 11:16:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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中,我有以下内容:

^{pr2}$

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

我怎么解决这个问题?在


Tags: 函数pyappinputattachment参数indexxlsx
2条回答

函数参数总是路径参数,即注册到@app.route()的路由路径中的<parametername>组件。你没有这样的参数,所以不要给你的函数任何参数。请参阅烧瓶快速启动中的Variable Rules。在

查询参数(表单中的key=value对,放在URL中的?之后)以^{}结束:

@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')

请参阅快速入门的The Request Object部分。在

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

有关此映射如何工作的详细信息,请参见Werkzeug ^{} documentation。在

最后我得出了以下解决方案:

  1. 向表单添加了POST方法
sForm = """<form action="makecsc_relocation" method="post">
                             Enter postal code here: <input type="text" name="post_index" value=""><br>
                             <input type="submit" value="Download report" ><br>
                             </form>"""
  1. 在函数makecsc_relocation中,我添加了以下字符串:
^{pr2}$

并将其传递给makeCscRelocationRep

相关问题 更多 >