Wednesday, November 17, 2010

Simple server running Python script on OS X: part 4

Continuing with the project from last time and before (here, here, and here).

I got two more things working: a dropdown menu and sending a file.

It would be nice if the user could only send the file types we want to accept, but that's not the way it works, at least you can't disable the unwanted types in the file dialog the way you can from Cocoa. I tried to use an accept attribute, but then I found it isn't supported by any browser! (Lost track of where I saw this, it's not mentioned in the spec).

Two possibilities: javascript to check the file extension, or coding in the script. I wasn't able to find MIME type info, see the printout. Probably the best would be to use Python-magic or something like it.

I had some errors that seemed to be related to file permissions, but at the moment it is working with:

$ ls -al data.txt
-r--------@ 1 telliott_admin staff 41 Nov 17 08:23 data.txt

I'm having trouble with output, so here is a screenshot of the first few lines:


<Content-type: text/html>

<form name="input" enctype="multipart/form-data"
action="cgi-bin/" method="post">

<select name="dropdown">
<option value="Math" selected>Math</option>
<option value="Physics">Physics</option>
<p>Please input a <code>.txt</code> or <code>.html</code> file:</p>
<input type="file" name="filename" />
<input type=submit value="Send" />

import os, cgi
import subprocess
form = cgi.FieldStorage()
D = os.environ

s = '''Content-type: text/html


print s
print form.keys(),'<br>'
print form.getvalue('dropdown'),'<br>'
data = form.getvalue('filename'),'<br>'
print data[0],'<br>'
print len(data),'<br>'

print '<table border="1">'
for k in D:
print '<tr>'
print '<td>', k, '</td>',
print '<td>', D[k],'</td>'
print '</tr>'
print '</table></p></p>'

print cgi.parse_header('CONTENT_TYPE')
print '</body></html>'

No comments: