首页 > 开发 > HTML > 正文

用Python实现的HTTP服务器无法显示图片

2017-09-09 13:57:17  来源: 网友分享
# -.- coding:utf-8 -.-'''Created on 2011-11-19@author: icejoywoo'''import socketimport datetime# 初始化sockets = socket.socket()# 获取主机名, 也可以使用localhost#host = socket.gethostname()host = "localhost"# 默认的http协议端口号port = 80# 绑定服务器socket的ip和端口号s.bind((host, port))# 服务器名字/版本号server_name = "MyServerDemo/0.1"# 缓存时间, 缓存一天expires = datetime.timedelta(days=1)# GMT时间格式GMT_FORMAT = '%a, %d %b %Y %H:%M:%S GMT'# 相应网页的内容content = '''<html><head><title>MyServerDemo/0.1</title></head><body><h1>Hello, World!</h1><img src="python.jpg" /></body></html>'''#f = open("index.html")#content = f.read()#print content# 可同时连接五个客户端s.listen(5)# 提示信息print "You can see a HelloWorld from this server in ur browser, type in", host, "\r\n"# 服务器循环while True:    # 等待客户端连接    c, addr = s.accept()    print "Got connection from", addr, "\r\n"    # 显示请求信息    print "--Request Header:"    # 接收浏览器的请求, 不作处理    data = c.recv(1024)    print data    # 获得请求的时间    now = datetime.datetime.utcnow()    # 相应头文件和内容    response = '''HTTP/1.1 200 OKServer: %sDate: %sExpires: %sContent-Type: text/html;charset=utf8Content-Length: %sConnection: keep-alive%s''' % (server_name,now.strftime(GMT_FORMAT),(now + expires).strftime(GMT_FORMAT),len(content),content)    # 发送回应    c.send(response)    print "--Response:\r\n", response    c.close()

我感觉问题应该是出在content和response上,
其中

content = '''<html><head><title>MyServerDemo/0.1</title></head><body><h1>Hello, World!</h1><img src="python.jpg" /></body></html>'''
response = '''HTTP/1.1 200 OK    Server: %s    Date: %s    Expires: %s    Content-Type: text/html;charset=utf8    Content-Length: %s    Connection: keep-alive    %s''' % (    server_name,    now.strftime(GMT_FORMAT),    (now + expires).strftime(GMT_FORMAT),    len(content),    content    )

用firebug调试时,显示结果是载入指定url失败,但python.jpg跟这个.py文件在同一目录下,怎么会无法读取呢?

解决方案

找到解决方案了,先读取图片,再直接嵌入到HTML中

data_uri = open('python.jpg', 'rb').read().encode('base64').replace('\n', '')content = '''<html><head><title>MyServerDemo/0.1</title></head><body><h1>Hello, World!</h1><img src="data:image/jpg;base64,{0}" /></body></html>'''.format(data_uri)

之前的做法需要两次GET,这种做法只用一次就行了
难道是这个原因?