def write_line(self, line, line_number, indent=None): if indent is None: indent = self._indent line_comment = ' # %s:%d' % (self.current_template.name, line_number) if self.include_stack: ancestors = ["%s:%d" % (tmpl.name, lineno) for (tmpl, lineno) in self.include_stack] line_comment += ' (via %s)' % ', '.join(reversed(ancestors)) print(" " * indent + escape.utf8(line) + escape.utf8(line_comment), file=self.file)
def get_response_headers_string(self, first_line): """生成响应头,并加上最后的两个CRLF""" _headers_string = escape.utf8(first_line) for _name, _value_list in self._headers_map_list.items(): for _value in _value_list: _header_line = "{name}: {value}".format( name = _name, value = _value) _headers_string += (CRLF + escape.utf8(_header_line)) return _headers_string + CRLF * 2
def parse_multipart_form_data(content_type, body, args, files): boundary = escape.utf8(content_type.split('boundary=')[-1]) end_index = body.rfind(b'--' + boundary + b'--') if end_index == -1: # 如果没有结尾符的话,则说明这个主体格式是错误的 gen_log.error('Invalid multipart/form-data: no final boundary') return parts = body[:end_index].split(b'--' + boundary + CRLF) for _part in parts: if not _part: continue _args_part, _body_part = _part.split(CRLF * 2)[:2] body = _body_part[:-2] headers = HTTPHeaders._parse_headers(_args_part) # 这里的headers是指某一个数据块的头部信息 con_dis = headers.get(b'Content-Disposition', None) if not con_dis: gen_log.error('must have Content-Disposition') return con_dis = parse_content_disposition(con_dis) name = escape.to_unicode(con_dis[b'name']) if b'filename' in con_dis: # 如果有filename,则表示这是一个文件 filename = con_dis.get(b'filename') if not filename: continue files.setdefault(name, []).append( HTTPFile(filename = escape.to_unicode(filename), body = body, content_type = escape.to_unicode(headers.get(b'Content-Type', 'application/octet-stream')))) else: args.setdefault(name, []).append(escape.to_unicode(body))
def get_best_upstream(self, handler): client_ip = handler.client_ip ip_long = struct.unpack(b'!L', escape.utf8(socket.inet_aton(client_ip)))[0] valid_hosts = self.upstreams_weight.keys() # Monitor the user to modify its own weight request if not valid_hosts: return ip_hash_index = ip_long % len(valid_hosts) return valid_hosts[ip_hash_index]
def get(self, key): key = self.prefix + utf8(key) value = self.db.get(key) if not value: return None value = pickle.loads(value) return value
def origin_is_accept(self): origin = utf8(self.request.get_header('Origin', '')) if not origin: return False origin_host = urlsplit(origin).netloc origin_host = ':' in origin_host and origin_host or (origin_host + ':80') if origin_host != self.request.host + ':' + self.request.port: return False return True
def generate(self, writer): value = self.value # Compress lots of white space to a single character. If the whitespace # breaks a line, have it continue to break a line, but just with a # single \n character if writer.compress_whitespace and "<pre>" not in value: value = re.sub(r"([\t ]+)", " ", value) value = re.sub(r"(\s*\n\s*)", "\n", value) if value: writer.write_line('_tt_append(%r)' % escape.utf8(value), self.line)
def set(self, key, value, expire = None): key = self.prefix + utf8(key) expire = expire or self.expire value = pickle.dumps(value, protocol = 1) pipe = self.db.pipeline() pipe.set(key, value) pipe.expire(key, expire) result_list = pipe.execute() for result in result_list: assert result
def accept(self): response = [ 'HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', 'Sec-WebSocket-Accept: %s' % (generate_response_key(self.websocket_key)), ] response = utf8('\r\n'.join(response) + '\r\n' * 2) self.stream.write(response) self.handler.on_open() while self.closed == False: frame_data = self.recv_frame_data() if frame_data.opcode == 0x1: # 接受text self.handler.on_message(frame_data) elif frame_data.opcode == 0x8: # 关闭 _data = frame_data.data if len(_data) >= 2: self.close_status = struct.unpack(b'!H', _data[:2])[0] if len(_data) > 2: self.close_reason = _data[2:] self.close()
def urlquote(param): return quote_plus(escape.utf8(param))
def _generate_hmac(self, session_id): return hmac.new(utf8(session_id), utf8(self.session_secret), hashlib.sha1).hexdigest()
def _generate_id(self): _id = 'GALE%s' % hashlib.sha1(utf8(self.session_secret) + utf8(str(uuid.uuid4()))).hexdigest() return _id
def send_message(self, chunk): if not is_string(chunk): raise WebSocketError('message type must str or unicode') frame = ObjectDict({'fin': 1, 'data': utf8(chunk), 'opcode': 1}) self._websocket_conn.send_frame_data(frame)
def _generate_key(key, args, kwargs): m = hashlib.md5(utf8(key)) [m.update(utf8(str(arg))) for arg in args] [m.update(utf8("%s=%s" % tuple(item))) for item in kwargs.items()] return m.hexdigest()
def ttl(self, key): key = self.prefix + utf8(key) return self.db.ttl(key) or 0