Flask - 方法不被允许

4 投票
1 回答
7942 浏览
提问于 2025-04-18 05:50

我正在学习一个Flask的入门教程,但遇到了一个错误。命令行中显示的完整错误信息是:“GET /signup HTTP/1.1” 405。根据这两个文件,你能帮我找出我哪里出错了吗?

http://opentechschool.github.io/python-flask/core/form-submission.html

<!-- index.html in the templates folder -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Cats Everywhere!</title> 

    <link href='http://fonts.googleapis.com/css?family=Sintony:400,700' rel='stylesheet' type='text/css'>

    <style type="text/css">    
  body
  {
    background-color:#000;
  }

  h1
  {
    font-size:48px;
    margin-top:0;
    font-family:Arial, sans-serif;
    text-shadow:2px 0 15px #292929;
    letter-spacing:4px;
    text-decoration:none;
    color:#DDD;
  }

  #banner
  {
    width:500px;
    height:200px;
    text-align:center;
    background-image:url(http://i.imgur.com/MQHYB.jpg);
    background-repeat:no-repeat;
    border-radius:5px;
    margin:90px auto auto;
    padding:80px 0;
  }

  .lead
  {
    background-color:rgba(255,255,255,0.6);
    border-radius:3px;
    box-shadow:rgba(0,0,0,0.2) 0 1px 3px;
    font-family:Sintony, sans-serif;
  }
    </style>

</head>  

<body>
    <div id="banner">
        <h1>cats everywhere</h1>
        <p class="lead">We're bringing cats to the internet. Free. Cute. Awesome.</p>
    </div>
    <div id="emailform">
        <form action="/signup" method="post">
            <input type="text" name="email"></input>
            <input type="submit" value="Signup"></input>
        </form>
    </div>
</body>
</html>

#catseverywhere.py file:
from flask import Flask, render_template
from flask import request, redirect

app = Flask(__name__)

@app.route('/')
def hello_world():
    author = "Me"
    name = "RandomName"
    return render_template('index.html', author=author, name=name)

@app.route('/signup', methods = ['POST'])
def signup():    
    email = request.form['email']
    print("The email address is '" + email + "'")
    return redirect('/')

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

1 个回答

3

你的代码运行得很好,但你对 /signup 路径的工作方式有些误解。

主页上有一个表单;在浏览器中访问 http://localhost:5000/,你会看到一个白色的文本框和一个 signup 按钮。你在那个框里输入的内容会被发送到服务器。

控制台的显示会是这样的:

 * Running on http://127.0.0.1:5000/
127.0.0.1 - - [08/May/2014 15:00:53] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [08/May/2014 15:00:53] "GET /favicon.ico HTTP/1.1" 404 -
The email address is 'abcd'
127.0.0.1 - - [08/May/2014 15:00:57] "POST /signup HTTP/1.1" 302 -
127.0.0.1 - - [08/May/2014 15:00:57] "GET / HTTP/1.1" 200 -

这里 GET / 是浏览器在获取主页和表单,POST /signup 是表单被提交,这之后会返回一个302重定向,让浏览器再次访问主页。

根据配置,/signup 路径只能处理 POST 请求,也就是浏览器为表单结果产生的请求。你通常不会直接在浏览器中访问它;如果你输入 http://localhost:5000/signup,实际上会产生一个 GET 请求。

换句话说,你看到的错误是 故意设计的; 这个路径只支持 POST 请求。

撰写回答