如何在 Laravel 9 项目中调用并传递信息给 Python 脚本?

huangapple go评论103阅读模式
英文:

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

问题

我在我的Laravel 9项目中有一个HTML表单,使用JS(带有jQuery)保存到浏览器的localStorage中。我还有一个Python脚本,需要获取一个CSV格式的数据库,根据localStorage中的信息进行修改,然后将其转换为JSON。最后,我有一个JavaScript文件,接受JSON并构建一个HTML表格。所有这些部分都可以单独工作,但我在将Python整合到我的Laravel 9项目中时遇到了问题。

在Laravel 9项目中调用和传递信息给Python脚本的最佳方式是什么?

对此的任何帮助或指导将不胜感激。提前感谢你!

英文:

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!

答案1

得分: 1

我成功地解决了这个问题。我是这样做的:

  1. 创建一个控制器:
    php artisan make:controller PythonController

  2. 在控制器中添加一个函数。下面是一个示例:

public function runScript()
{
    $scriptFile = public_path('script.py');
    $command = "python $scriptFile";

    exec($command, $output, $status);

    return view('database');
}
  1. 更新web.php中的路由:
Route::get('/run-python-script', [PythonController::class, 'runScript']);

记得在web.php中添加:use App\Http\Controllers\PythonController;

  1. 发起一个 AJAX 请求来运行 Python 脚本。以下是使用 jQuery 编写的 JavaScript 代码示例:
$.get('/run-python-script', function(response) {
    console.log(response);
});
英文:

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);
});

huangapple
  • 本文由 发表于 2023年3月12日 15:53:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75711746.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定