首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >覆盖来自Twisted.web的所有默认资源/响应

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

Stack Overflow用户
提问于 2010-11-30 03:31:48
回答 1查看 1.1K关注 0票数 1

一个超基本的http扭曲的前端。我如何才能确保不会回写html,除非我告诉它这样做。

所以,我下面有我的/zoo url。对于任何回溯或“没有这样的资源”响应,我只想丢弃连接或返回一个空响应。

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

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-11-30 04:16:20

先介绍一些基础知识

twisted.web的工作方式是

有一个名为Site的类,它是一个HTTP工厂。对于每个请求,都会调用此函数。实际上,调用了一个名为getResourceFor的函数来获取将为该请求提供服务的适当资源。此站点类使用根资源初始化。函数Site.getResourceFor在根资源上调用resource.getChildForRequest

呼叫流是:

Site.getResourceFor -> resource.getChildForRequest (根资源)

现在是时候看看getChildForRequest了:

代码语言:javascript
复制
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(路径)时,它们将成为该资源的子资源。举个例子:

代码语言:javascript
复制
root_resource
|
|------------ resource r1 (path = 'help')
|----resource r2 (path = 'login')  |
|                                  |----- resource r3 (path = 'registeration')
|                                  |----- resource r4 (path = 'deregistration')

一些思考:

  1. Now r1将使用path服务器请求http://../help/
  2. Now r3将使用path http://../help/registration/
  3. Now r4将使用path http://../help/deregistration/

服务器请求

使用路径http://../help/registration/xxx/

  • r3的服务器请求将使用路径http://../help/registration/yyy/

  1. r3服务器请求

解决方案的

您需要将Site子类化为

  1. 检查该路径是否与pathElement empty返回的资源完全匹配,然后才对其进行处理,否则
  2. 将返回一个资源,该资源将成为您处理其他方面的处理程序

你必须创建你自己的资源

代码语言:javascript
复制
def render(self, request):
    request.setResponseCode(...)
    return ""
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4307294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档