CherryPy: 405 Method Not Allowed 指定的方法对此资源无效

CherryPy: 405 Method Not Allowed Specified method is invalid for this resource

我正在用 cherrypy 构建我的第一个带有身份验证的网络应用程序:auth 部分有效,但在登录后我收到错误 405 Method Not Allowed Specified method is invalid for this resource。关于如何克服它有什么想法吗?

提前致谢!

from cherrypy.lib import auth_digest
import cherrypy

USERS = {'jon': 'secret'}

config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8,
    'log.screen'         : True
  },
  '/' : {
    # HTTP verb dispatcher
    'request.dispatch': cherrypy.dispatch.MethodDispatcher(),
    # JSON response
    'tools.json_out.on' : True,
    # Digest Auth
    'tools.auth_digest.on'      : True,
    'tools.auth_digest.realm'   : 'walledgarden',
    'tools.auth_digest.get_ha1' : auth_digest.get_ha1_dict_plain(USERS),
    'tools.auth_digest.key'     : 'generate_something_random',
  }
}

class HelloWorld():
    def index(self):
        return "Hello World!"
    index.exposed = True

#cherrypy.quickstart(HelloWorld(), config=None) #this works
cherrypy.quickstart(HelloWorld(), config=config) #this is broken

您正在使用 MethodDispacher,它将 HTTP 方法映射为 exposed class 的 methods,在这种情况下,您的 index 方法应称为 GET.

@cherrypy.expose
class HelloWorld():

    def GET(self):
        return "Hello World!"

如果您使用的 python 版本不支持 class 装饰器,请使用:

class HelloWorld():
    exposed = True

    def GET(self):
        return "Hello World!"

基本上,使用 MethodDispatcher 公开具有与 HTTP 方法匹配的方法的 resources(对象),例如 GET - > def GET(self)POST -> def POST(self).

您可能会发现此 post 信息:https://blog.joel.mx/posts/cherrypy-101-method-dispatcher

感谢 cyraxjoe 指点,我明白了:

from cherrypy.lib import auth_digest
import cherrypy

USERS = {'jon': 'secret'}

config = {'/': {'tools.auth_digest.on': True,
               'tools.auth_digest.realm': 'walledgarden',
               'tools.auth_digest.get_ha1': auth_digest.get_ha1_dict_plain(USERS),
               'tools.auth_digest.key': 'generate_something_random',
}}

class HelloWorld():
    def index(self):
        return "Hello World!"
    index.exposed = True

#cherrypy.quickstart(HelloWorld(), config=None) #this works -- NO AUTHENTICATION
cherrypy.quickstart(HelloWorld(), config=config) #WORKS WITH AUTHENTICATION