首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >响应自定义python web-server中的png图像

响应自定义python web-server中的png图像
EN

Stack Overflow用户
提问于 2016-04-06 18:49:01
回答 1查看 1.5K关注 0票数 1

我正在用python编写一个简单的been服务器,并且成功地做到了这一点。我能够在javascript文件中呈现html页面,但无法呈现图像。

一些相关的代码,

代码语言:javascript
复制
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))

我为客户端创建一个套接字,并使用以下方式返回响应,

代码语言:javascript
复制
clientSocket.sendall(self.createResponse(self._handleGET(data)))

我用utf8编码整个响应,这是一个字符串。这适用于html页面和js文件,以及css文件,但不适用于图像。(巴布亚新几内亚、gif等)我尝试设置头部和编码图像响应的base64二进制等,但我无法做到这一点。

  • 对怎么做有什么建议吗?
  • 这是否可能,因为现在我认为不可能使用此方法呈现图像,因为头部将在utf8中,而图像的内容将以其他编码方式呈现。所以他们不能连在一起。如果我错了,请纠正我。
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-07 09:08:21

http的头没有编码,应该是纯ASCII。内容部分是任何二进制数据。对于文本,可以在Content-Type中指定编码。因此,createResponse必须单独处理文本和二进制数据,可能使用显式编码参数:

代码语言:javascript
复制
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

与下列一起使用:

代码语言:javascript
复制
    with fp:
        return self.create_response(fp.read(), mime_type=mimetypes.guess_type(filepath)[0], encoding=None)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36459857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档