【问题标题】:Call between Javascript & Python with Flask: Method Not Allowed error 405使用 Flask 在 Javascript 和 Python 之间调用:不允许方法错误 405
【发布时间】:2014-06-29 23:24:07
【问题描述】:

我正在使用 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 文件位于同一个“模板”目录下。但是,我收到消息“不允许使用方法。请求的 URL 不允许使用该方法”。

查看 Stackoverflow 上提出的类似问题,我确保在方法中包含“GET”和“POST”。为什么我仍然有这个错误?

作为测试,“mypython.py”如下:

def restaurant_choice(zipcode, cuisine):
    print "zipcode:", zipcode
    return "cuisine: ", cuisine

restaurant_choice(getzipcode, getcuisine)

【问题讨论】:

  • 在日志中检查哪个动词到达服务器。它真的是一个帖子吗?有时客户端会先发送一个 OPTIONS,然后再发送 GET/POST。
  • 这是我在终端登录时得到的结果:127.0.0.1 - - [29/Jun/2014 19:20:41] "POST / HTTP/1.1" 405 -

标签: javascript python flask


【解决方案1】:

这里有多个问题:

  1. 您实际上并未向 /mypython.py 发送 POST 请求 - 您将其发送至 /(只能通过 GET 访问,因此会出现错误。)
  2. 您正在提交表单(通过$('#myForm').submit()在下一行通过$.ajax 发出 ajax 请求 - 浏览器将为您提供第一个,因为这将导致页面导航事件将取消第二个。
  3. /mypython.py 不是已定义的路由,因此会导致 404。Flask 仅处理显式注册的路由(/static/&lt;path:file_path&gt; 由 Flask 自动为您添加,这就是静态文件工作的原因)。
  4. templates 文件夹中的文件默认不会作为服务资源公开,而是由 render_template 函数通过 Jinja(通常)传递。
  5. 为了向最终用户公开 Python 功能(通过 JavaScript 或作为网页使用),您应该明确地使其可路由(通过 @app.routeapp.add_url_route)。

【讨论】:

    猜你喜欢
    • 2012-08-24
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    相关资源
    最近更新 更多