简体   繁体   中英

Get Python to accept POST / GET requests

I have a PHP page and a Python program. The Python program makes an internal API call to get information that is needed to display on the PHP page.

The Python program is set up to accept an argument, and process the API call using that argument. For example myPythonProgram 12345 - gets information pertaining to account 12345.

I would like to call this from my PHP page through Ajax, but if I call the program the way it's supposed to be called, I get a 404 (there is a space between the program and the argument). I've altered the Python script to accept requests (I think ), but when I do this, the Python code is rendered rather than the result. The following fails:

$.ajax({
    type: 'POST',
    url: "myPythonProgram",
    data: { id: '12345' },
    success: function(response) {
        // Stuff
    },
    fail: function() {
       alert('Error');
    },
    complete: function() {
        // Stuff
    }
});

I thought that maybe I could call another PHP page to execute the Python program via shell_exec() , but it appears that the page is rendered before the Python program completes its request. Something like:

$.ajax({
   type: 'POST',
   url: "callPy.php",
   data: { id: '12345' },
   success: function(response) {
       // Stuff
   },
   ....
});

with callPy.php being:

<?php

$data = $_REQUEST['data'];

if (isset($data) && $data['id'] != NULL) {
    $info = shell_exec("myPythonProgram " . $data['id']);
    print_r(json_encode($info));
}

?>

If I were to run this exact command myPythonProgram 12345 in a shell, it works. If I modify callPy.php to hard code the id, then call php callPy.php in a shell, it works. But calling this in a browser renders null.

How can I make python accept a POST or GET request, or make the PHP wait for the Python program to finish before it renders the page?

This was resolved by changing the permissions on the files needed for the API call.

First, I checked what user was being used for the web browser: ps aux | egrep '(apache|httpd)' ps aux | egrep '(apache|httpd)' , which showed me that it was 'apache'. Next, I tried to run the python program as that user: sudo -u apache ./myPythonProgram 12345 . This gave an error on a certificate that was required for the API call.

With shell_exec() , PHP will wait for the process to complete. Therefore, changing the permissions on that certificate allowed me to run the program as the apache user, and I was able to achieve the desired effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM