通过Flask在Javascript与Python之间调用:方法不允许错误405

2 投票
1 回答
1368 浏览
提问于 2025-04-18 11:31

我正在用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)

1 个回答

1

这里有几个问题:

  1. 你实际上并没有向 /mypython.py 发送一个 POST 请求,而是发送到了 /(这个地址只能通过 GET 请求访问,所以才会出错)。
  2. 你在提交表单(通过 $('#myForm').submit())的同时,还在下一行使用 $.ajax 发起一个ajax请求——浏览器会自动处理第一次提交,但这会导致页面跳转,从而 取消 第二个请求。
  3. /mypython.py 不是一个已定义的路由,所以会返回404错误。Flask只处理那些明确注册的路由(比如 /static/<path:file_path> 是Flask自动添加的,这就是为什么静态文件能正常工作)。
  4. templates 文件夹中的文件默认并不会作为可访问的资源,而是通过 render_template 函数经过Jinja处理后使用。
  5. 为了让用户能够通过JavaScript或网页使用Python的功能,你需要明确地将其设置为可路由(可以通过 @app.routeapp.add_url_route 来实现)。

撰写回答