python - 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
我该如何解决?
解决方案
函数参数始终是路径参数,即<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
文档。
推荐阅读
- ios - 动画高度更改 UITableView 但忽略 UILabel?
- vba - 将 .found = true 值添加到描述的字符串 Word VBA
- angular - 路由解析根组件Angular 6
- javascript - 更改事件与 React 和 Typescript 混为一谈
- javascript - 以信用卡格式键入字母数字键
- php - yii2中基于rbac角色在gridview中显示数据
- php - 如何使用php获取多个值可以变成单个值
- ios - 应用程序如何将帐户与应用内购买订阅联系起来?
- javascript - addExtension 和 addDevToolsExtension 的区别
- java - 为什么我在 Java 中收到 FileNotFoundException(文件名、目录名或卷标语法不正确)?