xscanserver - 副本.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. #!-*-coding:utf-8 -*-
  2. import os
  3. import sys
  4. import time
  5. import socket
  6. import json
  7. import logging
  8. import inspect
  9. import winerror
  10. import win32event
  11. import win32service
  12. import servicemanager
  13. import win32serviceutil
  14. from flask import Flask,request
  15. from tornado.ioloop import IOLoop
  16. from tornado.wsgi import WSGIContainer
  17. from tornado.httpserver import HTTPServer
  18. from parsedocx import DocxConverter,QuestionsParser
  19. app = Flask(__name__)
  20. @app.route('/parsedocx',methods=["POST"])
  21. def parsedocx():
  22. """
  23. """
  24. fobj = request.files['file']
  25. root = "c:\\AppData\\say365"
  26. if not os.path.exists(root):
  27. os.makedirs(root)
  28. docxname = os.path.join(root,str(int(time.time()*1000))+os.path.splitext(fobj.filename)[-1])
  29. with open(docxname,"wb+") as doc:
  30. doc.write(fobj.read())
  31. docxconv = DocxConverter(docxname)
  32. html = docxconv.docx2html()
  33. parser = QuestionsParser(html)
  34. questions = parser.get_questions()
  35. return json.dumps(questions)
  36. def main():
  37. #app.run(host='0.0.0.0', port=8002, debug=True)
  38. s = HTTPServer(WSGIContainer(app))
  39. s.listen(8002)
  40. IOLoop.current().start()
  41. class XsacnService(win32serviceutil.ServiceFramework):
  42. #服务名
  43. _svc_name_ = "XsacnService"
  44. #服务在windows系统中显示的名称
  45. _svc_display_name_ = "XsacnService"
  46. #服务的描述
  47. _svc_description_ = "XsacnService"
  48. def __init__(self, args):
  49. win32serviceutil.ServiceFramework.__init__(self, args)
  50. self.stop_event = win32event.CreateEvent(None, 0, 0, None)
  51. socket.setdefaulttimeout(60) # 套接字设置默认超时时间
  52. self.logger = self._getLogger() # 获取日志对象
  53. self.isAlive = True
  54. def _getLogger(self):
  55. # 设置日志功能
  56. logger = logging.getLogger('[PythonService]')
  57. this_file = inspect.getfile(inspect.currentframe())
  58. dirpath = os.path.abspath(os.path.dirname(this_file))
  59. handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
  60. formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
  61. handler.setFormatter(formatter)
  62. logger.addHandler(handler)
  63. logger.setLevel(logging.INFO)
  64. return logger
  65. def SvcDoRun(self):
  66. # 把自己的代码放到这里,就OK
  67. # 等待服务被停止
  68. #self.main()
  69. #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
  70. while self.isAlive:
  71. self.logger.info("服务正在运行...")
  72. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  73. result = sock.connect_ex(('127.0.0.1', 8002)) # 嗅探网址是否可以访问,成功返回0,出错返回错误码
  74. if result != 0:
  75. # Python3.8的asyncio改变了循环方式,因为这种方式在windows上不支持相应的add_reader APIs,就会抛出NotImplementedError错误。
  76. # 因此加入下面两行代码
  77. #if sys.platform == 'win32':
  78. # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
  79. main()
  80. sock.close()
  81. time.sleep(20)
  82. def SvcStop(self):
  83. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 先告诉SCM停止这个过程
  84. win32event.SetEvent(self.stop_event) # 设置事件
  85. self.ReportServiceStatus(win32service.SERVICE_STOPPED) # 确保停止,也可不加
  86. self.isAlive = False
  87. if __name__=='__main__':
  88. main()