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

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

# -.- coding:utf-8 -.-
'''
Created on 2011-11-19

@author: icejoywoo
'''
import socket
import datetime
# 初始化socket
s = 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 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
)
    # 发送回应
    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文件在同一目录下,怎么会无法读取呢?


当然,你需要根据GET请求判断请求的路径,然后查找文件,不存在返回404界面,存在的话,先将他们读取为bytes,然后判断一下content-type(这个必须的,不然客户端肯定不能正常识别),然后先发送头,再发送刚刚得到的bytes,ok~~~


找到解决方案了,先读取图片,再直接嵌入到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,这种做法只用一次就行了
难道是这个原因?

【热门文章】
【热门文章】