Search code examples
javascriptpythonjsonlaravellaravel-9

How to call and pass information to a Python script in a Laravel 9 project?


I have an HTML form in my Laravel 9 project saved to the browser's localStorage using JS (with jQuery). I also have a Python script that needs to take a CSV-formatted database, modify it based on the information from localStorage, and convert it to JSON. Lastly, I have a JavaScript file that takes the JSON and builds an HTML table. All of these parts work separately, but I'm having trouble integrating python into my Laravel 9 project.

What is the best way to call and pass information to a Python script within a Laravel 9 project?

Any help or guidance on this would be greatly appreciated. Thank you in advance!


Solution

  • I managed to solve the problem myself. I did it like this:

    1. Create a controller:
    php artisan make:controller PythonController
    
    1. Add a function to the controller. Here is one example:
        public function runScript()
        {
            $scriptFile = public_path('script.py');
            $command = "python $scriptFile";
        
            exec($command, $output, $status);
        
            return view('database');
        }
    
    1. Update the routes in web.php:
    Route::get('/run-python-script', [PythonController::class, 'runScript']);
    

    Remeber to add: use App\Http\Controllers\PythonController; in the web.php

    1. Make an AJAX request to run the Python script. Here done in JS with jQuery:
    $.get('/run-python-script', function(response) {
        console.log(response);
    });