覆盖来自的所有默认资源/响应扭曲的.web

2024-05-19 22:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

对于一个超基本的http twisted前端。 我怎样才能确保没有html被写回,除非我告诉它。在

所以,我在下面有我的/动物园的网址。 对于任何回溯或“无此类资源”响应,我只想断开连接或返回空响应。在

我想这是一个超级简单的问题,但我想不出来:) 我知道我可以通过没有我特定的子路径来做到这一点,但是我想做得有效率,只想尽早放弃它。。也许不用资源?在

class HttpApi(resource.Resource):
    isLeaf = True
    def render_POST(self, request):
        return "post..."


application = service.Application("serv")

json_api = resource.Resource()
json_api.putChild("zoo", HttpApi())
web_site = server.Site(json_api)
internet.TCPServer(8001, web_site).setServiceParent(application)

Tags: 路径apiwebjsonhttpapplicationhtmltwisted
1条回答
网友
1楼 · 发布于 2024-05-19 22:26:34

Some basics first

路途扭曲的.web工作是

有一个名为Site的类,它是一个HTTP工厂。 每一个请求都需要这样做。实际上,调用了一个名为getResourceFor的函数来获取将为该请求提供服务的适当资源。 此网站类是用根资源初始化的。功能呢Site.getResourceFor对根资源调用resource.getChildForRequest

呼叫流程是:

Site.getResourceFor -> resource.getChildForRequest (root resource)

现在我们来看看getChildForRequest:

def getChildForRequest(resource, request):
    """
    Traverse resource tree to find who will handle the request.
    """
    while request.postpath and not resource.isLeaf:
        pathElement = request.postpath.pop(0)
        request.prepath.append(pathElement)
        resource = resource.getChildWithDefault(pathElement, request)
    return resource

当资源注册到putChild(path)时,它们将成为该资源的子资源。 例如:

^{pr2}$

一些思考:

  1. 现在r1将使用路径http://../help/对请求进行服务器处理
  2. 现在r3将使用路径http://../help/registration/来服务器请求
  3. 现在r4将使用路径http://../help/deregistration/来服务器请求

但是

  1. r3将使用路径http://../help/registration/xxx/来处理请求
  2. r3将使用路径http://../help/registration/yyy/来服务器请求

For the solution:

您需要将站点子类化为

  1. 检查路径是否与pathElement为空返回的资源完全匹配,然后才处理它或
  2. 返回一个资源,该资源将作为处理其他方面的处理程序

你必须创建自己的资源

def render(self, request):
    request.setResponseCode(...)
    return ""

相关问题 更多 >