Showing results python command to the web cgi
Question: I have a python script and it runs well if executed in a terminal or command
line , but after I try even internal server error occurred . how to enhance
the script to be run on the web.

HTML

    
    
    <html><body>
    <form enctype="multipart/form-data" action="http://localhost/cgi-bin/coba5.py" method="post">
    <p>File: <input type="file" name="file"></p>
    <p><input type="submit" value="Upload"></p>
    </form>
    </body></html>
    

PYTHON

    
    
    #!/usr/bin/python
    import cgi, os
    import cgitb; cgitb.enable()
    import simplejson as json
    import optparse
    import sys
    
    try: # Windows needs stdio set for binary mode.
        import msvcrt
        msvcrt.setmode (0, os.O_BINARY) # stdin  = 0
        msvcrt.setmode (1, os.O_BINARY) # stdout = 1
    except ImportError:
        pass
    
    form = cgi.FieldStorage()
    
    # A nested FieldStorage instance holds the file
    fileitem = form['file']
    fn = os.path.basename(fileitem.filename)
    data = open('/tmp/upload-cgi/' + fn, 'wb').write(fileitem.file.read())
    data=fileitem.file.read()
    location_database = open('/home/bioinformatics2/DW/taxo.json', 'r')
    database = json.load(location_database)
    
    for line in data: 
     for taxonomy in database:  
      if taxonomy["genus"] == line.replace('\n','') :
       print "Kingdom: %s," % taxonomy['kingdom'],
       print "phylum: %s," % taxonomy['phylum'],
       print "class: %s," % taxonomy['class'],
       print "order: %s," % taxonomy['order'],
       print "family: %s," % taxonomy['family'],
       print "genus: %s" % taxonomy['genus']
       break
     else:
      print ("No found genus on taxanomy")
    


Answer: You're not outputting the HTTP header. At a minimum, you need to output:

    
    
    print "Content-Type: text/plain"
    print ""
    

You are also reading the file twice:

    
    
    data = open('/tmp/upload-cgi/' + fn, 'wb').write(fileitem.file.read())
    data=fileitem.file.read()
    

The second `fileitem.file.read()` will probably not read any content, since
the file should already be at the end-of-file, and so `data` will be empty.

