【问题标题】:Method Not Allowed The method is not allowed for the requested URL. 405 Error方法不允许 请求的 URL 不允许使用该方法。 405 错误
【发布时间】:2021-08-16 03:31:50
【问题描述】:

我是构建 API 的新手。我正在构建一个非常简单的 API:执行时,显示 API 的 HTML 页面会要求输入名称:Api 只会返回:“Hello {name}”。我收到 405 错误。这是我的 App.py 和 HTML 页面的代码:

from app import app
from flask import render_template
from flask import request

@app.route('/')
def home():
   return "hello no  world!"

@app.route('/template',methods=['POST','GET'])
def template():
    output = [request.form.values()]
    output = output[0]
    return render_template('home.html',prediction_text='Hello {}'.format(output))

还有我的 home.html 的 HTML 代码:

!doctype html>

<html lang="en-us">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>Welcome home</title>
  </head>

  <body>
    <div class="login">
        <h1>Enter your name</h1>

     <!-- Main Input For Receiving Query-->
    <form action="{{ url_for('template')}}"method="post">
        <input type="text" name="name" placeholder="Name" required="required" />

        <button type="submit" class="btn btn-primary btn-block btn-large">Enter</button>
    </form>

   <br>
   <br>
   {{ prediction_text }}

 </div>
  </body>
</html>

我已经查看了其他几个 StackOverflow 论坛就这个问题。 “GET”或“POST”方法似乎有问题,但我似乎无法弄清楚是什么?也许你们中的一个人可以看到我没有看到的东西。我在 Docker 中运行此 API,因此“app = Flask(name)”存储在其他地方,如果相关的话。

Method Not Allowed - The method is not allowed for the requested URL

Flask - POST - The method is not allowed for the requested URL

https://www.reddit.com/r/flask/comments/a04aew/ask_flask_help_me_to_find_the_error_in_my_code/

【问题讨论】:

  • 超文本传输​​协议 (HTTP) 405 Method, Not Allowed 响应状态码表示请求方法为服务器已知但目标资源不支持。
  • 那么你使用什么方法,POST?确切的要求是什么?你如何通过 Postman、curl 运行它?
  • @Alveona 因为我在 Docker 中运行应用程序,所以我有单独的文件用于使用 Ubuntu 终端运行程序。至于方法,我用来构建程序的视频专门使用“POST”方法,但是如果我们的输出要显示在 HTML 上,我在某处读到,它需要同时具有“GET”和“POST”。一切正常,但是当我输入名称并按 Enter 时,出现 405。
  • 更新:在我的 HTML 页面中:我将
    从“post”更改为“get”并且我现在确实得到了输出。然而它是这样的:“Hello ”而不是我打开 URL 时输入的名称。有什么想法吗?
  • 您需要request.form['name'] 之类的东西来获取文本框的值,因为您将其称为“名称”。并且您的路由 /template 接受 POST 请求,这就是为什么这个适用于表单但路由 / 不适用的原因。

标签: python html api flask


【解决方案1】:

这个问题现在已经解决了。我改变了两件事:

来自 HTML: 改变:

<form action="{{ url_for('template')}}"method="post">

 <form action="{{ url_for('template')}}"method="get">

并从 Flask API 更改:

output = [request.form.values()]
output = output[0]
return render_template('home.html',prediction_text='Hello {}'.format(output))

output = request.args.values()
return render_template('home.html',prediction_text="Hello {}?".format(list(output)[:]))

【讨论】:

    猜你喜欢
    • 2020-03-05
    • 2014-01-08
    • 2016-12-12
    • 2017-01-10
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多