javascriptpythonflaskcloudhosting

Internal Server Error when hosting flask web app


I am trying to host a flask web app on a hosting platform. So far I have tried to host on vercel and pythonanywhere, and I seem to run into the same issue with both. The code runs fine locally but on the cloud it gives me an Internal Server Error (500)

The code is long but ill try to shorten it up here. This is my flask app:

from flask import Flask, request, jsonify, Response, send_from_directory, render_template
from flask_cors import CORS
import pandas as pd
import io, os, time


app = Flask(__name__, static_folder='static', template_folder='templates')
CORS(app)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/process', methods=['POST'])
def process_file():
    try:
        type_id = int(request.form.get('buttonID'))
        
        uploaded_file = request.files['file']
        input_filename = uploaded_file.filename
        uploaded_file.save(input_filename)
                        
        output_filename = process_file(input_filename)
        
        file_extension = os.path.splitext(output_filename)[1].lower()
        if file_extension == '.csv':
            mimetype = 'text/csv'
        elif file_extension in ['.xls', '.xlsx']:
            mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
        else:
            return jsonify({"error": "Unsupported output file format"}), 400
        
        with open(output_filename, 'rb') as f:
            file_contents = f.read()
        
        return Response(
            file_contents,
            mimetype=mimetype,
            headers={"Content-Disposition": f"attachment;filename={output_filename}"}
        )
        
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/static/<path:path>')
def send_static(path):
    return send_from_directory('static', path)

The process_file function is defined, and it just creates the processed spreadsheet file in the directory and returns its name

This is my script.js (shortened):

async function handleSubmit() {
  if (!selectedButton) {
    document.getElementById('process-warning').style.display = 'block';
    return;
  }

  if (!fileForProcessing) {
    console.error("No file selected.");
    return;
  }


  const formData = new FormData();
  formData.append('file', fileForProcessing);
  formData.append('buttonID', selectedButton);

  try {
    const response = await fetch(`${window.location.origin}/process`, {
      method: 'POST',
      body: formData
    });

    if (response.status === 200) {
      newFileData = await response.arrayBuffer();
      recvdFile = true;

    }
  } catch (error) {
    console.error(`Error: ${error}`);
  } finally {
    document.getElementById('spinner').style.display = 'none';
    document.getElementById('processing-incomplete').style.display = 'none';
  }
}

The error occurs specifically on this line: const response = await fetch(`${window.location.origin}/process`, {

This happens when I press a submit button and the handleSubmit() function is called

At first I thought it was an issue with vercel, since the program works great locally, so I tried python anywhere, but I get the same issue. Ive been trying to figure out where this issue occurs, but the console just says Internal Server Error and gives me no leads.

Any way I could resolve this? TIA


Solution

  • Managed to solve the issue on my own, turns out I was missing openpyxl. Despite doing pip freeze, the library wasn't added to my list of dependencies in the requirements file.