#!-*-coding:utf-8 -*- import twain import traceback import uuid import sys,os import locale import SocketServer import BaseHTTPServer import re import json from Queue import Queue from threading import Thread from multiprocessing import Process from threading import Thread reload(sys) sys.setdefaultencoding("utf-8") root = "c:\\AppData\\Xscanner" xqueue = Queue() class XHttpHandler(BaseHTTPServer.BaseHTTPRequestHandler): """ """ def do_HEAD(self): """Serve a HEAD request.""" self.send_response(200) self.send_header("Access-Control-Allow-Origin","*") self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE,HEAD") self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type") self.send_header("Content-Type","application/json;charset=UTF-8") self.end_headers() def read_local_file(self,path): f = open(path,'rb') read = f.read() f.close() #print path return read def send_response(self, code, message=None): """Send the response header and log the response code. Also send two standard headers with the server software version and the current date. """ self.log_request(code) if message is None: if code in self.responses: message = self.responses[code][0] else: message = '' if self.request_version != 'HTTP/0.9': self.wfile.write("%s %d %s\r\n" % (self.protocol_version, code, message)) self.send_header('Date', self.date_time_string()) def do_GET(self): """ """ if self.path.split("?")[0] == '/xscanAction.aspx': print self.path try: id = int(re.search(r"tid=(.*)",self.path).groups()[0]) except Exception as e: id = None print e if id: t = Thread(target = start_scan) t.start() self.send_response(200) self.send_header("Content-Type","text/html;charset=UTF-8") self.end_headers() self.wfile.write("success") if self.path.split("?")[0] == '/xscanSourceList.aspx': snames = get_source_names() self.send_response(200) self.send_header("Access-Control-Allow-Origin","*") self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE") self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type") self.send_header("Content-Type","application/json;charset=UTF-8") self.end_headers() self.wfile.write(json.dumps(snames)) if self.path.split("?")[0] == '/xscanImgUri.aspx': imgs = [] while True: if not xqueue.empty(): imgs.append(xqueue.get(block=False)) continue break img = ",".join(imgs) self.send_response(200) self.send_header("Access-Control-Allow-Origin","*") self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE") self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type") self.send_header("Content-Type","application/json;charset=UTF-8") self.end_headers() self.wfile.write(img) if self.path.split("?")[0] == '/xscanImgReview.aspx': try: imgid = re.search(r"imgid=(.*)",self.path).groups()[0] except Exception as e: imgid = None print e imgpath = os.path.join(root,imgid) content = self.read_local_file(imgpath) self.send_response(200) self.send_header("Access-Control-Allow-Origin","*") self.send_header("Access-Control-Allow-Methods","POST, GET, OPTIONS, DELETE") self.send_header("Access-Control-Allow-Headers","x-requested-with,content-type") self.send_header("Content-Type","image/png") #self.send_header("Content-Type","application/json;charset=UTF-8") self.end_headers() self.wfile.write(content) if self.path == '/': self.path = "index.html" def server(): try: addr = len(sys.argv) < 2 and "localhost" or sys.argv[1] port = len(sys.argv) < 3 and 19882 or locale.atoi(sys.argv[2]) handler = XHttpHandler httpd = SocketServer.TCPServer((addr, port), handler) print ("HTTP server is at: http://%s:%d/" % (addr, port)) httpd.serve_forever() except KeyboardInterrupt: sys.exit() def get_source_names(): """ """ try: sm = twain.SourceManager(0) return sm.GetSourceList() except Exception as e: return [] def start_scan(): try: sm = twain.SourceManager(0) ss = sm.OpenSource("AT360") ss.RequestAcquire(0,0) try: if not os.path.exists(root): os.makedirs(root) while True: try: rv = ss.XferImageNatively() if rv is None: break else: (handle, count) = rv imgname = '{}.png'.format(uuid.uuid4()) imgfile = os.path.join(root,imgname) twain.DIBToBMFile(handle, imgfile) xqueue.put(imgname) except: traceback.print_exc() break except: traceback.print_exc() print "Error!" except Exception: return False,u"找不到扫描仪!" if __name__ == "__main__": server()