phpwordpressazureweb-development-server

Azure WebJobs with WordPress WebApp?


I am building a webpage through Azures web app in WordPress. I want to have one of my pages allow the user to upload a file, that file go to a python script which returns and image based on that file back to WordPress for the user to see.

Through mcuh trial and error I am now attempting to use webjobs for this since the python file takes awhile to run. I am very new to azure and web development as my main domain is data science so please be patient.

I am running this on my page to pull the file and access webjob functions -

<!-- wp:html -->
<form id="webjob-form" enctype="multipart/form-data">
<input type="file" id="file" name="file" required>
<button type="submit">Run WebJob</button>
</form>

<div id="output"></div>
<img id="stitched-image" style="max-width: 100%; display: none;" />

<script>
document.getElementById('webjob-form').addEventListener('submit', async (e) => {
e.preventDefault();

const formData = new FormData();
formData.append('file', document.getElementById('file').files[0]);

const response = await fetch('<?php echo admin_url('admin-ajax.php? 
action=trigger_webjob'); ?>', {
    method: 'POST',
    body: formData
});

const result = await response.json();

if (result.success) {
    // Display output or stitched image
    const imageUrl = result.data.match(/https:\/\/[^\s]+/)[0]; // Extract URL from 
response
    document.getElementById('stitched-image').src = imageUrl;
    document.getElementById('stitched-image').style.display = 'block';
} else {
    document.getElementById('output').innerHTML = `<pre style="color: red;">Failed: ${result.data}</pre>`;
}
});
</script>

The in my functions.php File in theme editor I have -

function trigger_webjob_with_file() {
if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $upload_dir = wp_upload_dir()['path'];
    if (!file_exists($upload_dir)) {
          mkdir($upload_dir, 0755, true);
}
    $file_path = $upload_dir . '/' . basename($file['name']);
    
    if (move_uploaded_file($file['tmp_name'], $file_path)) {
        $url = 
'https://omitted.scm.azurewebsites.net/api/triggeredwebjobs/StitchImages/run';
        $username = 'omitted';
        $password = 'omitted';

        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, array(
            'file' => curl_file_create($file_path)
        ));

        $response = curl_exec($curl);
        $error = curl_error($curl);
        curl_close($curl);

        if ($error) {
            wp_send_json_error("Error triggering WebJob: $error");
        } else {
            wp_send_json_success($response); // Return WebJob output to JS
        }
    } else {
        wp_send_json_error('Failed to upload file');
    }
    }
}

add_action('wp_ajax_trigger_webjob', 'trigger_webjob_with_file');
add_action('wp_ajax_nopriv_trigger_webjob', 'trigger_webjob_with_file');

I am not going to include my python script but it is ran with a shell file that just says

#!/bin/bash
python3 stitchImages.py "$1"

and for full context of what the python script provides the file ends with -

if status == cv2.Stitcher_OK:


print("Stitching successful!")
output_filename = "stitched_image.png"
wp_uploads_folder = os.path.join(os.getcwd(), 'wp-content', 'uploads')
if not os.path.exists(wp_uploads_folder):
    os.makedirs(wp_uploads_folder)

output_path = os.path.join(wp_uploads_folder, output_filename)
cv2.imwrite(output_path, cv2.cvtColor(stitched_image_rgb, cv2.COLOR_RGB2BGR))

# Return the URL instead of file path
output_url = f"https://omitted.azurewebsites.net/wp-content/uploads/{output_filename}"
print(f"Stitched image URL: {output_url}")

When I click the Run WebJobs button on the page it loads for a few seconds then just returns back to its original page with nothing uplaoded. Azure has no logged webjob triggers or errors.

Any Suggestions or spotted errors? I am open to maneuvering this another way if something makes more logical sense as I do want my sight to be usable and make some type of sense if another engineer were to look at its makeup. Again new to azure and wordpress so forgive me if this makes no sense.


Solution

  • An Azure Function would be the correct resource to use for this instead of a WebJob. WebJobs wouldn't be appropriate for this as they are meant to behave like a cronjob; something that executes on a schedule.