sudo apt-get install apache2 sudo apt-get install libapache2-mod-python sudo apt-get install python-pip (This installs the Python Package Index) pip install Jinja2 (This installs the Template Engine Jinja2)
All you need to do to enable your Apache for Python is to edit the configuration file /etc/apache2/sites-available/default by adding the following handler definition to the <Directory /var/www> - section:
AddHandler mod_python .py PythonHandler mod_python.publisher PythonDebug On
Now create a folder which is named 'templates' under /var/www . All your templates have to live inside this folder because we are using a File System Template Loader. Inside the template folder the hello.html fille was created for demonstration purposes:
<html> Hello {{name}} ! </html>
As you can see there is one placeholder 'name'. Now we want to create Python code which uses the template. The following code example explains it:
### # Apache could be used together with python. To have a clean # seperation between the script code behind and the html view # a template engine can be used. The following controller script # shows how to render a web page based on a model and an HTML # template ### #Import the Jinja2 template engine from jinja2 import Environment, FileSystemLoader # Function to handle the reqest def index(req): # Set the environment by using a file system loader env = Environment(loader = FileSystemLoader('/var/www/templates')) # Get the template hello.html template = env.get_template('hello.html') # Return the rendered result return template.render(name='Your Name')
Your rendered output is now accessible via http://yourhost/hello.py and should look as the following one:
Hello Your Name !