Tornado POST 405:方法不允许

时间:2013-09-25 13:49:38

标签: python python-2.7 tornado

出于某种原因,我无法在torando中使用post方法。

当我改变发布时,即使是hello_world示例也不起作用。

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Hello, world")

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

不允许抛出405方法。 有什么建议吗?

4 个答案:

答案 0 :(得分:7)

如果您想访问该页面,仍需要get,因为使用GET方法使用浏览器请求访问该页面。

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def post(self):
        self.write("Hello, world")
    get = post # <--------------

application = tornado.web.Application([
    (r"/", MainHandler),
])

if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

答案 1 :(得分:3)

Falsetru答案是一个有用的提示,是的,你需要的只是一个get方法。但不,我不认为get和post方法应该表现相同。两种方法的语义不同。请查看HTTP规范http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html,并考虑Brabster对此问题What is the difference between a HTTP-Get and HTTP-POST and why is HTTP-POST weaker in terms of security的回答。

(对不起,我的判决应该更好地评论一下,但我的名声不允许)

答案 2 :(得分:1)

最近,我遇到了同样的问题。以下代码是我的解决方案:

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def set_default_headers(self):
    print('set headers!!')
    self.set_header('Access-Control-Allow-Origin', '*')
    self.set_header('Access-Control-Allow-Headers', '*')
    self.set_header('Access-Control-Max-Age', 1000)
    self.set_header('Content-type', 'application/json')
    self.set_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS')
    self.set_header('Access-Control-Allow-Headers',
                    'Content-Type, Access-Control-Allow-Origin, Access-Control-Allow-Headers, X-Requested-By, Access-Control-Allow-Methods')


def OPTIONS(self):
    pass

def post(self):
    self.write("Hello, world")

application = tornado.web.Application([
(r"/", MainHandler),
])

if __name__ == "__main__":`enter code here`
 application.listen(8888)
 tornado.ioloop.IOLoop.instance().start()

答案 3 :(得分:0)

enter image description here您在问题中提供的示例代码可以正常运行。例如,确保使用Curl或Postman发送POST而不是GET。如果您将Web浏览器指向URL,它将尝试GET,您尚未定义。

您可能不想为URL定义GET。拥有一个仅限POST的URL是完全合法的,而Tornado肯定允许你这样做。 POST网址可能是从许多其他位置加载的表单的常见提交点。

相关问题