Devanshu-bot

generate-report

Sep 17th, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | Source Code | 0 0
  1. @app.route('/generate-report/<task_id>', methods=['GET'])
  2. def generate_report(task_id):
  3.     # logger.info("Received generate report request for Task ID: %s", task_id)
  4.  
  5.     # Check if the task_id exists in the 'known_tasks' set
  6.     task_exists = redis_client.sismember('known_tasks', task_id)
  7.  
  8.     if not task_exists:
  9.         return jsonify({'state': 'UNKNOWN', 'error': 'Task ID does not exist.'}), 404
  10.  
  11.     task = AsyncResult(task_id, app=celery)
  12.     # logger.info("Task State: %s", task.state)
  13.  
  14.     if task.state == 'SUCCESS':
  15.         result = task.result
  16.         llama_output, merged_buffer = generate_pdf(
  17.             result, result['roi_category'])
  18.  
  19.         if merged_buffer:
  20.             try:
  21.                 # Option 1: Return PDF directly
  22.                 # pdf_buffer = merged_buffer
  23.                 # pdf_buffer.seek(0)  # Ensure buffer is at the beginning
  24.  
  25.                 # return send_file(
  26.                 #     pdf_buffer,
  27.                 #     as_attachment=True,
  28.                 #     download_name='event_report.pdf',
  29.                 #     mimetype='application/pdf'
  30.                 # )
  31.  
  32.                 # Option 2: Return PDF as Base64 (commented out)
  33.  
  34.                 pdf_data = merged_buffer.getvalue()
  35.                 pdf_base64 = base64.b64encode(pdf_data).decode('utf-8')
  36.  
  37.                 response = {
  38.                     'state': task.state,
  39.                     'message': 'Report generated successfully.',
  40.                     'pdf_data': pdf_base64  # Base64-encoded PDF
  41.                 }
  42.                 return jsonify(response), 200
  43.  
  44.             except Exception as e:
  45.                 # logger.exception("Error generating PDF")
  46.                 return jsonify({'error': f'Error generating PDF: {str(e)}'}), 500
  47.         else:
  48.             # logger.error("Merged buffer is empty.")
  49.             return jsonify({'error': 'Failed to generate PDF.'}), 500
  50.  
  51.     elif task.state == 'FAILURE':
  52.         # logger.error("Task Failure: %s", task.info)
  53.         return jsonify({
  54.             'state': task.state,
  55.             'error': str(task.info)
  56.         }), 500
  57.  
  58.     else:
  59.         return jsonify({'state': task.state, 'message': 'Report is not ready yet.'}), 202
Add Comment
Please, Sign In to add comment