Example of Simple Website Using Python

While reading my email today, found this question from one of the python.my mailing list subscriber.

Question: i want to run a web server using python
can expertise in python share some simple codes with html as well to
demonstrate this. [link to python.my thread]

Answer: As I'm bored today coz Kristen didn't answer my email yet, I pop my ubuntu terminal and type this code:
## =========================================================
# Sample python site by ApOgEE
# ----------------------------
# 1) Make sure you have apache and enable mod-python on your apache. For example on ubuntu:
# $ sudo apt-get install apache2
# $ sudo apt-get install libapache2-mod-python
# $ sudo a2enmod python
#
# 2) Make sure you have proper PythonHandler. For example:
# AddHandler mod_python .py
# PythonHandler mod_python.publisher
# PythonDebug On
#
# 3) Enter this codes and name it as 'pythonmysample.py' on your web directory
#
# 4) test it on your browser http://localhost/pythonmysample.py
#

def index(req):
thetitle = "Python.my sample by ApOgEE"
mysite = siteheader(thetitle)
mysite += sitebody(thetitle)
mysite += sitefoot()
return mysite

def siteheader(title):
str = "<html><head><title>" + title + "\n"
str += "</title></head><body>\n"
return str

def sitefoot():
str = "\n</body></html>"
return str

def sitebody(title):
str = "<h1>" + title + "</h1>\n"
str += "<p>Hi mate!<br>\n" + \
"This is the testing python site example.<br><br>" + \
"Coded by: ApOgEE<br>" + \
"Visit <a href=\"http://coderstalk.blogspot.com\">http://coderstalk.blogspot.com</a>

\n"
return str

# end of code. Copyright (C) 2009, ApOgEE - http://coderstalk.blogspot.com



If you have problem opening the page on your ubuntu, here is the checklist:
  1. Install apache2 and libapache2-mod-python and enable mod-python
    $ sudo apt-get install apache2
    $ sudo apt-get install libapache2-mod-python
    $ sudo a2enmod python

  2. Edit /etc/apache2/sites-enabled/000-default. Search for this lines:
            <Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
    </Directory>
    and add python handler like this:
            <Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all

    AddHandler mod_python .py
    PythonHandler mod_python.publisher
    PythonDebug On

    </Directory>

  3. Restart your apache
    $ sudo /etc/init.d/apache2 restart

You can also download the simple python website source code.

That's all. Hope you enjoy it... Happy Coding!!

Comments

Strae said…
Thanks for this snipped, can you post something about useing get/post request too?

Popular posts from this blog

How to Create Hyperlink on Blogger Post

How to Add a Sudo User on AlmaLinux 9.2 (Turquoise Kodkod): A Step-by-Step Guide

How to Show and Hide Text in Blog Post