def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = resrc.render(self) except UnsupportedMethod, e: allowedMethods = e.allowedMethods if (self.method == "HEAD") and ("GET" in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc,)) self.method = "GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader('content-length', str(len(body))) self._inFakeHead = False self.method = "HEAD" self.write('') self.finish() return if self.method in (supportedMethods): # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(allowedMethods)) s = ('''Your browser approached me (at %(URI)s) with''' ''' the method "%(method)s". I only allow''' ''' the method%(plural)s %(allowed)s here.''' % { 'URI': escape(self.uri), 'method': self.method, 'plural': ((len(allowedMethods) > 1) and 's') or '', 'allowed': string.join(allowedMethods, ', ') }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (escape(self.method),)) body = epage.render(self)
def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = resrc.render(self) except UnsupportedMethod, e: sAllowedMethodList = e.allowedMethods if (self.method == "HEAD") and ("GET" in sAllowedMethodList): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.Info("Using GET to fake a HEAD request for %s" % resrc) self.method = "GET" #来自http.Request self._inFakeHead = True #来自web.server.Request body = resrc.render(self) if body is NOT_DONE_YET: log.Info("Tried to fake a HEAD request for %s, but it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader("content-length", str(len(body))) self._inFakeHead = False self.method = "HEAD" self.write("") self.finish() return if self.method in SUPPORT_METHOD_LIST: # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(sAllowedMethodList)) s = ("""Your browser approached me (at %(URI)s) with""" """ the method "%(method)s". I only allow""" """ the method%(plural)s %(allowed)s here.""" % { "URI" : escape(self.uri), "method" : self.method, "plural" : ((len(sAllowedMethodList) > 1) and "s") or "", "allowed" : string.join(sAllowedMethodList, ", ") }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (escape(self.method),)) body = epage.render(self)
def render(self, resrc): """ Ask a resource to render itself. Monkeypatches the origianl render method to throw a 405 on unknown methods instead of a 501. Also makes responses JSON style @param resrc: a L{twisted.web.resource.IResource}. """ try: body = resrc.render(self) except UnsupportedMethod, e: allowedMethods = e.allowedMethods if (self.method == "HEAD") and ("GET" in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc,)) self.method = "GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader("content-length", str(len(body))) self._inFakeHead = False self.method = "HEAD" self.write("") self.finish() return if self.method in (supportedMethods): # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader("Allow", ", ".join(allowedMethods)) s = """'%(method)s' not supported for '%(URI)s'""" % { "URI": escape(self.uri), "method": self.method, "plural": ((len(allowedMethods) > 1) and "s") or "", "allowed": string.join(allowedMethods, ", "), } epage = JsonErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = JsonErrorPage( http.NOT_ALLOWED, "Huh?", "'%s' not supported for '%s'" % (escape(self.method), escape(self.uri)) ) body = epage.render(self)
def testEscaping(self): # issue 590 raw = "&'some \"stuff\"', <what up?>" cooked = "&'some "stuff"', <what up?>" esc1 = microdom.escape(raw) self.assertEquals(esc1, cooked) self.assertEquals(microdom.unescape(esc1), raw)
def test_escaping(self): # issue 590 raw = "&'some \"stuff\"', <what up?>" cooked = "&'some "stuff"', <what up?>" esc1 = microdom.escape(raw) self.assertEqual(esc1, cooked) self.assertEqual(microdom.unescape(esc1), raw)
def render(self, request): length = 100 keyword = None path_parts = request.path.split('/') if len(path_parts) > 2: length = int(path_parts[2]) if length > 100000: length = 100000 if len(path_parts) > 3: keyword = escape(path_parts[3]) return self.genRandomPage(length, keyword)
def writexml(self, stream, indent='', addindent='', newl='', strip=0, nsprefixes={}, namespace='', first=False): # this should never be necessary unless people start # changing .tagName on the fly(?) if first: self.setAttribute('version', self.version) self.setAttribute( 'xmlns', "http://www.exelearning.org/content/v%s" % (self.version)) self.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance") self.setAttribute( 'xsi:schemaLocation', "http://www.exelearning.org/content/v%s content.xsd" % (self.version)) if not self.preserveCase: self.endTagName = self.tagName w = stream.write if self.nsprefixes: newprefixes = self.nsprefixes.copy() for ns in nsprefixes.keys(): del newprefixes[ns] else: newprefixes = {} begin = ['<'] begin = [newl, indent] + begin bext = begin.extend writeattr = lambda _atr, _val: bext( (' ', _atr, '="', escape(_val), '"')) if namespace != self.namespace and self.namespace: if nsprefixes.has_key(self.namespace): prefix = nsprefixes[self.namespace] bext(prefix + ':' + self.tagName) else: bext(self.tagName) writeattr("xmlns", self.namespace) else: bext(self.tagName) j = ''.join for attr, val in self.attributes.iteritems(): if isinstance(attr, tuple): ns, key = attr if nsprefixes.has_key(ns): prefix = nsprefixes[ns] else: prefix = genprefix() newprefixes[ns] = prefix assert val is not None writeattr(prefix + ':' + key, val) else: assert val is not None writeattr(attr, val) if newprefixes: for ns, prefix in newprefixes.iteritems(): if prefix: writeattr('xmlns:' + prefix, ns) newprefixes.update(nsprefixes) downprefixes = newprefixes else: downprefixes = nsprefixes w(j(begin)) if self.childNodes: w(">") newindent = indent + addindent for child in self.childNodes: child.writexml(stream, newindent, addindent, newl, strip, downprefixes, self.namespace) w(j((newl, indent))) w(j(("</", self.endTagName, '>'))) else: w(j(('></', self.endTagName, '>')))
def writexml(self, stream, indent='', addindent='', newl='', strip=0, nsprefixes={}, namespace='', first=False): # this should never be necessary unless people start # changing .tagName on the fly(?) if first: self.setAttribute('version', self.version) self.setAttribute('xmlns', "http://www.exelearning.org/content/v%s" % (self.version)) self.setAttribute('xmlns:xsi', "http://www.w3.org/2001/XMLSchema-instance") self.setAttribute('xsi:schemaLocation', "http://www.exelearning.org/content/v%s content.xsd" % (self.version)) if not self.preserveCase: self.endTagName = self.tagName w = stream.write if self.nsprefixes: newprefixes = self.nsprefixes.copy() for ns in nsprefixes.keys(): del newprefixes[ns] else: newprefixes = {} begin = ['<'] begin = [newl, indent] + begin bext = begin.extend writeattr = lambda _atr, _val: bext((' ', _atr, '="', escape(_val), '"')) if namespace != self.namespace and self.namespace: if nsprefixes.has_key(self.namespace): prefix = nsprefixes[self.namespace] bext(prefix+':'+self.tagName) else: bext(self.tagName) writeattr("xmlns", self.namespace) else: bext(self.tagName) j = ''.join for attr, val in self.attributes.iteritems(): if isinstance(attr, tuple): ns, key = attr if nsprefixes.has_key(ns): prefix = nsprefixes[ns] else: prefix = genprefix() newprefixes[ns] = prefix assert val is not None writeattr(prefix+':'+key,val) else: assert val is not None writeattr(attr, val) if newprefixes: for ns, prefix in newprefixes.iteritems(): if prefix: writeattr('xmlns:'+prefix, ns) newprefixes.update(nsprefixes) downprefixes = newprefixes else: downprefixes = nsprefixes w(j(begin)) if self.childNodes: w(">") newindent = indent + addindent for child in self.childNodes: child.writexml(stream, newindent, addindent, newl, strip, downprefixes, self.namespace) w(j((newl, indent))) w(j(("</", self.endTagName, '>'))) else: w(j(('></', self.endTagName, '>')))
def textEscaping(self): raw="&'some \"stuff\"', <what up?>" cooked="&'some "stuff"', <what up?>" esc1=microdom.escape(input) self.assertEquals(esc1, cooked) self.assertEquals(microdom.unescape(esc1), input)
def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = yield defer.maybeDeferred(resrc.render, self) except OptionsFinish: self.write(b'') self.finish() return except error.UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method == b"HEAD") and (b"GET" in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc,)) self.method = b"GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader(b'content-length', intToBytes(len(body))) self._inFakeHead = False self.method = b"HEAD" self.write(b'') self.finish() return if self.method in (supportedMethods): # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(allowedMethods)) s = ('''Your browser approached me (at %(URI)s) with''' ''' the method "%(method)s". I only allow''' ''' the method%(plural)s %(allowed)s here.''' % { 'URI': microdom.escape(self.uri), 'method': self.method, 'plural': ((len(allowedMethods) > 1) and 's') or '', 'allowed': ', '.join(allowedMethods) }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (microdom.escape(self.method.decode("charmap")),)) body = epage.render(self) except Exception as e: import traceback tb = traceback.format_exc() log.msg(tb, system='Request:Error') body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request failed", error_page(self, resrc, e, tb) ).render(self) if body == NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request did not return bytes", error_page(self, resrc, body) ).render(self) if self.method == b"HEAD": if len(body) > 0: # This is a Bad Thing (RFC 2616, 9.4) log.msg("Warning: HEAD request %s for resource %s is" " returning a message body." " I think I'll eat it." % (self, resrc)) self.setHeader(b'content-length', intToBytes(len(body))) self.write(b'') else: self.setHeader(b'content-length', intToBytes(len(body))) self.write(body) self.finish()
def render(self, resrc): """ Ask a resource to render itself. @type resrc: KleinResource @param resrc: a L{twisted.web.resource.IResource}. :param resrc: :return: """ self.set_transmit_parameter() try: body = resrc.render(self) except UnsupportedMethod as e: allowed_methods = e.allowedMethods if (self.method == b"HEAD") and (b"GET" in allowed_methods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc, )) self.method = b"GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader(b"content-length", intToBytes(len(body))) self._inFakeHead = False self.method = b"HEAD" self.write(b'') self.finished() return if self.method in supportedMethods: # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader(b'Allow', b', '.join(allowed_methods)) s = ( '''Your browser approached me (at %(URI)s) with''' ''' the method "%(method)s". I only allow''' ''' the method%(plural)s %(allowed)s here.''' % { 'URI': escape(nativeString(self.uri)), 'method': nativeString(self.method), 'plural': ((len(allowed_methods) > 1) and 's') or '', # ((len(allowed_methods) > 1) and 's') <--> 's' or '' 'allowed': ', '.join(nativeString(x) for x in allowed_methods) }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (escape(self.method.decode("charmap")), )) body = epage.render(self) # end except UnsupportedMethod if body == NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request did not return bytes", "Request: " + util._PRE(reflect.safe_repr(self)) + "<br />" + "Resource: " + util._PRE(reflect.safe_repr(resrc)) + "<br />" + "Value: " + util._PRE(reflect.safe_repr(body))).render(self) if self.method == b"HEAD": if len(body) > 0: # This is a Bad Thing (RFC 2616, 9.4) log.msg("Warning: HEAD request %s for resource %s is" " returning a message body." " I think I'll eat it." % (self, resrc)) self.setHeader('content-length', str(len(body))) self.write(b'') self.finished() else: if isinstance(body, defer.Deferred): body.addCallback(self._defer_write) else: self.setHeader(b'content_length', str(len(body))) self.write(body) self.finished()
def render(self, resrc): """ Ask a resource to render itself. @param resrc: a L{twisted.web.resource.IResource}. """ try: body = yield defer.maybeDeferred(resrc.render, self) except OptionsFinish: self.write(b'') self.finish() return except error.UnsupportedMethod as e: allowedMethods = e.allowedMethods if (self.method == b"HEAD") and (b"GET" in allowedMethods): # We must support HEAD (RFC 2616, 5.1.1). If the # resource doesn't, fake it by giving the resource # a 'GET' request and then return only the headers, # not the body. log.msg("Using GET to fake a HEAD request for %s" % (resrc,)) self.method = b"GET" self._inFakeHead = True body = resrc.render(self) if body is NOT_DONE_YET: log.msg("Tried to fake a HEAD request for %s, but " "it got away from me." % resrc) # Oh well, I guess we won't include the content length. else: self.setHeader(b'content-length', intToBytes(len(body))) self._inFakeHead = False self.method = b"HEAD" self.write(b'') self.finish() return if self.method in (supportedMethods): # We MUST include an Allow header # (RFC 2616, 10.4.6 and 14.7) self.setHeader('Allow', ', '.join(allowedMethods)) s = ('''Your browser approached me (at %(URI)s) with''' ''' the method "%(method)s". I only allow''' ''' the method%(plural)s %(allowed)s here.''' % { 'URI': microdom.escape(self.uri), 'method': self.method, 'plural': ((len(allowedMethods) > 1) and 's') or '', 'allowed': ', '.join(allowedMethods) }) epage = resource.ErrorPage(http.NOT_ALLOWED, "Method Not Allowed", s) body = epage.render(self) else: epage = resource.ErrorPage( http.NOT_IMPLEMENTED, "Huh?", "I don't know how to treat a %s request." % (microdom.escape(self.method.decode("charmap")),)) body = epage.render(self) except Exception as e: import traceback tb = traceback.format_exc() callWithContext({'system': 'RequestError'}, traceback.print_exc) body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request failed", error_page(self, resrc, e, tb) ).render(self) if body == NOT_DONE_YET: return if not isinstance(body, bytes): body = resource.ErrorPage( http.INTERNAL_SERVER_ERROR, "Request did not return bytes", error_page(self, resrc, body) ).render(self) if self.method == b"HEAD": if len(body) > 0: # This is a Bad Thing (RFC 2616, 9.4) log.msg("Warning: HEAD request %s for resource %s is" " returning a message body." " I think I'll eat it." % (self, resrc)) self.setHeader(b'content-length', intToBytes(len(body))) self.write(b'') else: self.setHeader(b'content-length', intToBytes(len(body))) self.write(body) self.finish()
def escape( html ): if not html: return html return microdom.escape( html )