• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python inevow.IRequest类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中nevow.inevow.IRequest的典型用法代码示例。如果您正苦于以下问题:Python IRequest类的具体用法?Python IRequest怎么用?Python IRequest使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了IRequest类的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: render_POST

 def render_POST(self, ctx):
     req = IRequest(ctx)
     log.msg(format="User reports incident through web page: %(details)s",
             details=get_arg(req, "details", ""),
             level=log.WEIRD, umid="LkD9Pw")
     req.setHeader("content-type", "text/plain")
     return "An incident report has been saved to logs/incidents/ in the node directory."
开发者ID:warner,项目名称:tahoe-lafs,代码行数:7,代码来源:root.py


示例2: error

 def error(f):
     message, code = humanize_failure(f)
     req = IRequest(ctx)
     req.setResponseCode(code)
     return json.dumps({
         "error": message,
     })
开发者ID:LeastAuthority,项目名称:tahoe-lafs,代码行数:7,代码来源:directory.py


示例3: render_GET

    def render_GET(self, ctx):
        req = IRequest(ctx)
        # This is where all of the directory-related ?t=* code goes.
        t = get_arg(req, "t", "").strip()

        # t=info contains variable ophandles, t=rename-form contains the name
        # of the child being renamed. Neither is allowed an ETag.
        FIXED_OUTPUT_TYPES =  ["", "json", "uri", "readonly-uri"]
        if not self.node.is_mutable() and t in FIXED_OUTPUT_TYPES:
            si = self.node.get_storage_index()
            if si and req.setETag('DIR:%s-%s' % (base32.b2a(si), t or "")):
                return ""

        if not t:
            # render the directory as HTML, using the docFactory and Nevow's
            # whole templating thing.
            return DirectoryAsHTML(self.node,
                                   self.client.mutable_file_default)

        if t == "json":
            return DirectoryJSONMetadata(ctx, self.node)
        if t == "info":
            return MoreInfo(self.node)
        if t == "uri":
            return DirectoryURI(ctx, self.node)
        if t == "readonly-uri":
            return DirectoryReadonlyURI(ctx, self.node)
        if t == 'rename-form':
            return RenameForm(self.node)

        raise WebError("GET directory: bad t=%s" % t)
开发者ID:LeastAuthority,项目名称:tahoe-lafs,代码行数:31,代码来源:directory.py


示例4: renderHTTP_exception

 def renderHTTP_exception(self, ctx, f):
     try:
         text, code = humanize_failure(f)
     except:
         log.msg("exception in humanize_failure")
         log.msg("argument was %s" % (f,))
         log.err()
         text, code = str(f), None
     if code is not None:
         return self.simple(ctx, text, code)
     if f.check(server.UnsupportedMethod):
         # twisted.web.server.Request.render() has support for transforming
         # this into an appropriate 501 NOT_IMPLEMENTED or 405 NOT_ALLOWED
         # return code, but nevow does not.
         req = IRequest(ctx)
         method = req.method
         return self.simple(ctx,
                            "I don't know how to treat a %s request." % method,
                            http.NOT_IMPLEMENTED)
     req = IRequest(ctx)
     accept = req.getHeader("accept")
     if not accept:
         accept = "*/*"
     if "*/*" in accept or "text/*" in accept or "text/html" in accept:
         super = appserver.DefaultExceptionHandler
         return super.renderHTTP_exception(self, ctx, f)
     # use plain text
     traceback = f.getTraceback()
     return self.simple(ctx, traceback, http.INTERNAL_SERVER_ERROR)
开发者ID:gnusosa,项目名称:tahoe-lafs,代码行数:29,代码来源:common.py


示例5: render_GET

    def render_GET(self, ctx):
        req = IRequest(ctx)
        t = get_arg(req, "t", "").strip()

        # t=info contains variable ophandles, so is not allowed an ETag.
        FIXED_OUTPUT_TYPES = ["", "json", "uri", "readonly-uri"]
        if not self.node.is_mutable() and t in FIXED_OUTPUT_TYPES:
            # if the client already has the ETag then we can
            # short-circuit the whole process.
            si = self.node.get_storage_index()
            if si and req.setETag('%s-%s' % (base32.b2a(si), t or "")):
                return ""

        if not t:
            # just get the contents
            # the filename arrives as part of the URL or in a form input
            # element, and will be sent back in a Content-Disposition header.
            # Different browsers use various character sets for this name,
            # sometimes depending upon how language environment is
            # configured. Firefox sends the equivalent of
            # urllib.quote(name.encode("utf-8")), while IE7 sometimes does
            # latin-1. Browsers cannot agree on how to interpret the name
            # they see in the Content-Disposition header either, despite some
            # 11-year old standards (RFC2231) that explain how to do it
            # properly. So we assume that at least the browser will agree
            # with itself, and echo back the same bytes that we were given.
            filename = get_arg(req, "filename", self.name) or "unknown"
            d = self.node.get_best_readable_version()
            d.addCallback(lambda dn: FileDownloader(dn, filename))
            return d
        if t == "json":
            # We do this to make sure that fields like size and
            # mutable-type (which depend on the file on the grid and not
            # just on the cap) are filled in. The latter gets used in
            # tests, in particular.
            #
            # TODO: Make it so that the servermap knows how to update in
            # a mode specifically designed to fill in these fields, and
            # then update it in that mode.
            if self.node.is_mutable():
                d = self.node.get_servermap(MODE_READ)
            else:
                d = defer.succeed(None)
            if self.parentnode and self.name:
                d.addCallback(lambda ignored:
                    self.parentnode.get_metadata_for(self.name))
            else:
                d.addCallback(lambda ignored: None)
            d.addCallback(lambda md: FileJSONMetadata(ctx, self.node, md))
            return d
        if t == "info":
            return MoreInfo(self.node)
        if t == "uri":
            return FileURI(ctx, self.node)
        if t == "readonly-uri":
            return FileReadOnlyURI(ctx, self.node)
        raise WebError("GET file: bad t=%s" % t)
开发者ID:tahoe-lafs,项目名称:tahoe-lafs,代码行数:57,代码来源:filenode.py


示例6: ManifestStreamer

class ManifestStreamer(dirnode.DeepStats):
    implements(IPushProducer)

    def __init__(self, ctx, origin):
        dirnode.DeepStats.__init__(self, origin)
        self.req = IRequest(ctx)

    def setMonitor(self, monitor):
        self.monitor = monitor
    def pauseProducing(self):
        pass
    def resumeProducing(self):
        pass
    def stopProducing(self):
        self.monitor.cancel()

    def add_node(self, node, path):
        dirnode.DeepStats.add_node(self, node, path)
        d = {"path": path,
             "cap": node.get_uri()}

        if IDirectoryNode.providedBy(node):
            d["type"] = "directory"
        elif IFileNode.providedBy(node):
            d["type"] = "file"
        else:
            d["type"] = "unknown"

        v = node.get_verify_cap()
        if v:
            v = v.to_string()
        d["verifycap"] = v or ""

        r = node.get_repair_cap()
        if r:
            r = r.to_string()
        d["repaircap"] = r or ""

        si = node.get_storage_index()
        if si:
            si = base32.b2a(si)
        d["storage-index"] = si or ""

        j = simplejson.dumps(d, ensure_ascii=True)
        assert "\n" not in j
        self.req.write(j+"\n")

    def finish(self):
        stats = dirnode.DeepStats.get_results(self)
        d = {"type": "stats",
             "stats": stats,
             }
        j = simplejson.dumps(d, ensure_ascii=True)
        assert "\n" not in j
        self.req.write(j+"\n")
        return ""
开发者ID:david415,项目名称:tahoe-lafs,代码行数:56,代码来源:directory.py


示例7: locateChild

 def locateChild(self, context, segments):
     """
     Unwrap the wrapped resource if HTTPS is already being used, otherwise
     wrap it in a helper which will preserve the wrapping all the way down
     to the final resource.
     """
     request = IRequest(context)
     if request.isSecure():
         return self.wrappedResource, segments
     return _SecureWrapper(self.urlGenerator, self.wrappedResource), segments
开发者ID:fusionapp,项目名称:mantissa,代码行数:10,代码来源:web.py


示例8: renderHTTP

 def renderHTTP(self, context):
     """
     Render the wrapped resource if HTTPS is already being used, otherwise
     invoke a helper which may generate a redirect.
     """
     request = IRequest(context)
     if request.isSecure():
         renderer = self.wrappedResource
     else:
         renderer = _SecureWrapper(self.urlGenerator, self.wrappedResource)
     return renderer.renderHTTP(context)
开发者ID:fusionapp,项目名称:mantissa,代码行数:11,代码来源:web.py


示例9: setETag

 def setETag(self, ctx, t):
     """Set the ETag on the response. If this matches a conditional
     request, return True to short-circuit the request"""
     req = IRequest(ctx)
     if not self.node.is_mutable():
         # If the client already has the ETag then we can
         # short-circuit the whole process.
         si = self.node.get_storage_index()
         if si and req.setETag('CHK:%s-%s' % (base32.b2a(si), t or "")):
             return True
     return False
开发者ID:jsgf,项目名称:tahoe-lafs,代码行数:11,代码来源:filenode.py


示例10: render_PUT

    def render_PUT(self, ctx):
        req = IRequest(ctx)
        t = get_arg(req, "t", "").strip()
        replace = parse_replace_arg(get_arg(req, "replace", "true"))

        assert self.parentnode and self.name
        if req.getHeader("content-range"):
            raise WebError("Content-Range in PUT not yet supported", http.NOT_IMPLEMENTED)
        if not t:
            return self.replace_me_with_a_child(req, self.client, replace)
        if t == "uri":
            return self.replace_me_with_a_childcap(req, self.client, replace)

        raise WebError("PUT to a file: bad t=%s" % t)
开发者ID:p-static,项目名称:tahoe-lafs,代码行数:14,代码来源:filenode.py


示例11: locateChild

    def locateChild(self, context, segments):
        """
        Delegate dispatch to a sharing resource if the request is for a user
        subdomain, otherwise fall back to the wrapped resource's C{locateChild}
        implementation.
        """
        request = IRequest(context)
        hostname = request.getHeader('host')

        info = self.subdomain(hostname)
        if info is not None:
            username, domain = info
            index = UserIndexPage(IRealm(self.siteStore),
                                  self.webViewer)
            resource = index.locateChild(None, [username])[0]
            return resource, segments
        return self.wrapped.locateChild(context, segments)
开发者ID:fusionapp,项目名称:mantissa,代码行数:17,代码来源:_webutil.py


示例12: renderHTTP

 def renderHTTP(self, ctx):
     req = IRequest(ctx)
     if req.method == 'GET':
         req.setHeader('Content-Type', 'text/plain')
         return 'PUT data here to create an object.'
     elif req.method == 'PUT':
         return self.handlePUT(req)
     else:
         req.setResponseCode(http.NOT_ALLOWED)
         req.setHeader('Content-Type', 'text/plain')
         return 'Method not allowed'
开发者ID:fusionapp,项目名称:entropy,代码行数:11,代码来源:store.py


示例13: __init__

 def __init__(self, ctx, origin):
     dirnode.DeepStats.__init__(self, origin)
     self.req = IRequest(ctx)
开发者ID:LeastAuthority,项目名称:tahoe-lafs,代码行数:3,代码来源:directory.py


示例14: simple

 def simple(self, ctx, text, code=http.BAD_REQUEST):
     req = IRequest(ctx)
     req.setResponseCode(code)
     #req.responseHeaders.setRawHeaders("content-encoding", [])
     #req.responseHeaders.setRawHeaders("content-disposition", [])
     req.setHeader("content-type", "text/plain;charset=utf-8")
     if isinstance(text, unicode):
         text = text.encode("utf-8")
     req.setHeader("content-length", str(len(text)))
     req.write(text)
     # TODO: consider putting the requested URL here
     req.finishRequest(False)
开发者ID:gnusosa,项目名称:tahoe-lafs,代码行数:12,代码来源:common.py


示例15: text_plain

def text_plain(text, ctx):
    req = IRequest(ctx)
    req.setHeader("content-type", "text/plain")
    req.setHeader("content-length", len(text))
    return text
开发者ID:gnusosa,项目名称:tahoe-lafs,代码行数:5,代码来源:common.py


示例16: render_OPTIONS

    def render_OPTIONS(self, ctx):
        """
        Handle HTTP OPTIONS request by adding appropriate headers.

        :param ctx: client transaction from which request is extracted
        :returns: str (empty)
        """
        req = IRequest(ctx)
        req.setHeader("server", "Tahoe-LAFS gateway")
        methods = ', '.join([m[7:] for m in dir(self) if m.startswith('render_')])
        req.setHeader("allow", methods)
        req.setHeader("public", methods)
        req.setHeader("compliance", "rfc=2068, rfc=2616")
        req.setHeader("content-length", 0)
        return ""
开发者ID:tahoe-lafs,项目名称:tahoe-lafs,代码行数:15,代码来源:common.py


示例17: renderHTTP

    def renderHTTP(self, ctx):
        req = IRequest(ctx)
        gte = static.getTypeAndEncoding
        ctype, encoding = gte(self.filename,
                              static.File.contentTypes,
                              static.File.contentEncodings,
                              defaultType="text/plain")
        req.setHeader("content-type", ctype)
        if encoding:
            req.setHeader("content-encoding", encoding)

        if boolean_of_arg(get_arg(req, "save", "False")):
            # tell the browser to save the file rather display it we don't
            # try to encode the filename, instead we echo back the exact same
            # bytes we were given in the URL. See the comment in
            # FileNodeHandler.render_GET for the sad details.
            req.setHeader("content-disposition",
                          'attachment; filename="%s"' % self.filename)

        filesize = self.filenode.get_size()
        assert isinstance(filesize, (int,long)), filesize
        first, size = 0, None
        contentsize = filesize
        req.setHeader("accept-ranges", "bytes")

        # TODO: for mutable files, use the roothash. For LIT, hash the data.
        # or maybe just use the URI for CHK and LIT.
        rangeheader = req.getHeader('range')
        if rangeheader:
            ranges = self.parse_range_header(rangeheader)

            # ranges = None means the header didn't parse, so ignore
            # the header as if it didn't exist.  If is more than one
            # range, then just return the first for now, until we can
            # generate multipart/byteranges.
            if ranges is not None:
                first, last = ranges[0]

                if first >= filesize:
                    raise WebError('First beyond end of file',
                                   http.REQUESTED_RANGE_NOT_SATISFIABLE)
                else:
                    first = max(0, first)
                    last = min(filesize-1, last)

                    req.setResponseCode(http.PARTIAL_CONTENT)
                    req.setHeader('content-range',"bytes %s-%s/%s" %
                                  (str(first), str(last),
                                   str(filesize)))
                    contentsize = last - first + 1
                    size = contentsize

        req.setHeader("content-length", b"%d" % contentsize)
        if req.method == "HEAD":
            return ""

        finished = []
        def _request_finished(ign):
            finished.append(True)
        req.notifyFinish().addBoth(_request_finished)

        d = self.filenode.read(req, first, size)

        def _finished(ign):
            if not finished:
                req.finish()
        def _error(f):
            lp = log.msg("error during GET", facility="tahoe.webish", failure=f,
                         level=log.UNUSUAL, umid="xSiF3w")
            if finished:
                log.msg("but it's too late to tell them", parent=lp,
                        level=log.UNUSUAL, umid="j1xIbw")
                return
            req._tahoe_request_had_error = f # for HTTP-style logging
            if req.startedWriting:
                # The content-type is already set, and the response code has
                # already been sent, so we can't provide a clean error
                # indication. We can emit text (which a browser might
                # interpret as something else), and if we sent a Size header,
                # they might notice that we've truncated the data. Keep the
                # error message small to improve the chances of having our
                # error response be shorter than the intended results.
                #
                # We don't have a lot of options, unfortunately.
                req.write("problem during download\n")
                req.finish()
            else:
                # We haven't written anything yet, so we can provide a
                # sensible error message.
                eh = MyExceptionHandler()
                eh.renderHTTP_exception(ctx, f)
        d.addCallbacks(_finished, _error)
        return req.deferred
开发者ID:tahoe-lafs,项目名称:tahoe-lafs,代码行数:93,代码来源:filenode.py


示例18: DeepCheckStreamer

class DeepCheckStreamer(dirnode.DeepStats):

    def __init__(self, ctx, origin, verify, repair, add_lease):
        dirnode.DeepStats.__init__(self, origin)
        self.req = IRequest(ctx)
        self.verify = verify
        self.repair = repair
        self.add_lease = add_lease

    def setMonitor(self, monitor):
        self.monitor = monitor
    def pauseProducing(self):
        pass
    def resumeProducing(self):
        pass
    def stopProducing(self):
        self.monitor.cancel()

    def add_node(self, node, path):
        dirnode.DeepStats.add_node(self, node, path)
        data = {"path": path,
                "cap": node.get_uri()}

        if IDirectoryNode.providedBy(node):
            data["type"] = "directory"
        elif IFileNode.providedBy(node):
            data["type"] = "file"
        else:
            data["type"] = "unknown"

        v = node.get_verify_cap()
        if v:
            v = v.to_string()
        data["verifycap"] = v or ""

        r = node.get_repair_cap()
        if r:
            r = r.to_string()
        data["repaircap"] = r or ""

        si = node.get_storage_index()
        if si:
            si = base32.b2a(si)
        data["storage-index"] = si or ""

        if self.repair:
            d = node.check_and_repair(self.monitor, self.verify, self.add_lease)
            d.addCallback(self.add_check_and_repair, data)
        else:
            d = node.check(self.monitor, self.verify, self.add_lease)
            d.addCallback(self.add_check, data)
        d.addCallback(self.write_line)
        return d

    def add_check_and_repair(self, crr, data):
        data["check-and-repair-results"] = json_check_and_repair_results(crr)
        return data

    def add_check(self, cr, data):
        data["check-results"] = json_check_results(cr)
        return data

    def write_line(self, data):
        j = json.dumps(data, ensure_ascii=True)
        assert "\n" not in j
        self.req.write(j+"\n")

    def finish(self):
        stats = dirnode.DeepStats.get_results(self)
        d = {"type": "stats",
             "stats": stats,
             }
        j = json.dumps(d, ensure_ascii=True)
        assert "\n" not in j
        self.req.write(j+"\n")
        return ""
开发者ID:LeastAuthority,项目名称:tahoe-lafs,代码行数:76,代码来源:directory.py



注:本文中的nevow.inevow.IRequest类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python livepage.handler函数代码示例发布时间:2022-05-27
下一篇:
Python flatsax.parseString函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap