Always Get Better

Posts Tagged ‘python’

Python file upload

Friday, January 2nd, 2009

I recently needed to handle file uploads from a Flash form post using CGI and Python. I made two discoveries:

  1. Python’s CGI library ignores query string variables on POST requests.
  2. After you’ve done it once, working with POST variables whether uploaded files or otherwise is dead simple!

Here is the file I came up with:

[source:python]
#!/usr/bin/python
import cgi, sys, os

UPLOAD_DIR = “/home/user/uploads”

postVars = cgi.FieldStorage()

if postVars.has_key(“myFile”):
fileitem = postVars[“myFile”]

# If myFile doesn’t contain a FILE, exit
if not fileitem.file:
return

# Strip file extension
(name,ext) = os.path.splitext( fileitem.filename )

# If a binary file, ensure write flags are binary
if ext == “.jpg” or ext == “.png” or ext == “.gif”:
ioFlag = “wb”
else:
ioFlag = “w”

# Save file data to disk stream
fileObj = file(os.path.join(self.path, fileitem.filename),ioFlag)
while 1:
chunk = fileitem.file.read(100000)
if not chunk: break
fileObj.write(chunk)
fileObj.close()
[/source]

Bonus points for checking for and creating a new directory to store the uploaded file in, if needed.

Create Directory in Python

Thursday, January 1st, 2009

I needed to learn how to create directories using Python and found this great resource (digression: check out this author’s page headers – way cool!)

Although I didn’t really add anything new to the code, I ended up creating the following commented function which I share here in case it helps more users to understand.

[source:python]
# If directory (path) doesn’t exist, create it
def createPath(path):
if not os.path.isdir(path):
os.mkdir(path)

# Example of Windows file path
createPath( “C:\\Python\\myNewDirectory” )

# Example of Linux file path
createPath( “/home/username/myNewDirectory” )
[/source]