我正在Python中使用Flask,我试图在我托管的服务器上详细说明发布请求(本地主机上的atm,因为我仍在努力使其工作)。
帖子消息通过以下方式生成:
payload = {'k' : '123' }
r = requests.post ('http://localhost', payload)
然后我得到的结果是
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>405 Method Not Allowed</title>
<h1>Method Not Allowed</h1>
<p>The method is not allowed for the requested URL.</p>
同时,如果我尝试向地址 localhost/post 发送相同的请求,如下所示
r2 = requests.post ('http://localhost/post', data)
结果变成
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>404 Not Found</title>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
我用来创建服务器的代码如下:
from flask import Flask, jsonify, Request
from flask.templating import render_template
from flask.globals import request
app = Flask(__name__)
@app.route('/', methods = ['GET', 'POST'])
def index ():
return render_template('indexServer.html')
@app.route('/post', methods =['GET', 'POST'])
def post():
return render_template('response.html')
if __name__ == '__main__':
app.run(host = 'localhost', port = 80, debug = True)
现在,虽然索引函数中的 GET 方法可以工作,但当我尝试获取“/post”页面时却不起作用。我想这背后的原因也和我在上面尝试发帖时得到 404 的原因相同。
我想了解为什么会发生这种情况,因为我无法弄清楚发生了什么以及我做错了什么。如果它还不是很明显,我刚刚开始使用 Flask 使用 Python 工作,所以它可能是任何东西。
感谢您的关注。
最佳答案
您的代码看起来不错 - 在我看来,您的 Flask 应用程序实际上并未像您期望的那样监听端口 80。
造成这种情况的原因可能有很多 - 也许现有进程已经在使用端口 80
,因此您的 Flask 应用程序无法绑定(bind)到它。或者在许多操作系统中,您需要以 root
身份运行进程才能绑定(bind)到小于 1024
的端口。我建议您将绑定(bind)端口更改为 8088
:
if __name__ == '__main__':
app.run(host = 'localhost', port = 8088, debug = True)
然后再次尝试您的请求:
r2 = requests.post ('http://localhost:8088/post', data)
关于python - 为什么我调用这些方法时总是出现 "Not found"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30248491/