Search This Blog

Monday, May 11, 2020

Apache on Linux using Python3 via CGI



QUICK guide to enabling Python on an Apache2 Linux server


Assuming Python3 and Apache2 are installed on Ubuntu server.


Firstly enable CGI on Apache|:

sudo a2enmod cgi


Next configure Apache2 for the relevant website:

sudo nano /etc/apache2/sites-enabled/000-default.conf

add the following after the VirtualHosts line:


< Directory /var/www/html> 
Options +ExecCGI   
DirectoryIndex index.py
</ Directory>   
AddHandler cgi-script .py

Now create a test Python script and put it into the folder listed (e.g. /var/www/html).
Import CGI and enable as in demo below.

This script will return the parameters passed to the page, then numbers 1 to 100 and end of pg msg.

  GNU nano 4.3                                      test.py                                                 
#!/usr/bin/python3

import cgitb
import cgi
cgitb.enable()

cgitb.enable(display=1, logdir="/var/log/apachepy")

print("Content-Type: text/html;charset=utf-8")
print()


arguments = cgi.FieldStorage()

for i in arguments.keys():
    print (arguments[i].value)

print ('
'
)

print (arguments['imgurl'].value)


for in in range (0,100):
    print (i + '
')

print ('--end of demo---')


Finally test the page by going to your browser... then put in the URL such as
http://myurl/test.py?img='www.bbc.com/123.jpg'






No comments: