【问题标题】:Method Not Allowed flask error 405方法不允许烧瓶错误 405
【发布时间】:2014-03-08 12:02:44
【问题描述】:

我正在开发一个烧瓶注册表,我收到一个错误:

error 405 method not found.

代码:

import os
# Flask
from flask import Flask, request, session, g, redirect, url_for, abort, \
     render_template, flash, Markup, send_from_directory, escape
from werkzeug import secure_filename

from cultura import app

# My app
from include import User

@app.route('/')
def index():
    return render_template('hello.html')

@app.route('/registrazione', methods=['POST']) 
def registration():
    if request.method == 'POST':
        username= request.form.username.data
        return render_template('registration.html', username=username)
    else :
        return render_template('registration.html')

registration.html:

<html>
<head> <title>Form di registrazione </title>
 </head> 

    <body>
    {{ username }}
    <form id='registration' action='/registrazione' method='post'>
    <fieldset >
    <legend>Registrazione utente</legend>
    <input type='hidden' name='submitted' id='submitted' value='1'/>
    <label for='name' >Nome: </label> 
    <input type='text' name='name' id='name' maxlength="50" /> <br>
    <label for='email' >Indirizzo mail:</label>
    <input type='text' name='email' id='email' maxlength="50" />
     <br>
    <label for='username' >UserName*:</label>
    <input type='text' name='username' id='username' maxlength="50" />
     <br>
    <label for='password' >Password*:</label>
    <input type='password' name='password' id='password' maxlength="50" />
    <br>
    <input type='submit' name='Submit' value='Submit' />

    </fieldset>
    </form>
    </body>
    </html>

当我访问localhost:5000/registrazione 时,我收到错误消息。我做错了什么?

【问题讨论】:

  • methods=['POST']if request.method == 'POST': (...) else: 完全不兼容
  • 所以。您收到一个方法不允许错误,并且您正在对声明为仅接受 POST 的路由执行 GET 请求。你现在明白为什么了吗?
  • 是的,我添加了 @app.route('/registrazione', methods=['GET', 'POST']) 但现在我收到错误 500 Internal Server Error
  • 可能是因为{{ username }}没有定义,但是你有日志,所以你应该知道。
  • 我认为username. data 是错误的。只需使用username = request.form.username 就可以了。

标签: python forms flask


【解决方案1】:

这是因为您在定义路由时只允许 POST 请求。

当您在浏览器中访问/registrazione 时,它会首先执行 GET 请求。只有在您提交表单后,您的浏览器才会进行 POST。因此,对于像您这样的自提交表单,您需要同时处理这两个问题。

使用

@app.route('/registrazione', methods=['GET', 'POST']) 

应该可以。

【讨论】:

  • 谢谢,现在开始工作。但是如果我编辑 def registration(): if request.method == 'POST': username= request.form.username.data return render_template('registration.html', username=username) else : return render_template('registration.html ') 我收到内部服务器错误
  • @Matteo 这是另一个问题,请创建一个新问题并包含堆栈跟踪。
【解决方案2】:

仅供现在阅读它的人使用。 您必须先呈现 /registrazione,然后才能访问表单数据。就写吧。

@app.route("/registrazione")
    def render_registrazione() -> "html":
        return render_template("registrazione.html")

在定义 def registration() 之前。顺序是关键。在事件可用之前,您无法访问数据。这是我对问题的理解。

【讨论】:

  • 因为我遇到了同样的问题,或者至少它看起来与我相似,因为我收到了相同的错误消息,而对我来说,提供的解决方案不起作用。但是,如果我先在项目中使用表单渲染模板,然后尝试使用新函数和 post 方法访问表单数据,一切正常。所以我想我不能发布到不存在的东西上。如果其他人的解决方案不适合我,我为什么不应该发布我的解决方案?
【解决方案3】:

使用 wsgi 和 JQuery、Ajax 和 json 的烧瓶应用示例:

activecalls.py

from flask import Flask, jsonify

application = Flask(__name__, static_url_path='')

@application.route('/')
def activecalls():
    return application.send_static_file('activecalls/active_calls_map.html')

@application.route('/_getData', methods=['GET', 'POST'])
def getData():
    #hit the data, package it, put it into json.
    #ajax would have to hit this every so often to get latest data.
    arr = {}
    arr["blah"] = []
    arr["blah"].append("stuff");

    return jsonify(response=arr)


if __name__ == '__main__':
    application.run()

Javascript json,/static/activecalls/active_calls_map.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>

<script>
$.ajax({
    //url : "http://dev.consumerunited.com/wsgi/activecalls.py/_getData",
    url : "activecalls.py/_getData",
    type: "POST",
    data : formData,
    datatype : "jsonp",
    success: function(data, textStatus, jqXHR)
    {
        //data - response from server
         alert("'" + data.response.blah + "'");
    },
    error: function (jqXHR, textStatus, errorThrown)
    {
         alert("error: " + errorThrown);

    }
});
</script>

当你运行它时。警告框打印:“stuff”。

【讨论】:

    【解决方案4】:

    更改方法注册名称

    @app.route('/registrazione', methods=['POST']) 
    def registrazione(): 
        if request.method == 'POST':
           username= request.form.username.data
           return render_template('registration.html', username=username)
       else :
           return render_template('registration.html')
    

    【讨论】:

      【解决方案5】:

      我也遇到了这个错误,我浏览了所有这些文档并试图解决这个问题,但最后这是一个愚蠢的错误。

      下面的代码产生了405 Method Not Allowed 错误

      import requests
      import json
      
      URL = "http://hostname.com.sa/fetchdata/"
      
      PARAMS = '{ "id":"111", "age":30, "city":"New Heaven"}'
      
      response = requests.post(url = URL, json = PARAMS)
      
      print(response.content)
      

      这是由于网址末尾有一个额外的/,当我删除它时,它就消失了。请求 URL 的以下更新修复了它

      URL = "http://hostname.com.sa/fetchdata"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-28
        • 2014-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-20
        • 2017-11-13
        相关资源
        最近更新 更多