What I’d like to show you in my very first blog post is how to run Python (2.x or 3.x) in a local Apache web server which runs under Laragon. Why bother using Python 2.x when Python 3.x is out, one might ask. Well, I wouldn’t have done this unless I knew that my web hosting provider supports Python 3.x. So out of my mistake I ended up learning interesting stuff about Python 2.x character encoding and how to use Python in a CGI (Common Gateway Interface) script .
Let’s start!
Install Python
First things first – what we should do is to install Python 2.x. interpreter in our Laragon installation. Thankfully, this is really easy for the newbies since Laragon itself makes it easy by giving relevant instructions. However, you can follow the instructions below and you’ll be good to go.
For Python 3.x:
- First go to the notification area in the taskbar and right click on Laragon icon > Tools > Quick Add > Python 3.x
- Close and re-open Laragon
For Python 2.x:
- Download zip file from here
- Unzip in C:\laragon\bin\python
- Close and re-open Laragon
Configure Apache web server
Follow steps below to -simply put- let Apache know that Python files can also be displayed by a web browser:
- Right click on Laragon icon > Apache > httpd.conf
- In the configuration file search for the
AddHandler
command - If need be, uncomment it by removing the hash (
#
) symbol - Add the
.py
extension at the end of the same line - Search for the
Options
command - Make sure the
ExecCGI
is included as an argument (or+ExecCGI
assuming all of the arguments are denoted in the same way, i.e. with a+
sign) - Save and close the text file
Create and set up python file
What we need to do now is to create a python file and prepare it so it can be readable by your web browser. We achieve this by:
- Create a directory C:\laragon\www\python and a python file in it which you can name as you prefer. I will quickly name it as
index.py
- Open the file, add the following lines and save it:
#!C:/laragon/bin/python/python-2.7.13/python.exe
# -*- coding: utf-8 -*-
print "Content-Type: text/html"
print ''
print '<meta charset="utf-8">'
# IMPORTS
import cgi;
import cgitb;cgitb.enable()
print '<h1>Hello World!Γεια σου Κόσμε</h1>'
- Now we should start the server by right clicking on Laragon icon > Apache > Start Apache
- To test whether the
index.py
can be “read” by your web browser or not, type localhost/python/index.py in your browser. What you should see is a “Hello World!Γεια σου Κόσμε!” header
That’s all for now. Thanks for reading and keep up with my next blog post!
Cheers
[sourcecode language=”python” wraplines=”false” collapse=”false”]
# convert the line into a list of characters
# and feed the list to the ReadAhead generator
chars = ReadAhead(list(line))
c = chars.next() # get first
[/sourcecode]