简体   繁体   中英

Call PHP code from Python

I'm trying to integrate an old PHP ad management system into a (Django) Python-based web application. The PHP and the Python code are both installed on the same hosts, PHP is executed by mod_php5 and Python through mod_wsgi , usually.

Now I wonder what's the best way to call this PHP ad management code from within my Python code in a most efficient manner (the ad management code has to be called multiple times for each page)?

The solutions I came up with so far, are the following:

  1. Write SOAP interface in PHP for the ad management code and write a SOAP client in Python which then calls the appropriate functions.

    The problem I see is, that will slow down the execution of the Python code considerably, since for each page served, multiple SOAP client requests are necessary in the background.

  2. Call the PHP code through os.execvp() or subprocess.Popen() using PHP command line interface.

    The problem here is that the PHP code makes use of the Apache environment ($_SERVER vars and other superglobals). I'm not sure if this can be simulated correctly.

  3. Rewrite the ad management code in Python.

    This will probably be the last resort. This ad management code just runs and runs, and there is no one remaining who wrote a piece of code for this :) I'd be quite afraid to do this ;)

Any other ideas or hints how this can be done?

Thanks.

How about using AJAX from the browser to load the ads?

For instance (using JQuery):

$(document).ready(function() { $("#apageelement").load("/phpapp/getads.php"); })

This allows you to keep you app almost completely separate from the PHP app.

Best solution is to use server side includes. Most webservers support this.

For example this is how it would be done in nginx:

<!--# include virtual="http://localhost:8080/phpapp/getads.php" -->

Your webserver would then dynamically request from your php backend, and insert it into the response that goes to the client. No javascript necessary, and entirely transparent.

You could also use a borderless <iframe>

I've done this in the past by serving the PHP portions directly via Apache. You could either put them in with your media files, (/site_media/php/) or if you prefer to use something more lightweight for your media server (like lighttpd), you can set up another portion of the site that goes through apache with PHP enabled.

From there, you can either take the ajax route in your templates, or you can load the PHP from your views using urllib(2) or httplib(2). Better yet, wrap the urllib2 call in a templatetag, and call that in your templates.

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