Python HTTP服务器载入指定url失败图片不能正常显示怎么破,,# -.- coding
Python HTTP服务器载入指定url失败图片不能正常显示怎么破,,# -.- coding
# -.- 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,这种做法只用一次就行了
难道是这个原因?
当然,你需要根据GET请求判断请求的路径,然后查找文件,不存在返回404界面,存在的话,先将他们读取为bytes,然后判断一下content-type(这个必须的,不然客户端肯定不能正常识别),然后先发送头,再发送刚刚得到的bytes,ok~~~
编橙之家文章,
相关内容
- Python父子进程开启与挂起问题求助,python问题求助,需要
- Python Crypto.PublicKey这个包应该怎么安装?,,信息如下:
- Python爬知乎登陆可以通过cookies绕过验证码吗,pythonco
- 求大牛知道http post多并发设置python 2.7环境,python2.7,注
- Python抓取通过电影名称获取视频地址,python电影名称
- 请问特殊符号在cmd中要如何输出呢?,特殊符号cmd输出
- except和finally可以同时在try中使用吗,exceptfinally,try:
- 重新安装yum报ImportError: No module named sqlitecachec错误是何
- Python可以同时控制两个显示屏幕输出吗?,python显示屏幕
- 关于Python修饰类@class的求助,Python修饰类@class,看到文章
评论关闭