| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
- #!-*-coding:utf-8 -*-
- import os
- import sys
- import time
- import socket
- import json
- import logging
- import inspect
- import winerror
- import win32event
- import win32service
- import servicemanager
- import win32serviceutil
- from flask import Flask,request
- from tornado.ioloop import IOLoop
- from tornado.wsgi import WSGIContainer
- from tornado.httpserver import HTTPServer
- from parsedocx import DocxConverter,QuestionsParser
- app = Flask(__name__)
- @app.route('/parsedocx',methods=["POST"])
- def parsedocx():
- """
- """
- fobj = request.files['file']
- root = "c:\\AppData\\say365"
- if not os.path.exists(root):
- os.makedirs(root)
- docxname = os.path.join(root,str(int(time.time()*1000))+os.path.splitext(fobj.filename)[-1])
- with open(docxname,"wb+") as doc:
- doc.write(fobj.read())
- docxconv = DocxConverter(docxname)
- html = docxconv.docx2html()
- parser = QuestionsParser(html)
- questions = parser.get_questions()
- return json.dumps(questions)
- def main():
- #app.run(host='0.0.0.0', port=8002, debug=True)
- s = HTTPServer(WSGIContainer(app))
- s.listen(8002)
- IOLoop.current().start()
-
- class XsacnService(win32serviceutil.ServiceFramework):
- #服务名
- _svc_name_ = "XsacnService"
- #服务在windows系统中显示的名称
- _svc_display_name_ = "XsacnService"
- #服务的描述
- _svc_description_ = "XsacnService"
-
- def __init__(self, args):
- win32serviceutil.ServiceFramework.__init__(self, args)
- self.stop_event = win32event.CreateEvent(None, 0, 0, None)
- socket.setdefaulttimeout(60) # 套接字设置默认超时时间
- self.logger = self._getLogger() # 获取日志对象
- self.isAlive = True
-
- def _getLogger(self):
- # 设置日志功能
- logger = logging.getLogger('[PythonService]')
- this_file = inspect.getfile(inspect.currentframe())
- dirpath = os.path.abspath(os.path.dirname(this_file))
- handler = logging.FileHandler(os.path.join(dirpath, "service.log"))
- formatter = logging.Formatter('%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
- handler.setFormatter(formatter)
- logger.addHandler(handler)
- logger.setLevel(logging.INFO)
- return logger
-
- def SvcDoRun(self):
- # 把自己的代码放到这里,就OK
- # 等待服务被停止
- #self.main()
- #win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
- while self.isAlive:
- self.logger.info("服务正在运行...")
- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- result = sock.connect_ex(('127.0.0.1', 8002)) # 嗅探网址是否可以访问,成功返回0,出错返回错误码
- if result != 0:
- # Python3.8的asyncio改变了循环方式,因为这种方式在windows上不支持相应的add_reader APIs,就会抛出NotImplementedError错误。
- # 因此加入下面两行代码
- #if sys.platform == 'win32':
- # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
- main()
- sock.close()
- time.sleep(20)
-
- def SvcStop(self):
- self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # 先告诉SCM停止这个过程
- win32event.SetEvent(self.stop_event) # 设置事件
- self.ReportServiceStatus(win32service.SERVICE_STOPPED) # 确保停止,也可不加
- self.isAlive = False
-
-
- if __name__=='__main__':
- main()
|