local_file_service.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import threading
  3. import time
  4. from flask import Flask, send_from_directory
  5. import flask
  6. from flask_cors import CORS
  7. from program_public_tools import ProgramPublicTools
  8. class LocalFileService(object):
  9. def __init__(self):
  10. self.filename_list = ["信号发生器.pdf", "直流电源.pdf", "万用表.pdf", "直流电子负载.pdf", "示波器.pdf",
  11. "高压放大器.pdf"]
  12. self.__host = "127.0.0.1"
  13. self.__port = ProgramPublicTools.find_available_server_port(number=1, address=self.__host, start_port=9500)[0]
  14. self.__app = Flask(__name__)
  15. CORS(self.__app)
  16. self.__setup_routes()
  17. self.__thread = None
  18. self.__start_flag: bool = False
  19. def __setup_routes(self):
  20. @self.__app.route("/documents/<filename>")
  21. def route_serve_pdf(filename):
  22. return self.__serve_pdf(filename)
  23. def __serve_pdf(self, filename):
  24. print("========filename: ", filename)
  25. if filename not in self.filename_list:
  26. flask.abort(404)
  27. current_file_path = os.path.realpath(__file__)
  28. current_dir = os.path.dirname(current_file_path)
  29. parent_dir = os.path.dirname(current_dir)
  30. file_path = os.path.join(parent_dir, "source", filename)
  31. print("file_path:", file_path)
  32. if not os.path.isfile(file_path):
  33. flask.abort(404)
  34. return send_from_directory(os.path.dirname(file_path), os.path.basename(file_path))
  35. def __start_flask(self):
  36. self.__app.run(port=self.__port)
  37. def start(self):
  38. if self.__start_flag is False:
  39. self.__start_server()
  40. self.__start_flag = True
  41. return self.get_server_info()
  42. def __start_server(self):
  43. self.__thread = threading.Thread(target=self.__start_flask)
  44. self.__thread.daemon = True
  45. self.__thread.start()
  46. return self.get_server_info()
  47. def get_server_info(self):
  48. return self.__host, self.__port