GMTROM/REST/old/app2.py

75 lines
2.9 KiB
Python
Raw Permalink Normal View History

import subprocess
import json
import time
from flask import Flask, request, jsonify
from I2C_Function import analyze_data, read_data
from flask_cors import CORS
from threading import Lock
app = Flask(__name__)
CORS(app)
initialized = False
lock = Lock() # Sperre (Lock) für die analyze_data-Methode
@app.route('/trng/randomNum/init', methods=['GET'])
def initialize_generator():
global initialized # Zugriff auf die globale Variable
with lock: # Sperre (Lock) verwenden, um sicherzustellen, dass nur ein Thread die Methode ausführt
if initialized:
return jsonify({'message': 'random number generator already initialized'}), 200
result = analyze_data(int(1), int(1), startup=True)
if result is True:
initialized = True
return jsonify({'message': 'successful operation; random number generator is ready and random numbers can be requested'}), 200
else:
return jsonify({'error': 'Unable to initialize the random number generator within a timeout of 60 seconds.'}), 555
@app.route('/trng/randomNum/getRandom', methods=['GET'])
def get_random_numbers():
global initialized # Zugriff auf die globale Variable
quantity = request.args.get('quantity')
bits = request.args.get('numBits')
if not quantity.isdigit() or not bits.isdigit():
return jsonify({'error': 'Invalid input. Quantity and bits must be numeric.'}), 400
if int(quantity) <= 0 or int(bits) <= 0:
return jsonify({'error': 'Invalid input. Quantity and bits must be positive integers.'}), 400
if not initialized:
return jsonify({'error': 'system not ready; try init'}), 432
with lock: # Sperre (Lock) verwenden, um sicherzustellen, dass nur ein Thread die Methode ausführt
random_numbers = analyze_data(int(quantity), int(bits), startup=False)
if random_numbers is False:
return jsonify({'error': 'Unable to generate random numbers.'}), 500
if random_numbers:
response_data = {
'status': 'successful operation; HEX-encoded bit arrays (with leading zeros if required)',
'randomNumbers': random_numbers
}
return jsonify(response_data), 200
else:
return jsonify({'error': 'Unable to generate random numbers.'}), 500
@app.route('/trng/randomNum/shutdown', methods=['GET'])
def shutdown_generator():
global initialized # Zugriff auf die globale Variable
with lock: # Sperre (Lock) verwenden, um sicherzustellen, dass nur ein Thread die Methode ausführt
initialized = False
return jsonify({'message': "successful operation; random number generator has been set to 'standby mode'"}), 200
if __name__ == '__main__':
cert_path = '/etc/nginx/ssl/cert-gmtrom.pem'
key_path = '/etc/nginx/ssl/cert-gmtrom-key.pem'
app.run(host='0.0.0.0', ssl_context=(cert_path, key_path))