[Tutor] Python+CGI+MySQL performance

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Sun, 27 Jan 2002 21:10:34 -0800 (PST)


On Sun, 27 Jan 2002, Erik Price wrote:

> On Saturday, January 26, 2002, at 04:51  PM, Pijus Virketis wrote:
> 
> > Mind you, there is a mod_python plug-in for Apache as well.
> 
> I have a quick question about using an Apache plugin like this -- what
> is the functional difference between using mod_python and python as a
> CGI?  I understand that mod_python may be somewhat faster, but what I
> am wondering is, do you write the script differently for one from the
> other?

We can write it similarly if we're careful.


In regular CGI, the web server will execute the script, just as if we were
running in from the shell prompt.  In the CGI version, we pretty much
start from scratch every time someone looks at the page.


What's different about mod_python is that there's a Python interpreter
embedded right into Apache's mod_python module.  The advantage here is
that, instead of incurring the cost of starting up the interpreter every
time the user requests a resource, we can just do it once.


When we write a mod_python'ed script, we probably need to make a special
function called "service()" or something similar to that, so that
mod_python() knows how to call the script when there's an HTTP request.  
I'd have to check the mod_python site for the specific function mod_python
expects to call, but I think that's the general idea.  Let me check...

http://www.modpython.org/live/mod_python-2.7.6/doc-html/tut-what-it-do.html

Ah, ok, they expect to see a function called "handle()".  Close enough.  
*grin* If you've fiddled arround with graphical user interfaces (GUI's),
you're may already be familiar with this style of program: it's an
"event-driven" program!  In a GUI, the program waits until the user
touches a a widget.  Similarly, in mod_python, a script waits until the
web server calls handle().




If we wanted a script to run similarly as both a CGI and in mod_python, we
can possibly use the following hook at the bottom of our program:

###
if __name__ == '__main__':
    req = somehowCreateARequestObjectThatMimicsWhatModPythonDoes()
    service(req)
###

However, I haven't played around with mod_python, so I don't quite know
how to define somehowCreateARequestObjectThatMimicsWhatModPythonDoes().  
*grin* But I'm sure it's possible.  Another alternative is to use
mod_python's CGI emulation handler:

http://www.modpython.org/live/mod_python-2.7.6/doc-html/hand-cgi.html

which allows us to just write our scripts just like CGI's, and mod_python
will set things up properly for us.