123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171 |
- #!-*-coding:utf-8 -*-
- import os
- import sys
- import time
- import socket
- import signal
- import json
- import logging
- import inspect
- import winerror
- import win32event
- import win32service
- import servicemanager
- import win32serviceutil
- from threading import Thread
- from tornado.ioloop import IOLoop
- from tornado.wsgi import WSGIContainer
- from tornado.httpserver import HTTPServer
- from flask_cors import *
- from flask import Flask,request,make_response,jsonify
- from config import *
- from parsedocx import QuestionsParser
- from docconvert import DocxConverter
- from mergepdf2html import pdf2html
- #from twainscan import get_source_names,start_scan
- app = Flask(__name__)
- CORS(app,supports_credentials=True)
- @app.route('/parsedocx.aspx',methods=["POST"])
- def parsedocx():
- """
- """
- try:
- fobj = request.files['file']
- 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)
- #pdffile = docxconv.docx2pdf()
- #html = pdf2html(pdffile)
- html = "C:\\AppData\\say365\\htmp\\510f7327-81cd-4498-8668-e67464ba561f.html"
- parser = QuestionsParser(html)
- questions = parser.get_questions()
- #os.remove(html)
- res = make_response(jsonify(questions))
- return res
- res = json.dumps(questions)
- return res
- except Exception as e:
- xlog.error(e)
- return str(e)
-
- #@app.route('/xscanSourceList.aspx',methods=["GET"])
- #def xscanSourceList():
- # """
- # """
- # snames = get_source_names()
- # res = make_response(jsonify(snames))
- # return res
-
- #@app.route('/xscanAction.aspx',methods=["GET"])
- #def xscanAction():
- # """
- # """
- # try:
- # t = Thread(target = start_scan)
- # t.start()
- # return "success"
- # except Exception as e:
- # xlog.error(e)
- # return str(e)
-
- def main():
- try:
- #app.run(host='0.0.0.0', port=8002, debug=True)
- s = HTTPServer(WSGIContainer(app))
- s.listen(19882)
- IOLoop.instance().start()
- except KeyboardInterrupt:
- IOLoop.instance().stop()
-
- class XscanService(win32serviceutil.ServiceFramework):
- #服务名
- _svc_name_ = "XscanService"
- #服务在windows系统中显示的名称
- _svc_display_name_ = "XscanService"
- #服务的描述
- _svc_description_ = "XscanService"
-
- 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('[XscanService]')
- 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', 19882)) # 嗅探网址是否可以访问,成功返回0,出错返回错误码
- if result != 0:
- # Python3.8的asyncio改变了循环方式,因为这种方式在windows上不支持相应的add_reader APIs,就会抛出NotImplementedError错误。
- # 因此加入下面两行代码
- #if sys.platform == 'win32':
- # asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
- self.main()
- sock.close()
- time.sleep(20)
-
- def main(self):
- try:
- #app.run(host='0.0.0.0', port=8002, debug=True)
- s = HTTPServer(WSGIContainer(app))
- s.listen(19882)
- IOLoop.current().start()
- except KeyboardInterrupt:
- IOLoop.instance().stop()
- sys.exit(0)
-
- 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__':
- #if len(sys.argv) == 1:
- # try:
- # evtsrc_dll = os.path.abspath(servicemanager.__file__)
- # servicemanager.PrepareToHostSingle(XscanService)
- # servicemanager.Initialize('XscanService', evtsrc_dll)
- # servicemanager.StartServiceCtrlDispatcher()
- # except win32service.error, details:
- # if details[0] == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
- # win32serviceutil.usage()
- #else:
- # win32serviceutil.HandleCommandLine(XscanService)
- try:
- main()
- except KeyboardInterrupt:
- sys.exit()
-
|