python - 覆盖来自 Twisted.web 的所有默认资源/响应

标签 python twisted twisted.web

用于超基本的 http 扭曲前端。 我怎样才能确保没有 html 被写回,除非我告诉它。

所以,我的/zoo 网址如下。 对于任何回溯或“没有此类资源”响应,我只想删除连接或返回空响应。

我想这是一个 super 简单的问题,但无法弄清楚:) 我知道我可以通过没有特定的子路径来做到这一点,但想要高效地做到这一点,只想尽早放弃它..也许不使用资源?

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)

最佳答案

Some basics first

twisted.web 的工作方式是

有一个类叫Site这是一个 HTTP 工厂。 每个请求都会调用此方法。事实上,调用一个名为 getResourceFor 的函数来获取服务该请求的适当资源。 该 Site 类是使用根资源初始化的。函数 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) 注册时,它们会成为该资源的子资源。 一个例子:

root_resource
|
|------------ resource r1 (path = 'help')
|----resource r2 (path = 'login')  |
|                                  |----- resource r3 (path = 'registeration')
|                                  |----- resource r4 (path = 'deregistration')

一些思考:

  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:

您需要将 Site 子类化为

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

您必须创建自己的资源

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

关于python - 覆盖来自 Twisted.web 的所有默认资源/响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4307294/

相关文章:

python - 正则表达式获取数据后 |

python - 无法为 twisted.web 导入 python http 模块

python - 扭曲的 ReconnectingClientFactory 失败且没有错误

python - 访问 twisted.web.client.Agent 的套接字选项

jquery - 有没有人有将 jqGrid 与 twisted/python 一起使用的示例

python - 子类化 multiprocessing.managers.BaseProxy

python - 使用 Python 在 Excel 工作表中查找带下划线的单词

python - Pillow 模块 - 裁剪和保存时色调发生变化(无转换)

python - twisted:一个客户端,多个服务器

python - python扭曲静态文件中的变量替换