英文:
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
我成功地解决了这个问题。我是这样做的:
-
创建一个控制器:
php artisan make:controller PythonController
-
在控制器中添加一个函数。下面是一个示例:
public function runScript()
{
$scriptFile = public_path('script.py');
$command = "python $scriptFile";
exec($command, $output, $status);
return view('database');
}
- 更新
web.php
中的路由:
Route::get('/run-python-script', [PythonController::class, 'runScript']);
记得在web.php
中添加:use App\Http\Controllers\PythonController;
- 发起一个 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:
- Create a controller:
php artisan make:controller PythonController
- 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');
}
- 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
- Make an AJAX request to run the Python script. Here done in JS with jQuery:
$.get('/run-python-script', function(response) {
console.log(response);
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论