我有以下扭曲的代码。但是,当我运行该应用程序时,我收到 localhost 的错误 404
from prometheus_client import Histogram, make_wsgi_app
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource
from twisted.web.resource import Resource
from twisted.internet import reactor
metrics_resource = WSGIResource(
reactor, reactor.getThreadPool(), make_wsgi_app())
LATENCY_HISTOGRAM = Histogram('hello_world_latency_seconds_h',
'Time for a request Hello World.',
buckets=[0.0001, 0.0002, 0.0005, 0.001, 0.01, 0.1, 0.2, 1, 10])
class HelloWorld(Resource):
isLeaf = False
@LATENCY_HISTOGRAM.time()
def render_GET(self, request):
return b"Hello World"
root = HelloWorld()
root.putChild(b'metrics', metrics_resource)
reactor.listenTCP(8000, Site(root))
reactor.run()
我做错了什么?
您正在使用 Twisted(一个 Python 框架),并且由于代码中缺少方法而遇到错误。由于您的 HelloWorld 类的 isLeaf 属性设置为 False,Twisted 期望此类可以处理子资源。
HelloWorld 类(资源): 叶=真 def render_GET(自身,请求): 返回b“Hello World!”
HelloWorld 类(资源): 叶=假 def render_GET(自身,请求): 返回b“Hello World!”
def getChild(self, name, request):
if name == '':
return self
else:
return Resource.getChild(self, name, request) # Default behavior
通过执行上述任一操作,您应该可以防止 Twisted 在尝试访问根路径或由 HelloWorld 类错误处理的任何子路径时抛出 404 错误。