我正在使用 Flask 运行服务器。这是我的 views.py:
from flask import render_template
from app import app
@app.route('/')
@app.route('/user_form.html', methods=["GET", "POST"])
def index():
return render_template("user_form.html")
user_form.html 包含以下 Javascript:
<SCRIPT>
function get_UserInputValues(form) {
var getzipcode = document.getElementById('user_zip').value;
var getcuisine = document.getElementById('cuisine').value;
var selection1 = $("#slider1").slider("value");
var selection2 = $("#slider2").slider("value");
var selection3 = $("#slider3").slider("value");
var myurl = 'http://127.0.0.1:5000/mypython.py';
/*alert(getzipcode);
alert(getcuisine);
alert(selection1);
alert(selection2);
alert(selection3);*/
$('#myForm').submit();
$.ajax({url: myurl, type: "POST", data: {zip: getzipcode, cuisine:getcuisine}, dataType: 'json', done: onComplete})
}
function onComplete(data) {
alert(data);
};
</SCRIPT>
user_form.html 和 mypython.py 文件位于相同的“templates”目录下。但是,我收到消息,“方法不允许。请求的 URL 不允许该方法”。
查看 Stackoverflow 上提出的类似问题,我确保在方法中包含“GET”和“POST”。为什么我仍然有这个错误?
作为测试,“mypython.py”如下:
def restaurant_choice(zipcode, cuisine):
print "zipcode:", zipcode
return "cuisine: ", cuisine
restaurant_choice(getzipcode, getcuisine)
请您参考如下方法:
这里有多个问题:
- 你实际上并没有发送
POST请求/mypython.py- 您正在将其发送至/(只能通过GET访问,因此出现错误。) - 你们都在提交表单(通过
$('#myForm').submit())并且通过$.ajax发出 ajax 请求在下一行 - 浏览器将为您生成第一个,因为这将导致页面导航事件,所以它将取消第二个。 -
/mypython.py不是定义的路由,因此将导致 404。Flask 仅处理明确注册的路由(/static/<path:file_path>由 Flask 自动为您添加,这就是静态文件工作的原因)。 templates中的文件默认情况下,文件夹不会作为服务资源公开,而是通过render_template通过 Jinja(通常)传递功能。- 为了向最终用户公开 Python 功能(通过 JavaScript 或作为网页使用),您应该明确使其可路由(通过
@app.route或app.add_url_route)。
