123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180 |
- import os
- import requests
- from flask import jsonify, request, url_for, send_file
- from werkzeug.utils import secure_filename
- from app import app, utils
- #from app.models import init_db, TestRunTask
- import uuid
- from rq.job import Job
- #from baangt.base.DataBaseORM import TestrunLog, DATABASE_URL
- from baangt.base.DataBaseORM import engine, TestrunLog
- from sqlalchemy.orm import sessionmaker
- import datetime
- import pickle
- from baangt.base.ExportResults.ExportResults import ExportResults
- from baangt.base.PathManagement import ManagedPaths
- #db_session = init_db()
- @app.route('/')
- def index():
- return 'Welcome to baangt API service'
- @app.route(f'/{app.config["API_BASE"]}/run/<string:input_format>', methods=['POST'])
- def run_xlsx(input_format):
- #
- # runs Testrun defined in posted json or xlsx file 'testrun'
- #
- # validate input format
- if not input_format in ['xlsx', 'json']:
- app.logger.error(f'Test Run: unsupported input format requested: {input_format}')
- return jsonify({'error': 'Invalid input format.'}), 400
- # default json Testrun definition
- testRunDict = None
- globalsDict = None
- # process JSON input
- if input_format == 'json':
- app.logger.info('Test Run: processing JSON input')
- data = request.get_json()
- if data is None:
- app.logger.error('The request does not contain JSON TestRun')
- return jsonify({'error': 'The request does not contain JSON TestRun.'}), 400
- name = data['name']
- testRunName = utils.validateTestrunName(data.get('name'))
- testRunDict = data.get('testrun')
- globalsDict = data.get('globals')
- app.logger.info(f'Test Run Read: name "{testRunName}", definition {"+" if testRunDict else None}, globals {"+" if globalsDict else None}')
- # proces XLSX input
- if input_format == 'xlsx':
- app.logger.info('Test Run: processing XLSX input')
- try:
- xlsx = request.files.get('testrun')
- # get filename and save file
- filename = secure_filename(xlsx.filename)
- testRunName = os.path.join(os.path.abspath(os.path.dirname(__file__)), app.config['UPLOAD_FOLDER'], filename)
- xlsx.save(testRunName)
- except Exception as e:
- app.logger.error(f'Unable to process input: {e}')
- return jsonify({'error': f'{e}'}), 400
- # generate UUID
- testRunUUID = uuid.uuid4()
- # queue job
- job = app.task_queue.enqueue(
- 'app.tasks.run_testrun',
- testRunName=testRunName,
- globalSettings=globalsDict,
- testRunDict=testRunDict,
- testRunId=testRunUUID,
- job_id=str(testRunUUID),
- )
- app.logger.info(f'Test Run queued: {testRunUUID}')
- return jsonify({'id': str(job.get_id())}), 202
- @app.route(f'/{app.config["API_BASE"]}/results/json/<string:uuid_str>')
- def get_testrun(uuid_str):
- #
- # returns results of the specified Testrun as JSON
- #
- app.logger.info(f'Testrun results requested: {uuid_str}')
- jsonResponse = {'id': uuid_str}
- # get TestrunLog from DB
- session = sessionmaker(bind=engine)()
- log = session.query(TestrunLog).get(uuid.UUID(uuid_str).bytes)
- if log:
- # Tetsrun completed and saved to DB
- jsonResponse.update(log.to_json())
- app.logger.info('Testrun results successfully fetched')
- return jsonify(jsonResponse), 200
- # get task status
- try:
- job = Job.fetch(uuid_str, connection=app.redis)
- app.logger.info(f'Testrun job status: {job.get_status()}')
- if job.get_status() == 'finished':
- jsonResponse['error'] = 'Failed to save results.'
- return jsonify(jsonResponse), 400
- if job.get_status() == 'failed':
- app.logger.error(f'Failed to finish Testrun: {job.exc_info}')
- jsonResponse['error'] = f'Failed to finish Testrun.'
- return jsonify(jsonResponse), 400
- except Exception as e:
- app.logger.error(f'{e}')
- jsonResponse['error'] = 'Testrun does not exist! If you are running it on your local system then please wait for completion of the run.'
- return jsonify(jsonResponse), 202
- return jsonify(jsonResponse), 202
-
- @app.route(f'/{app.config["UPLOAD_FOLDER"]}/<string:filename>')
- def uploads(filename):
- #
- # returns files from 'uploads'
- #
- filename_splitted = filename.split('.')
- if len(filename_splitted) > 1:
- if filename_splitted[-1].lower == 'json':
- return send_file(
- '/'.join((app.config['UPLOAD_FOLDER'], filename)),
- mimetype='application/json',
- )
-
- return send_file(
- '/'.join((app.config['UPLOAD_FOLDER'], filename)),
- attachment_filename=filename,
- as_attachment=True,
- mimetype='application/vnd.ms-excel',
- )
- return send_file(
- '/'.join((app.config['UPLOAD_FOLDER'], filename)),
- attachment_filename=f'{filename}.xlsx',
- as_attachment=True,
- mimetype='application/vnd.ms-excel',
- )
- @app.route(f'/{app.config["API_BASE"]}/results/update/<string:testRunId>', methods=["POST"])
- def update_testRunResult(testRunId):
- data = request.get_json(testRunId)
- ordt = data.copy()
- try:
- session = sessionmaker(bind=engine)()
- #data["id"] = uuid.UUID(data["id"]).bytes
- tr = TestrunLog(
- id = uuid.UUID(data["id"]).bytes,
- testrunName = data["testrunName"],
- logfileName = data["logfileName"],
- startTime = datetime.datetime.now(),
- endTime = datetime.datetime.now(),
- dataFile = data["dataFile"],
- statusOk = data["statusOk"],
- statusFailed = data["statusFailed"],
- statusPaused = data["statusPaused"],
- RLPJson = data["RLPJson"],
- )
- session.add(tr)
- session.commit()
- return jsonify({"update": "success"}), 200
- except Exception as ex:
- dat = {"ex": str(ex), "data": ordt}
- return jsonify(dat), 200
- @app.route(f"/exportresults", methods=["POST"])
- def export_result():
- try:
- data = pickle.loads(request.data)
- data["TESTRUNINSTANCE"].managedPaths = ManagedPaths()
- results = ExportResults(**data)
- return send_file(results.fileName, attachment_filename=results.fileName, mimetype='application/vnd.ms-excel', as_attachment=True), 200
- except Exception as ex:
- data = {"results": str(ex)}
- return jsonify(data), 200
|