Executing Python Scripts in Laravel A Step-by-Step Guide

Websolutionstuff | Nov-26-2024 | Categories : Laravel Python

When working on a Laravel application, you may encounter scenarios where Python's robust libraries for data transformation, machine learning, or other complex tasks can complement Laravel's capabilities.

In this article, I’ll walk you through a simple and effective way to execute Python scripts directly from Laravel, providing step-by-step guidance and code snippets. This integration can be a game-changer for applications that need the best of both worlds.

Executing Python Scripts in Laravel A Step-by-Step Guide

Executing Python Scripts in Laravel A Step-by-Step Guide

 

Step 1: Create a Python Script

Let’s start by creating a Python script that performs a sample task. In this example, the script will accept input, process it, and return the result.

scripts/sample_task.py

import sys
import json

def main():
    # Get data from Laravel
    input_data = sys.stdin.read()
    data = json.loads(input_data)

    # Process data (example: multiply input by 2)
    result = {"output": data["input"] * 2}

    # Return the result
    print(json.dumps(result))

if __name__ == "__main__":
    main()

 

Step 2: Set Up Laravel Route and Controller

In Laravel, we need to create a route and a controller method to execute the Python script.

routes/web.php

use App\Http\Controllers\PythonController;

Route::get('/run-python', [PythonController::class, 'runPythonScript']);

 

Step 3: Create the Controller

Now, let’s create the controller that handles the execution of the Python script.

app/Http/Controllers/PythonController.php

<?php

namespace App\Http\Controllers;

use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process;

class PythonController extends Controller
{
    public function runPythonScript()
    {
        // Define the Python script path
        $scriptPath = base_path('scripts/sample_task.py');

        // Prepare data to send to Python
        $inputData = json_encode(['input' => 10]);

        // Execute the Python script
        $process = new Process(['python3', $scriptPath]);
        $process->setInput($inputData);
        $process->run();

        // Check for errors
        if (!$process->isSuccessful()) {
            throw new ProcessFailedException($process);
        }

        // Parse Python output
        $output = json_decode($process->getOutput(), true);

        return response()->json([
            'status' => 'success',
            'data' => $output,
        ]);
    }
}

 

Step 4: Install Symfony Process Component

The Symfony Process component is used to execute the Python script. Install it using Composer:

composer require symfony/process

 

Step 5: Test the Integration

Start your Laravel development server:

php artisan serve

Visit the route in your browser or use a tool like Postman:

http://127.0.0.1:8000/run-python

You should receive a JSON response:

{
    "status": "success",
    "data": {
        "output": 20
    }
}

 

Step 6: Secure and Optimize
  • Error Handling: Ensure detailed error handling for Python script execution.
  • Validation: Validate input data to prevent injection attacks.
  • Environment Setup: Use a virtual environment for Python to isolate dependencies

 


You might also like:

Recommended Post
Featured Post
Scrolla - jQuery Plugin for Reveal Animations
Scrolla - jQuery Plugin for Re...

In this tutorial we will see how to use scrolla - jQuery plugin for reveal animations when scrolling a mouse. this jquer...

Read More

Apr-21-2021

How to Upload Multiple Image in Laravel 8
How to Upload Multiple Image i...

In this example we will see how to upload multiple image in laravel 8. here, we wil see tutorial of multiple image uploa...

Read More

Sep-17-2021

How To Add Summernote Editor In Laravel
How To Add Summernote Editor I...

In this tutorial, I will let you know how to use summernote editor in laravel, In laravel or PHP many editors are a...

Read More

Jun-17-2020

Bootstrap DateTimePicker Example
Bootstrap DateTimePicker Examp...

In this post i will show you how to implement bootstrap datetimepicker with example, bootstrap 4 datetimepicke...

Read More

Apr-02-2021