Azure WebJobs+WordPress WebApp文件处理触发异常求助
我在Azure WebApp上搭建WordPress网站,需要实现一个用户上传文件后,调用Python脚本生成图片并返回展示的功能。由于Python脚本运行耗时较长,选择用WebJobs实现,但点击页面上的「Run WebJob」按钮后,页面加载几秒无结果返回,Azure中也没有WebJobs触发记录或错误日志。我主要从事数据科学工作,对Azure和Web开发不熟悉。
当前实现代码
前端上传页面代码
<!-- 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) { const imageUrl = result.data.match(/https:\/\/[^\s]+/)[0]; 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>
WordPress主题functions.php代码
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); } } 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');
WebJob启动脚本(shell文件)
#!/bin/bash python3 stitchImages.py "$1"
Python脚本结尾代码
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)) output_url = f"https://omitted.azurewebsites.net/wp-content/uploads/{output_filename}" print(f"Stitched image URL: {output_url}")
问题排查步骤
1. 修复Admin AJAX请求的参数错误
前端代码中admin_url('admin-ajax.php? action=trigger_webjob')的URL里?和action之间有空格,会导致WordPress无法识别正确的action参数,直接返回400错误。修改为:
const response = await fetch('<?php echo admin_url('admin-ajax.php?action=trigger_webjob'); ?>', { method: 'POST', body: formData });
2. 验证WebJob触发API的有效性
手动用curl调用WebJob触发接口,确认是否能正常触发:
curl -u "username:password" -X POST -F "file=@/本地测试文件路径" https://omitted.scm.azurewebsites.net/api/triggeredwebjobs/StitchImages/run
- 检查用户名/密码是否正确:在Azure门户的WebApp→部署中心→FTP获取发布用户名和密码
- 检查WebJob名称是否大小写完全匹配,且已部署到
site/wwwroot/App_Data/jobs/triggered/StitchImages目录下 - 给启动脚本添加执行权限:通过Kudu控制台(https://omitted.scm.azurewebsites.net)执行
chmod +x start.sh
3. 修正文件传递逻辑
当前PHP代码通过POST传递文件给WebJob,但WebJob的shell脚本用$1接收命令行参数,两者不匹配,导致脚本找不到文件而静默失败。可以二选一修改:
- 修改PHP代码:将文件路径作为命令行参数传给WebJob
$url = "https://omitted.scm.azurewebsites.net/api/triggeredwebjobs/StitchImages/run?arguments=" . urlencode($file_path); curl_setopt($curl, CURLOPT_POSTFIELDS, null); // 无需传递文件,只传路径参数 - 修改Python脚本:直接读取POST上传的文件(需添加multipart/form-data解析逻辑)
4. 查看WebJob日志
通过Kudu控制台→Tools→WebJobs Dashboard查看WebJob历史记录,或直接访问site/wwwroot/App_Data/jobs/triggered/StitchImages/logs目录查看日志文件,确认脚本执行时的具体错误。
优化实现方案
方案1:修正WebJob文件传递逻辑
将Python脚本中的上传目录路径改为Azure WebApp的实际路径:
wp_uploads_folder = '/home/site/wwwroot/wp-content/uploads'
确保WebJob能直接访问到WordPress的上传目录,避免路径错误。
方案2:改用Azure Queue实现异步处理
- 用户上传文件到WordPress后,PHP将文件路径写入Azure Queue存储
- 创建持续运行的WebJob,监听Queue消息,收到消息后执行Python脚本生成图片
- 脚本生成图片后,将URL存入WordPress数据库,前端通过轮询获取结果
- 优点:避免WebJob触发API的超时问题,异步处理更稳定,适合耗时任务
方案3:替换为Azure Functions
创建HTTP触发的Azure Function,直接接收文件上传并调用Python代码生成图片,返回图片URL。WordPress前端直接调用Function的API,用轮询方式等待结果。
- 优点:无需手动管理WebJob部署,自动扩缩容,日志系统更完善
内容的提问来源于stack exchange,提问作者Sierra Walker

