Saturday, 25 June 2016

Simple Python Web Server with CGI

Here is the code for python CGI web server :
 

 CgiServer.py

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable() # This line enables CGI error reporting

ServerHandler = CGIHTTPServer.CGIHTTPRequestHandler
ServerHandler.cgi_directories = ["/"]
HttpServer = BaseHTTPServer.HTTPServer(("", 8000), ServerHandler)
HttpServer.serve_forever()

and here's the code for a sample page:

TestPage.py

#!/usr/bin/env python

print """Content-type:text/html\r\n\r\n
<html>
<head>
 <title>Test Page</title>
</head>
<body>
 <center><h1>Hello world. This is The Test Page</h1></center>
</body>
</html>"""

then set the executable permissions for both file and run the Cgi_Server.py

$ chmod +x CgiServer.py
$ chmod +x TestPage.py
$ ./CgiServer.py

now open your web browser and type the following url

http://localhost:8000/TestPage.py


Voila!! thats it.

for more details visit : https://wiki.python.org/moin/CgiScripts

No comments:

Post a Comment