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
How To Setup And Configuration Angular 15
How To Setup And Configuration...

Setting up and configuring Angular 15, the latest version of the popular JavaScript framework, is a crucial step in star...

Read More

Jun-07-2023

How To Image Upload In CKeditor With Laravel 10
How To Image Upload In CKedito...

In this article, we will see how to image upload in CKEditor with laravel 10. Here, we will learn about image uploa...

Read More

May-08-2023

How To Validate Upload File Type Using Javascript
How To Validate Upload File Ty...

This article will show us how to validate upload file type using javascript. Using this post we can easily check the sel...

Read More

Aug-03-2020

Send Email In Laravel
Send Email In Laravel

In this article, we will explore the process of sending emails in Laravel, covering versions 6, 7, 8, 9, and 10. Email f...

Read More

Sep-02-2020