我正在用python编写一个简单的been服务器,并且成功地做到了这一点。我能够在javascript文件中呈现html页面,但无法呈现图像。
一些相关的代码,
def createResponse(self, data):#, last_modified=0):
# print data
response_code = data[0]
mimetype = data[1][1]
data = data[1][0] # (200, (data, mimetype))
res = "HTTP/1.0 " + self.config['STATUS_STRING'][str(response_code)] + "\r\n"
res += "Content-Type: " + mimetype + "\r\n"
res += "Date: " + strftime("%a, %d %b %Y %X GMT", gmtime()) + "\r\n"
# if last_modified:
# res += "Last Modified: " + last_modified + "\r\n"
res += 'Server: ' + self.config['SERVER_NAME'] + "\r\n"
res += 'Connection: close' + '\r\n' # signal that the conection wil be closed after complting the request
res += "\r\n"
res += data
return res.encode("utf8")
def _handleGET(self, path):
# some stuff, then
# File exists and read permission, so give file
try:
fp = open(filepath, "rb")
except IOError as e:
if e.errno == errno.EACCES:
return (500, self._readFile(self.config['ERROR_DIR'] + '/' + str(500) + ".html"));
# Not a permission error.
raise
else:
with fp:
return (200, (fp.read().decode("utf8"), mimetypes.guess_type(filepath)[0])) # return (200,(data,mimetype))我为客户端创建一个套接字,并使用以下方式返回响应,
clientSocket.sendall(self.createResponse(self._handleGET(data)))我用utf8编码整个响应,这是一个字符串。这适用于html页面和js文件,以及css文件,但不适用于图像。(巴布亚新几内亚、gif等)我尝试设置头部和编码图像响应的base64二进制等,但我无法做到这一点。
utf8中,而图像的内容将以其他编码方式呈现。所以他们不能连在一起。如果我错了,请纠正我。发布于 2016-04-07 09:08:21
http的头没有编码,应该是纯ASCII。内容部分是任何二进制数据。对于文本,可以在Content-Type中指定编码。因此,createResponse必须单独处理文本和二进制数据,可能使用显式编码参数:
def create_response(self, content, response_code=200, mimetype='text/html', encoding='UTF-8', additional_params=None):
header_params = {
'Content-Type', '%s; charset=%s' %(mimetype, encoding) if encoding else mimetype,
'Date': strftime("%a, %d %b %Y %X GMT", gmtime()),
'Server': self.config['SERVER_NAME'],
'Connection': 'close',
}
if additional_params:
header_params.update(additional_params)
if encoding:
content = content.encode(encoding)
header = "HTTP/1.0 %s\r\n%s\r\n" % (
self.config['STATUS_STRING'][str(response_code)],
''.join('%s: %s\r\n' % kv for kv in header_params.iteritems())
)
return header.encode('utf8') + content与下列一起使用:
with fp:
return self.create_response(fp.read(), mime_type=mimetypes.guess_type(filepath)[0], encoding=None)https://stackoverflow.com/questions/36459857
复制相似问题