You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel实现Blade表单数据传Python脚本并返回结果至视图

在Laravel中调用Python机器学习脚本并实现前后端交互

我来给你一步步拆解这个完整流程,从Blade表单提交数据到Python脚本处理,再把结果返回给视图展示,全程都是可落地的代码:

一、前期准备

  • 确保你的服务器/本地环境已经安装了Python,在终端执行python --version或者python3 --version能正常输出版本号
  • 把你的Python脚本放到Laravel项目的某个目录下,比如storage/app/python_scripts/,记得给脚本设置可执行权限:chmod +x storage/app/python_scripts/your_script.py

二、修改Python脚本(适配Laravel调用)

原来的脚本是通过函数接收参数,并且用print输出结果,我们需要调整成能接收命令行参数的形式,这样Laravel可以通过命令行调用它并捕获输出:

import sys

def readSequence(sequence):
    # 这里保留你原来的机器学习处理逻辑,比如生成final_pred的代码
    # 暂时用模拟值代替,你替换成自己的真实逻辑即可
    final_pred = 1  # 假设处理后得到1

    if final_pred == 0:
        return "Not Found"
    elif final_pred == 1:
        return "Foundd"

if __name__ == "__main__":
    # 从命令行获取传入的序列参数
    if len(sys.argv) >= 2:
        input_sequence = sys.argv[1]
        result = readSequence(input_sequence)
        # 打印结果,让Laravel可以捕获
        print(result)
    else:
        print("Error: No sequence provided")

三、创建Blade表单视图

在resources/views/sequence-form.blade.php中创建提交表单:

<!DOCTYPE html>
<html>
<head>
    <title>Sequence Prediction</title>
</head>
<body>
    <h1>Enter Your Sequence</h1>
    @if(isset($result))
        <div style="padding: 10px; margin: 10px 0; background: #f0f8ff;">
            <strong>Prediction Result:</strong> {{ $result }}
        </div>
    @endif

    <form method="POST" action="{{ route('sequence.process') }}">
        @csrf
        <div>
            <label for="sequence">Sequence:</label>
            <input type="text" id="sequence" name="sequence" required>
        </div>
        <button type="submit">Predict</button>
    </form>
</body>
</html>

四、配置路由和控制器

  1. 在routes/web.php中添加路由:
use App\Http\Controllers\SequenceController;

Route::get('/sequence', function () {
    return view('sequence-form');
})->name('sequence.form');

Route::post('/sequence/process', [SequenceController::class, 'process'])->name('sequence.process');
  1. 创建控制器SequenceController:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SequenceController extends Controller
{
    public function process(Request $request)
    {
        // 验证输入的序列
        $request->validate([
            'sequence' => 'required|string',
        ]);

        $sequence = $request->input('sequence');
        $pythonScriptPath = storage_path('app/python_scripts/your_script.py');
        
        // 调用Python脚本,注意根据你的Python版本用python或python3
        // 使用escapeshellarg避免命令注入风险
        $command = "python3 " . escapeshellarg($pythonScriptPath) . " " . escapeshellarg($sequence);
        $result = shell_exec($command);

        // 处理结果,去除多余的换行符
        $result = trim($result);

        // 如果脚本执行出错,返回错误信息
        if ($result === null) {
            $result = "Error: Failed to execute Python script";
        }

        // 返回视图并传递结果
        return view('sequence-form', compact('result'));
    }
}

五、关键注意事项

  • 安全问题:一定要用escapeshellarg()处理用户输入和脚本路径,避免命令注入攻击
  • Python版本:如果你的环境中Python3是默认的,就用python,否则用python3,根据实际情况调整
  • 权限问题:确保Laravel的运行用户(比如www-data)有访问Python脚本所在目录的权限,并且能执行Python命令
  • 错误处理:可以在控制器中添加更多的异常捕获逻辑,比如检查脚本是否存在,Python是否可执行等

内容的提问来源于stack exchange,提问作者kamrul Islam Tushar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 09:02:34