Search code examples
phppythonjoomlacherrypyjoomla3.0

Can you display python web code in Joomla?


I'm building a Joomla 3 web site but I have the need to customize quite a few pages. I know I can use PHP with Joomla, but is it also possible to use Python with it? Specifically, I'm looking to use CherryPy to write some custom pieces of code but I want them to be displayed in native Joomla pages (not just iFrames). Is this possible?


Solution

  • PHP execution of Python "scripts"

    This will work for scripts, which do stuff and return the output, not for CherryPy.

     <?php
        // execute your Python script from PHP
        $command = escapeshellcmd('myPythonScript.py');
        $output = shell_exec($command);
    
        echo $output;
    
        // take response content to embed it into the page
     ?>
    

    PHP to access a Python/CherryPy served website

    import cherrypy
    class HelloWorld(object):
        def index(self):
            return "Hello World!"
        index.exposed = True
    
    cherrypy.quickstart(HelloWorld())
    

    This starts a http://localhost:8080 and you should see Hello world!.

    Now you could access CherryPy's output by accessing it at it's localhost:port. Not good performance-wise, but works.

    <?php
        $output = file_get_contents('http://localhost:8080/');
        echo $output;
    ?>
    

    Joomla + Ajax to access a Pyhton/CherryPy served website

    An alternative solution would be, to not use PHP to fetch the content, but to do the fetch from client-side. Basically, you would use an Ajax-Request to the CherryPy served website, to fetch it's content and embed it into the dom of the Joomla served page.

     // add jQuery Ajax reqeust from your Joomla page to CherryPy
     $.ajax({
        url: "https://localhost:8080/", // <-- access the 2nd served website
        type: 'GET',
        success: function(res) {
          //console.log(res);
          alert(res);
          $("#someElement").html(res);
        }
     });