Python BaseHTTPServer CGIHTTPServer

2.4k views Asked by At

I am trying to implement a simple HTTP server with a form enabling the user to upload a file.

I have got three code files: - A python script creating the webserver with BaseHTTPServer and CGIHTTPServer - A html file with my form - Another python script linked to that form

Web server:

#!/usr/bin/env python
# coding: utf-8


import BaseHTTPServer
import CGIHTTPServer

import cgitb; cgitb.enable() # enable CGI error reporting

PORT = 8000
server_address = ('', PORT)

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler 
handler.cgi_directories = ['cgi-bin']


httpd = server(server_address, handler)

httpd.serve_forever()

index.html:

<html>
<body>
  <form enctype="multipart/form-data"
        action="save_file.py" method="POST">
    <p>File: <input type="file" name="filename"/></p>
    <p><input type="submit" value="Send"/></p>
  </form>
</body>
</html>

save_file.py (inside cgi-bin folder):

#!/usr/bin/env python
# coding: utf-8

import cgi, os
import cgitb; cgitb.enable()

form = cgi.FieldStorage()

# Get filename
fileitem = form['filename']

# Test if file uploaded
if fileitem.filename:
    message = 'ok'   
else:
    message = 'No file was uploaded'


print "Content-type: text/html"
print ""
print """
<html>
<body>
  <p> %s </p
</body>
</html>
""" % message

I can run the server, but when I click on Send to submit, after (or not) having selected a file, I have the following error message:

Error response

Error code 501.

Message: Can only POST to CGI scripts.

Error code explanation: 501 = Server does not support this operation.

0

There are 0 answers