# -*- coding: utf-8 -*-
"""
FileName: response
Author: Tao Hao
@contact: taohaohust@outlook.com
Created time: 2019/5/29
Description:
Changelog:
"""
from multidict import CIMultiDict
from httpserver.utils import remove_entity_headers, STATUS_CODES
class HTTPResponse(object):
def __init__(self, body=None,
status=200, headers=None,
content_type="text/plain", body_bytes=b""):
self.content_type = content_type
self.headers = headers
if body is not None:
self.body = self.encode_body(body)
else:
self.body = body_bytes
self.status = status
self.headers = CIMultiDict(headers or {})
def encode_body(self, data):
try:
return data.encode()
except AttributeError:
return str(data).encode()
def parse_headers(self):
headers = b""
for key, value in self.headers.items():
try:
headers += b"%b: %b\r\n" % (key.encode(), value.encode("utf-8"))
except AttributeError:
headers += b"%b: %b\r\n" % (
str(key).encode(), str(value).encode("utf-8")
)
return headers
def has_message_body(self):
"""
According to the following RFC message body and length SHOULD NOT
be included in responses status 1XX, 204 and 304.
https://tools.ietf.org/html/rfc2616#section-4.4
https://tools.ietf.org/html/rfc2616#section-4.3
"""
return self.status not in (204, 304) and not (100