设为首页 收藏本站
查看: 601|回复: 0

[经验分享] 利用python BaseHTTPServer 开发的图片浏览小工具

[复制链接]

尚未签到

发表于 2015-12-2 11:48:47 | 显示全部楼层 |阅读模式
  最近从网上爬了点图片,为了方便浏览就写了这么个小工具。直接上码,解释偏少,代码没有优化,实现比较简略。仅作记录之用。
  1.httpd.py



1 # encoding: UTF-8
2 #-*-coding:utf-8-*-
3 import BaseHTTPServer
4 import config
5 import urllib
6 from CreatHtml import CreateHtmlClass
7 import os
8
9 #登录页面代码,做个简单的访问权限控制
10 login_html ='''<html>
11 <title>Directory listing for </title>
12 <body>
13 <center>
14 <h2> login</h2>
15 <hr>
16     <form action="/login" method="post">
17     <p>UserName: <input type="text" name="une" /></p>
18     <p>PassWord: <input type="password" name="pwd" /></p>
19     <input type="submit" value="Login" />
20     </form>
21 <hr>
22 </center>
23 </body>
24 </html>'''
25
26
27 ct_obj = CreateHtmlClass()
28
29 class EasyWebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
30     def do_GET(self):
31         #if self.path == '/':
32         print self.client_address
33         #print self.headers
34         if self.headers.has_key("Cookie"):
35             print self.headers["Cookie"]
36             err_code,content_type,content = ct_obj.root_html(self.path)
37             self.send_response(err_code)
38             self.send_header("Content-type", content_type)
39             self.send_header("Content-Length", str(len(content)))
40             self.end_headers()
41             self.wfile.write(content)
42         else:
43             print "not login"
44             self.send_response(200)
45             self.send_header("Content-type", "text/html; charset=utf-8")
46             self.send_header("Content-Length", str(len(login_html)))
47             self.end_headers()
48             self.wfile.write(login_html)
49
50     def do_POST(self):
51         print self.path
52         if self.path == "/login":
53             datas = self.rfile.read(int(self.headers['content-length']))
54             datas = urllib.unquote(datas).decode("utf-8", 'ignore')
55             #datas = transDicts(datas)
56             if datas == "une=xxx&pwd=xxx":
57                 err_code,content_type,content = ct_obj.root_html("/")
58                 self.send_response(err_code)
59                 self.send_header("Content-type", content_type)
60                 self.send_header("Content-Length", str(len(content)))
61                 self.send_header("Set-Cookie","JSESSIONID=JIGUGUJICHACHACHA;Path=/")
62                 self.end_headers()
63                 self.wfile.write(content)
64         else:
65             self.send_response(404)
66             self.send_header("Content-type", "text/html; charset=utf-8")
67             self.send_header("Content-Length", 3)
68             self.end_headers()
69             self.wfile.write("404")
70         
71
72
73 server = BaseHTTPServer.HTTPServer(('',18080),EasyWebRequestHandler)
74 print 'EasyWebServer start...'
75 server.serve_forever()
  2. CreatHtml.py
  



  1 # encoding: UTF-8
  2 #-*-coding:utf-8-*-
  3 import os
  4 import config
  5 from PIL import Image
  6
  7
  8 image_dic = {
  9     'png':'image/png',
10     'jpg':'image/jpeg',
11     'jpeg':'image/jpeg',
12     'bmp':'image/bmp',
13 }
14
15 class CreateHtmlClass:
16     """docstring for CreateHtml"""
17     def __init__(self):
18         self.root = config.root
19
20 #    def check_image(self,path):
21 #        type_pos = path.rfind('.')
22 #        type_str = path[type_pos+1:]
23 #        if not image_dic.has_key( type_str.lower() ):
24 #            return False,0
25 #
26 #        im = Image.open(path)
27 #        width = im.size[0]
28 #        height = im.size[1]
29 #        ratio = width/1400.0
30 #        if  ratio > 1.0 :
31 #            return True,str(int(height/ratio))
32 #        else:
33 #            return False,1
34     def check_image(self,path):
35         type_pos = path.rfind('.')
36         type_str = path[type_pos+1:]
37         if not image_dic.has_key( type_str.lower() ):
38             return False,0
39         try:
40             im = Image.open(path)
41             width = im.size[0]
42             height = im.size[1]
43             ratio = width/1400.0
44             if  ratio > 1.0 :
45                 return True,str(int(height/ratio))
46             else:
47                 return False,1
48         except Exception, e:
49             print e
50             return False,1
51         
52     def creat_dir_html(self,path):
53         if path == '/':
54             path = ""
55         local_path = self.root + path
56         content = ""
57         local_path_about = local_path + '/about.info'
58         if os.path.exists(local_path_about):
59             f = open(local_path_about,'r')
60             h2 = f.readline()
61             f.close()
62
63             content = '<title>Directory listing for '+ h2+'</title><body><center><h2>'+ h2 +'</h2><hr><ul>'
64             for f in os.listdir(local_path):
65                 if str(f) != 'about.info':
66                     is_image,height = self.check_image(local_path + '/' + str(f))
67                     if is_image:
68                         content += '<li><img src="' + path + '/' + str(f) + '" alt="' + str(f) + '" width="1400" height="'+ height +'"/></li><br/><br/>'
69                     elif height == 1:
70                         content += '<li><img src="' + path + '/' + str(f) + '" alt="' + str(f) + '" /></li><br/><br/>'
71             content += '</ul></center><hr></body></html>'
72         else:
73             content = '<title>Directory listing for '+ path+'</title><body><h2>'+ path +' /</h2><hr><ul>'
74             for f in os.listdir(local_path):
75                 content += '<li><a href="' + path + '/' + str(f) + '">' + str(f) + '</a></li>'
76             content += '</ul><hr></body></html>'
77         return content
78
79     def read_local_file(self,path):
80         f = open(path,'rb')
81         read = f.read()
82         f.close()
83         #print path
84         return read
85
86     def write_local_file(self,path,content):
87         f = open(path,'w')
88         f.write(content)
89         f.close()
90
91     def get_dir_html(self,path,refresh_pos):
92         content = None
93         content_type = None
94         error_code = 200
95         local_path = self.root + path
96         path_name_pos = path.rfind('/')
97         path_name = path[path_name_pos+1:]
98         local_path_html = local_path + '/'+path_name+'.html'
99         print local_path_html
100         content_type = "text/html; charset=utf-8"
101         if path == '/' :
102             content = self.creat_dir_html(path)
103         elif refresh_pos == -1 and os.path.exists(local_path_html):
104             content = self.read_local_file(local_path_html)
105         else:
106             content = self.creat_dir_html(path)
107             self.write_local_file(local_path_html,content)
108
109         return error_code,content_type,content
110
111     def get_404_html(self):
112         content = "404"
113         error_code = 404
114         content_type = "text/html; charset=utf-8"
115         return error_code,content_type,content
116
117     def get_file_content(self,path):
118         if path=='/':
119             path = ""
120         local_path = self.root + path
121         type_pos = path.rfind('.')
122         type_str = path[type_pos+1:]
123         content_type = "*/*"
124         print type_str
125         error_code = 200
126         if image_dic.has_key(type_str.lower()):
127             content_type = image_dic[type_str.lower()]
128
129         if os.path.exists(local_path):
130             content = self.read_local_file(local_path)
131         else:
132             return self.get_404_html()
133         return error_code,content_type,content
134
135     def root_html(self,path):
136         refresh_pos = path.find('refresh')
137         if refresh_pos != -1:
138             path = path[0:refresh_pos-1]
139         content = None
140         content_type = None
141         error_code = None
142         local_path = self.root + path
143
144         
145         if os.path.isdir(local_path):
146             error_code,content_type,content = self.get_dir_html(path,refresh_pos)
147         else:
148             error_code,content_type,content = self.get_file_content(path)
149
150         return error_code,content_type,content
  3.config.py



1 # encoding: UTF-8
2 #-*-coding:utf-8-*-
3 root="E:/"
  
  使用细节:
  1.注意在存放图片文件夹内新建一个about.info 的文件,内部填写的是图片简介(utf-8)编码保存

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-146293-1-1.html 上篇帖子: Python自动补全 下篇帖子: 实习小记-python中不可哈希对象设置为可哈希对象
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表