烧瓶url_for导致escape_chars http_405

时间:2020-09-27 19:35:42

标签: flask http-status-code-405 url-for

我搜索并阅读了许多类似的帖子,但是我的问题的行为与发现的行为不同。

我有一个超级简单的烧瓶应用程序(如下)。所做的全部工作就是在test.html页面上显示两个按钮,以回调到python def。

  1. Test1按钮具有硬编码的形式action =“ / test”。
    • 作品
  2. Test2按钮的形式为action =“ {{url_for('test')}}”
    • 失败:> POST /%7B%7B%20url_for('test')%20%7D%7D HTTP / 1.1“ 405-
    • 不允许使用方法

可能是什么问题? 转义字符是问题吗?如果是这样,我该如何预防?

test.py

#!/usr/bin/env python3
from flask import Flask, request, send_file
app = Flask(__name__, static_url_path='', static_folder='')

@app.route('/')
def FooTest():
  return app.send_static_file('test.html')

@app.route("/test", methods=["GET","POST"])
def test():
  print("Got Callback:")
  return "Click"

if __name__ == '__main__':
  app.run(debug=True)

test.html

<!DOCTYPE html> 
<html> 
   <form method="post" action="/test">
       <button type="submit"> Test1</button/>
   </form>
   <form method="post" action="{{ url_for('test') }}">
       <button type="submit"> Test2</button/>
   </form>
</html>

1 个答案:

答案 0 :(得分:1)

您的test.html是Jinja2模板,可以通过调用render_template来创建所需的HTML进行处理。您按原样返回模板,因此浏览器尝试调用不存在的http://localhost:5000/{{ url_for('test') }}。像这样更改FooTest(您可能需要调整文件路径):

from flask import render_template

@app.route('/')
def FooTest():
  return render_template('test.html')