Can't Write File

Carsten Haese carsten.haese at gmail.com
Wed Nov 11 17:58:31 CET 2009


Victor Subervi wrote:
> Here's
> a bigger code snippet with the entire try clause:
> 
>           if 14 < x < 20: # This just shows that it's a pic, not some
> other type of data
>             y += 1
>             w += 1
>             try: # It does this, because I've printed 'getpic1.py' etc.
>               getpic = "getpic" + str(w) + ".py"
>               try:
>                 os.remove(getpic)
>               except:
>                 pass
>               code = """#! /usr/bin/python
> import cgitb; cgitb.enable()
> import MySQLdb
> import cgi
> import sys,os
> sys.path.append(os.getcwd())
> from login import login
> def pic():
>   user, passwd, db, host = login()
>   form = cgi.FieldStorage()
>   db = MySQLdb.connect(host, user, passwd, db)
>   cursor= db.cursor()
>   sql = "select pic%s from products where ID=%s;"
>   cursor.execute(sql)
>   content = cursor.fetchone()[0]
>   cursor.close()
>   print content
> print 'Content-type: image/jpeg'
> print
> pic()""" % (str(w), str(i))
>               script = open(getpic, "w") # I've deleted everything below
> this line to the except to test
>               script.write(code)
>               print '<td><input type="hidden" name="%s" />\n' % str(x)
>               os.chmod(getpic, 0755)
>               print '<img src="%s" width="100"><br /><br /></td>\n' %
> (getpic)
>               count2 += 1
>             except:
>               print '<td>nope</td>'
>           else:
>             print '<td>%s</td>\n' % (field)
>           x += 1

If I'm understanding correctly what you're doing here, you're generating
an HTML page with image tags, and at the same time you're generating the
scripts whose purpose it is to serve the corresponding images' data.
This is a terrible approach for the following reason: If two different
users request this page for two different product IDs at roughly the
same time, the getpic scripts for the first user will be overwritten by
the getpic scripts for the second user before the first user's browser
had a chance to issue its requests for the results for his getpic scripts.

Rather than auto-generating on-the-fly variants of the getpic scripts
that only differ in the picture number and product ID, you should have
just one static getpic script that takes parameters from the URL that
tell it which image number and product ID to use.

This will fix your problem indirectly because then your script won't
have to write out any files at all.

--
Carsten Haese
http://informixdb.sourceforge.net




More information about the Python-list mailing list