app.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import socket
  2. from api import create_app
  3. from pathlib import Path
  4. import yaml
  5. def get_local_ip():
  6. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  7. sock.connect(('8.8.8.8', 80)) # Google DNS 服务器
  8. ip_address = sock.getsockname()[0]
  9. sock.close()
  10. return ip_address
  11. current_file_path = Path(__file__).resolve()
  12. base_dir = current_file_path.parent
  13. config_path = base_dir / "config/config.yaml"
  14. class ConfigMap(dict):
  15. __setattr__ = dict.__setitem__
  16. __getattr__ = dict.__getitem__
  17. with open(str(config_path), mode='r', encoding='utf-8') as fd:
  18. data = yaml.load(fd, Loader=yaml.FullLoader)
  19. _config = data.get(data.get("CurrentConfig", "DevelopmentConfig"))
  20. config = ConfigMap()
  21. for k, v in _config.items():
  22. config[k] = v
  23. config['base_dir'] = base_dir
  24. database = _config.get("database")
  25. if database:
  26. if database.get("type") == "sqlite":
  27. database_uri = f'sqlite:///{base_dir}/{database.get("path")}'
  28. elif database.get("type") == "mysql":
  29. database_uri = f'mysql+pymysql://{database.get("user")}:{database.get("password")}@{database.get("host")}:{database.get("port")}/{database.get("database")}?'
  30. else:
  31. database_uri = ''
  32. config['SQLALCHEMY_DATABASE_URI'] = database_uri
  33. ip_address = get_local_ip()
  34. port = config.get("PORT", 5559)
  35. # 配置 SERVER_NAME
  36. config['SERVER_NAME'] = f'{ip_address}:5559'
  37. # 配置 APPLICATION_ROOT
  38. config['APPLICATION_ROOT'] = '/'
  39. # 配置 PREFERRED_URL_SCHEME
  40. config['PREFERRED_URL_SCHEME'] = 'http'
  41. app = create_app(config)
  42. if __name__ == '__main__':
  43. app.run(host="0.0.0.0", port=port, debug=config.get("DEBUG", False))