remote.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. from pathlib import Path
  2. from flask import request, Flask
  3. from flask_cors import CORS
  4. from datetime import datetime
  5. import pyodbc
  6. import subprocess
  7. app = Flask(__name__)
  8. # cors = CORS(app, resources={r"/*": {"origins": "http://localhost:4200/"}})
  9. CORS(app)
  10. script_dir = Path(__file__).parent
  11. batch_dir = script_dir.joinpath('../batch').resolve()
  12. print(batch_dir)
  13. tasks_dir = script_dir.joinpath('../../Tasks').resolve()
  14. if not tasks_dir.exists():
  15. tasks_dir = script_dir.joinpath('../../Portal/Tasks').resolve()
  16. print(tasks_dir)
  17. # batch_dir = Path('C:/GAPS/GCStarter/batch')
  18. # path2 = Path('C:/GAPS/Portal/Tasks')
  19. @app.route('/', methods=['GET', 'POST'])
  20. def main():
  21. if request.args.get('valid') != '1':
  22. return "Funktioniert!"
  23. if request.args.get('gchr') is not None:
  24. return gchr()
  25. log = request.args.get('log')
  26. if log is not None:
  27. return logs(log)
  28. filename = request.args.get('batch', 'GCStarter.bat')
  29. return batch(filename)
  30. @app.route('/gchr/', methods=['POST'])
  31. def gchr():
  32. dsn = request.form.get('dsn')
  33. query = request.form.get('query')
  34. if dsn is None or query is None:
  35. return 'Fehler: fehlende Parameter'
  36. return fetch_query_as_csv(dsn[5:], query)
  37. def fetch_query_as_csv(dsn, query):
  38. try:
  39. conn = pyodbc.connect(dsn)
  40. cursor = conn.cursor()
  41. cursor.execute(query)
  42. return "\r\n".join([";".join(map(str, row)) for row in cursor.fetchall()])
  43. except pyodbc.InterfaceError as e:
  44. print(e.args[1])
  45. return e.args[1], 422
  46. @app.route('/logs/<log>')
  47. def logs(log):
  48. logfile = batch_dir.joinpath('logs/' + log)
  49. if not logfile.exists():
  50. return f"Fehler: Datei '{log}' unbekannt"
  51. with open(logfile, 'r') as f:
  52. return f.read()
  53. @app.route('/batch/<filename>')
  54. def batch(filename):
  55. cmd = batch_dir.joinpath(filename)
  56. if not cmd.exists():
  57. cmd = tasks_dir.joinpath(filename)
  58. if not cmd.exists():
  59. return f"Fehler: Datei '{filename}' unbekannt"
  60. log = filename[:-4] + '_' + datetime.now().strftime('%Y%m%d_%H%M%S') + '.log'
  61. logfile = batch_dir.joinpath('logs/' + log)
  62. with open(logfile, 'wb') as stream:
  63. if filename != 'GCStarter.bat':
  64. stream.write(b'Starte Prozess...')
  65. cmd = str(cmd) + ' & echo Prozess beendet. & echo [.]'
  66. subprocess.Popen(f'C:\\Windows\\System32\\cmd.exe /C "{cmd}"', stdout=stream, stderr=stream)
  67. # p.wait()
  68. return log
  69. if __name__ == '__main__':
  70. app.run(host='0.0.0.0', port='8091')