views:

143

answers:

4

I've been told by my hosting company that Python is installed on their servers. How would I go about using it to output a simple HTML page? This is just as a learning exercise at the moment, but one day I'd like to use Python in the same way as I currently use PHP.

+2  A: 

There are many ways you could do this: assuming the server architecture supports the WSGI standard, then you could do something as simple as plugging in your own handler to generate the HTML (this could just build a string manually if you want to be really straightforward, or else use a template engine like Mako.

An example of a WSGI handler might look like this:

class HelloWorldHandler(object):

    def __call__(self, environ, start_response):
        """
        Processes a request for a webpage
        """
        start_response('200 OK', [('Content-Type', 'text/html')])
        return "<p>Hello world!</p>"

Obviously it is up to you what you return or how you generate it: as I say, for more complex pages a templating engine might be useful.

The more involved way would be to leverage a more complete framework, such as paste or turbogears but if you only want to output a static page or two this could be overkill.

jkp
+2  A: 

If your server is running Apache HTTP server, then you need something like mod_wsgi or mod_python installed and running as a module (your server signature may tell you this).

Once running, you may need to add a handler to your apache config, or a default may be setup.

After that, look at the documentation for the middleware of the module you are running, then maybe go on and use something like Django.

Aiden Bell
+1  A: 

You can't use it "the same way" as PHP. There are however tons of ways of doing it like Python.

Look into the likes of Turbogears or Django. Or BFG of you want something minimalistic, or WSGI (via mod_wsgi) if you want to go directly to the basics.

http://www.djangoproject.com/

http://bfg.repoze.org/

http://turbogears.org/

http://www.wsgi.org/wsgi/

Lennart Regebro
+2  A: 

When I used shared hosting I found that if I renamed the file to .py and prefixed it with a shebang line then it would be executed as Python.

#!/usr/bin/python

Was probably pretty bad practice, but it did work. Don't expect to be able to spit out any extensive web apps with it though.

Fiona Burrows
"renamed the file to .py"? What file?
S.Lott
+1 to annoy MR S.LOTT
Blauohr