简体   繁体   中英

Web2Py adding a file to a DB

I'm creating a file in my Web2Py code as follows:

tmpPckUpFile = open('FileContent.txt', 'w+')

I add to it

tmpPckUpFile.write("some stuff")

I close the file

tmpPckUpFile.close()

then try to update a row in the DB

db(db.project_pickup_approvals.id==request.args(0)).update(PickupContent = tmpPckUpFile)

At this point, I generally get an error: I/O operation on closed file

so what I've tried doing is removing the close() and now the file gets added to the DB but nothing is written. I get a blank file.

Q: How can I write to the file and place it into the DB?

If you do not want to retain the original "FileContent.txt" temporary file on the filesystem, you can instead write the content to a StringIO object, which is a file-like object that does not require the creation of an actual file on the filesystem.

import cStringIO
tmpPckUpFile = cStringIO.StringIO()
tmpPckUpFile.write('some stuff')
tmpPckUpFile.seek(0)
upload_field = db.project_pickup_approvals.PickupContent
db(db.project_pickup_approvals.id == request.args(0)).update(
    PickupContent=upload_field.store(tmpPckUpFile, filename='myfile.txt'))
tmpPckUpFile.close()

The above code should also work if you replace the first two lines with your original tmpPckUpFile = open('FileContent.txt', 'w+') line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM