From a11be64a6d36b5bb32753f89fe5f0627ff64ed7b Mon Sep 17 00:00:00 2001 From: Karma Riuk Date: Wed, 14 May 2025 16:16:05 +0200 Subject: [PATCH] now validating the input for code refinement --- src/routes/answers.py | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/routes/answers.py b/src/routes/answers.py index b2d6984..2a54079 100644 --- a/src/routes/answers.py +++ b/src/routes/answers.py @@ -25,6 +25,25 @@ def validate_json_format_for_comment_gen(data: str) -> dict[str, str]: raise InvalidJsonFormatError() +def validate_json_format_for_code_refinement(data: str) -> dict[str, dict[str, str]]: + try: + obj = json.loads(data) + if not isinstance(obj, dict): + raise InvalidJsonFormatError("Submitted json doesn't contain an object") + + for _, submission in obj.items(): + if not all(isinstance(content, str) for content in submission.values()): + raise InvalidJsonFormatError( + "Submitted json object must be str -> {str -> str}. Namely id -> {filename -> content of file}" + ) + return obj + + except InvalidJsonFormatError as e: + raise e + except Exception: + raise InvalidJsonFormatError() + + @router.route('/submit/comments', methods=['POST']) def submit_comments(): file = request.files.get('file') @@ -51,5 +70,18 @@ def submit_comments(): @router.route('/submit/refinement', methods=['POST']) def submit_refinement(): file = request.files.get('file') - # similar to above + if file is None or file.filename is None or file.filename.split('.')[-1] not in ALLOWED_EXT: + return jsonify({'error': 'Only JSON files are allowed'}), 400 + data = file.read().decode() + try: + validated = validate_json_format_for_code_refinement(data) + except InvalidJsonFormatError as e: + return jsonify({'error': 'Invalid JSON format', 'message': str(e)}), 400 + + socketio = current_app.extensions['socketio'] + sid = request.headers.get('X-Socket-Id') + if sid: + socketio.emit('successful-upload', room=sid) + socketio.emit('started-processing', room=sid) + return jsonify({'message': 'Answer submitted successfully'})