2014-06-29 121 views
2

我正在用瓶的服务器。这里是我的views.py:电话:不允许的方法错误405

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不允许使用该方法”。

看着问#2类似的问题,我就确定包括“GET”和“POST”的方法。为什么我仍然有这个错误?

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

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

restaurant_choice(getzipcode, getcuisine) 
+0

什么是mypython.py? –

+0

检查动词到达服务器的日志。它真的是一个POST吗?有时客户端发送OPTIONS然后GET/POST。 – Javier

+0

这是我得到的日志中的终端:127.0.0.1 - - [29月/ 6/2014 19时二十分41秒] “POST/HTTP/1.1” 405 - – Rohit

回答

1

有多种问题在这里:

  1. 您还没有实际发送POST请求/mypython.py - 您发送它到/(它只能通过GET访问,因此错误。)
  2. 你们都提交表格(通过$('#myForm').submit()通过$.ajax下一行做一个Ajax请求 - 浏览器将先为你,因为这将导致页面导航事件将取消第二。
  3. /mypython.py/mypython.py不是一个定义的路由,所以会产生一个404. Flask只处理显式注册的路由(Flask自动为你添加/static/<path:file_path>,这就是静态文件工作的原因)。
  4. 文件中的文件夹templates不公开为默认服务资源,而是通过神社(一般)由render_template函数传递。
  5. 为了向终端用户公开Python功能(通过JavaScript或网页使用),您应该明确地使其可以路由(通过@app.routeapp.add_url_route)。