def __init__(self, template_string, name="<string>", loader=None, compress_whitespace=None, autoescape=_UNSET): self.name = name if compress_whitespace is None: compress_whitespace = name.endswith(".html") or \ name.endswith(".js") if autoescape is not _UNSET: self.autoescape = autoescape elif loader: self.autoescape = loader.autoescape else: self.autoescape = _DEFAULT_AUTOESCAPE self.namespace = loader.namespace if loader else {} reader = _TemplateReader(name, escape.native_str(template_string)) self.file = _File(self, _parse(reader, self)) self.code = self._generate_python(loader, compress_whitespace) self.loader = loader try: # Under python2.5, the fake filename used here must match # the module name used in __name__ below. self.compiled = compile( escape.to_unicode(self.code), "%s.generated.py" % self.name.replace('.', '_'), "exec") except Exception: log.err("%s code:" % self.name) for line in _format_code(self.code).rstrip().split("\n"): log.err(line) raise
def __init__(self, template_string, name="<string>", loader=None, compress_whitespace=None, autoescape=_UNSET): self.name = name if compress_whitespace is None: compress_whitespace = name.endswith(".html") or \ name.endswith(".js") if autoescape is not _UNSET: self.autoescape = autoescape elif loader: self.autoescape = loader.autoescape else: self.autoescape = _DEFAULT_AUTOESCAPE self.namespace = loader.namespace if loader else {} reader = _TemplateReader(name, escape.native_str(template_string)) try: self.file = _File(self, _parse(reader, self)) self.code = self._generate_python(loader, compress_whitespace) except ParseError as e: raise TemplateError("Error parsing template %s, line %d: %s" % (name, reader.line, str(e))) self.loader = loader try: # Under python2.5, the fake filename used here must match # the module name used in __name__ below. self.compiled = compile( escape.to_unicode(self.code), "%s.generated.py" % self.name.replace('.', '_'), "exec") except Exception: raise TemplateError("Error compiling template " + name + ":\n" + _format_code(self.code).rstrip())
def __init__(self, template_string, name="<string>", loader=None, compress_whitespace=None, autoescape=_UNSET): self.name = name if compress_whitespace is None: compress_whitespace = name.endswith(".html") or \ name.endswith(".js") if autoescape is not _UNSET: self.autoescape = autoescape elif loader: self.autoescape = loader.autoescape else: self.autoescape = _DEFAULT_AUTOESCAPE self.namespace = loader.namespace if loader else {} reader = _TemplateReader(name, escape.native_str(template_string)) self.file = _File(self, _parse(reader, self)) self.code = self._generate_python(loader, compress_whitespace) self.loader = loader try: # Under python2.5, the fake filename used here must match # the module name used in __name__ below. self.compiled = compile( escape.to_unicode(self.code), "%s.generated.py" % self.name.replace('.', '_'), "exec") except Exception: formatted_code = _format_code(self.code).rstrip() log.msg("%s code:" % self.name) for line in formatted_code.split("\n"): log.msg(line) raise
def _on_headers(self, data): try: eol = data.find(b"\r\n") start_line = data[:eol] try: method, uri, version = start_line.split(b" ") except ValueError: raise _BadRequestException("Malformed HTTP request line") if not version.startswith(b"HTTP/"): raise _BadRequestException( "Malformed HTTP version in HTTP Request-Line") try: headers = httputil.HTTPHeaders.parse(to_unicode(data[eol:])) content_length = int(headers.get("Content-Length", 0)) except ValueError: raise _BadRequestException("Malformed HTTP headers") self._request = HTTPRequest(connection=self, method=to_unicode(method), uri=to_unicode(uri), version=to_unicode(version), headers=headers, remote_ip=to_unicode(self._remote_ip)) if content_length: if headers.get("Expect") == "100-continue": self.transport.write(b"HTTP/1.1 100 (Continue)\r\n\r\n") if content_length < 100000: self._contentbuffer = StringIO() else: self._contentbuffer = TemporaryFile() self.content_length = content_length self.setRawMode() return self.request_callback(self._request) except _BadRequestException as e: log.msg("Malformed HTTP request from %s: %s", self._remote_ip, e) self.transport.loseConnection()
def parse_multipart_form_data(boundary, data, arguments, files): """Parses a multipart/form-data body. The boundary and data parameters are both byte strings. The dictionaries given in the arguments and files parameters will be updated with the contents of the body. """ # The standard allows for the boundary to be quoted in the header, # although it's rare (it happens at least for google app engine # xmpp). I think we're also supposed to handle backslash-escapes # here but I'll save that until we see a client that uses them # in the wild. if boundary.startswith(b'"') and boundary.endswith(b'"'): boundary = boundary[1:-1] final_boundary_index = data.rfind(b"--" + boundary + b"--") if final_boundary_index == -1: log.msg("Invalid multipart/form-data: no final boundary") return parts = data[:final_boundary_index].split(b"--" + boundary + b"\r\n") for part in parts: if not part: continue eoh = part.find(b"\r\n\r\n") if eoh == -1: log.msg("multipart/form-data missing headers") continue headers = HTTPHeaders.parse(to_unicode(part[:eoh])) disp_header = headers.get("Content-Disposition", "") disposition, disp_params = _parse_header(disp_header) if disposition != "form-data" or not part.endswith(b"\r\n"): log.msg("Invalid multipart/form-data") continue value = part[eoh + 4:-2] if not disp_params.get("name"): log.msg("multipart/form-data value missing name") continue name = disp_params["name"] if disp_params.get("filename"): ctype = headers.get("Content-Type", "application/unknown") files.setdefault(name, []).append( HTTPFile(filename=disp_params["filename"], body=value, content_type=ctype)) else: arguments.setdefault(name, []).append(value)
def test_to_unicode(self): self.assertEqual(to_unicode("rawr"), u"rawr") self.assertEqual(to_unicode(u"rawr"), u"rawr")