xscanserver.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #!-*-coding:utf-8 -*-
  2. import os
  3. import sys
  4. import time
  5. import socket
  6. import signal
  7. import json
  8. import logging
  9. import inspect
  10. import winerror
  11. import win32event
  12. import win32service
  13. import servicemanager
  14. import win32serviceutil
  15. from threading import Thread
  16. from tornado.ioloop import IOLoop
  17. from tornado.wsgi import WSGIContainer
  18. from tornado.httpserver import HTTPServer
  19. from flask_cors import *
  20. from flask import Flask,request,make_response,jsonify
  21. from config import *
  22. from parsedocx import QuestionsParser
  23. from docconvert import DocxConverter
  24. from mergepdf2html import pdf2html
  25. #from twainscan import get_source_names,start_scan
  26. app = Flask(__name__)
  27. CORS(app,supports_credentials=True)
  28. @app.route('/parsedocx.aspx',methods=["POST"])
  29. def parsedocx():
  30. """
  31. """
  32. try:
  33. fobj = request.files['file']
  34. if not os.path.exists(root):
  35. os.makedirs(root)
  36. docxname = os.path.join(root,str(int(time.time()*1000))+os.path.splitext(fobj.filename)[-1])
  37. with open(docxname,"wb+") as doc:
  38. doc.write(fobj.read())
  39. #docxconv = DocxConverter(docxname)
  40. #pdffile = docxconv.docx2pdf()
  41. #html = pdf2html(pdffile)
  42. html = "C:\\AppData\\say365\\htmp\\510f7327-81cd-4498-8668-e67464ba561f.html"
  43. parser = QuestionsParser(html)
  44. questions = parser.get_questions()
  45. #os.remove(html)
  46. res = make_response(jsonify(questions))
  47. return res
  48. res = json.dumps(questions)
  49. return res
  50. except Exception as e:
  51. xlog.error(e)
  52. return str(e)
  53. #@app.route('/xscanSourceList.aspx',methods=["GET"])
  54. #def xscanSourceList():
  55. # """
  56. # """
  57. # snames = get_source_names()
  58. # res = make_response(jsonify(snames))
  59. # return res
  60. #@app.route('/xscanAction.aspx',methods=["GET"])
  61. #def xscanAction():
  62. # """
  63. # """
  64. # try:
  65. # t = Thread(target = start_scan)
  66. # t.start()
  67. # return "success"
  68. # except Exception as e:
  69. # xlog.error(e)
  70. # return str(e)
  71. def main():
  72. try:
  73. #app.run(host='0.0.0.0', port=8002, debug=True)
  74. s = HTTPServer(WSGIContainer(app))
  75. s.listen(19882)
  76. IOLoop.instance().start()
  77. except KeyboardInterrupt:
  78. IOLoop.instance().stop()
  79. class XscanService(win32serviceutil.ServiceFramework):
  80. #服务名
  81. _svc_name_ = "XscanService"
  82. #服务在windows系统中显示的名称
  83. _svc_display_name_ = "XscanService"
  84. #服务的描述
  85. _svc_description_ = "XscanService"
  86. def __init__(self, args):
  87. win32serviceutil.ServiceFramework.__init__(self, args)
  88. self.stop_event = win32event.CreateEvent(None, 0, 0, None)
  89. socket.setdefaulttimeout(60) # 套接字设置默认超时时间
  90. self.logger = self._getLogger() # 获取日志对象
  91. self.isAlive = True
  92. def _getLogger(self):
  93. # 设置日志功能
  94. logger = logging.getLogger('[XscanService]')
  95. this_file = inspect.getfile(inspect.currentframe())
  96. dirpath = os.path.abspath(os.path.dirname(this_file))
  97. handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
  98. formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  99. handler.setFormatter(formatter)
  100. logger.addHandler(handler)
  101. logger.setLevel(logging.INFO)
  102. return logger
  103. def SvcDoRun(self):
  104. # 把自己的代码放到这里,就OK
  105. # 等待服务被停止
  106. #self.main()
  107. #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
  108. while self.isAlive:
  109. self.logger.info("服务正在运行...")
  110. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  111. result = sock.connect_ex(('127.0.0.1', 19882)) # 嗅探网址是否可以访问,成功返回0,出错返回错误码
  112. if result != 0:
  113. # Python3.8的asyncio改变了循环方式,因为这种方式在windows上不支持相应的add_reader APIs,就会抛出NotImplementedError错误。
  114. # 因此加入下面两行代码
  115. #if sys.platform == 'win32':
  116. # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  117. self.main()
  118. sock.close()
  119. time.sleep(20)
  120. def main(self):
  121. try:
  122. #app.run(host='0.0.0.0', port=8002, debug=True)
  123. s = HTTPServer(WSGIContainer(app))
  124. s.listen(19882)
  125. IOLoop.current().start()
  126. except KeyboardInterrupt:
  127. IOLoop.instance().stop()
  128. sys.exit(0)
  129. def SvcStop(self):
  130. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 先告诉SCM停止这个过程
  131. win32event.SetEvent(self.stop_event) # 设置事件
  132. self.ReportServiceStatus(win32service.SERVICE_STOPPED) # 确保停止,也可不加
  133. self.isAlive = False
  134. if __name__=='__main__':
  135. #if len(sys.argv) == 1:
  136. # try:
  137. # evtsrc_dll = os.path.abspath(servicemanager.__file__)
  138. # servicemanager.PrepareToHostSingle(XscanService)
  139. # servicemanager.Initialize('XscanService', evtsrc_dll)
  140. # servicemanager.StartServiceCtrlDispatcher()
  141. # except win32service.error, details:
  142. # if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
  143. # win32serviceutil.usage()
  144. #else:
  145. # win32serviceutil.HandleCommandLine(XscanService)
  146. try:
  147. main()
  148. except KeyboardInterrupt:
  149. sys.exit()