dorado
dorado

Reputation: 1525

cgi file .py not exexuting; file gets displayed instead

I created a webserver in python.

server.py

import sys
import BaseHTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

HandlerClass = SimpleHTTPRequestHandler
ServerClass  = BaseHTTPServer.HTTPServer
Protocol     = "HTTP/1.0"

if sys.argv[1:]:
    port = int(sys.argv[1])
else:
    port = 8000
server_address = ('127.0.0.1', port)

HandlerClass.protocol_version = Protocol
httpd = ServerClass(server_address, HandlerClass)

sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()

and a file form.html

<html>
<title>FORM</title>
<body>
        <form id="form1" method="GET" action="/var/www/cgi-bin/formaction.py">
        Name : <input type="text" name="username">
        Password : <input type="password" name="password">
        <input type="submit">
    </form>
</body>
</html>

and formaction.py

import cgi, cgitb
cgitb.enable()
form = cgi.FieldStorage()
username = form.getvalue('username');
password = form.getvalue('password');
print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (username, password)
print "</body>"
print "</html>"

When I submit the form, the cgi file get displayed as it is rather than getting executed. How can I get the python script to execute.

Directory structure is as follows:

directory structure is as follows:

Upvotes: 1

Views: 311

Answers (1)

devastrix
devastrix

Reputation: 91

To run a CGI script in python, you need to run a CGI Server and not a HTTP Server. Try typing the following in command promt :

python -m CGIHTTPServer

Or try the following script :

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

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
PORT = 8000
server_address = ("", PORT)
handler.cgi_directories = ["/cgi-bin"]

httpd = server(server_address, handler)
print 'Server running on 127.0.0.1:8000...'
httpd.serve_forever()

Upvotes: 1

Related Questions