码迷,mamicode.com
首页 > 编程语言 > 详细

利用python BaseHTTPServer 开发的图片浏览小工具

时间:2015-01-05 10:48:59      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

最近从网上爬了点图片,为了方便浏览就写了这么个小工具。直接上码,解释偏少,代码没有优化,实现比较简略。仅作记录之用。

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 style=" list-style:none"><img src=" + path + / + str(f) + " alt=" + str(f) + " width="1400" height="+ height +"/></li><br/><br/>
 69                     elif height == 1:
 70                         content += <li style=" list-style:none"><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)编码保存

利用python BaseHTTPServer 开发的图片浏览小工具

标签:

原文地址:http://www.cnblogs.com/hgd7123/p/4202780.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!