My goal is to create an Android app that will take a photo and upload
it to Web2Py photolog apps running on GAE and my local server.
I am scripting Android with Python and had expected to use something
like urllib2 to post the image and data to an upload_photo crud.create
form.
When trying to post directly to a Web2Py-created form, nothing gets
written -- apparently because I'm not sending the _formkey. When using
my own form, the best I've been able to accomplish is adding
everything but the data.
Is there a more sensible route to getting images into a database
programmatically? If it must be through a form, will I need to somehow
capture and return the _formkey along with the upload?
Any comments, leads, or questions will be appreciated.
============
Model:
db.define_table('photolog',
Field('photo','upload',label='Photo',
uploadfield='photo_data'),
Field('title',default=''),
Field('photo_data','blob'),
auth.signature)
db.photolog.title.requires = [IS_NOT_IN_DB(db,
db.photolog.title),]
============
This contoller and view work as expected:
def add_photo():
return dict(form=crud.create(db.photolog))
-----
<div id="photolog_form">
{{=form}}
</div>
============
>From web2py shell, I can insert records to the database
programmatically with:
>>>filename = 'pic.jpg'
>>>stream=open(filename,'rb')
>>>db.photolog.insert(title='Not again!', \
photo=db.photolog.photo.store(stream,filename), \
photo_data=stream.read())
>>>db.commit()
============
A controller that doesn't work (even through the browser):
def add_photo():
form = SQLFORM(db.photolog)
if form.accepts(request.vars, session, dbio=False):
title = request.vars.title
photo = request.vars.photo.file
data = photo.read()
form.vars.id = db.photolog.insert(title=title,
photo=db.photolog.photo.store(photo,photo.name),
photo_data=data)
db.commit()
return dict(form=form)
============
Client-side Python script:
I've tried variations on the this, along with trying to use Doug
Hellmann's urllib2 multi-part form helper (http://www.doughellmann.com/
PyMOTW/urllib2/):
filename = 'pic.jpg'
stream=open(filename,'rb')
data = {'title': 'Super Photo',
'photo': (stream, filename),
'photo_data': stream.read()
}
urllib2.urlopen('http://example.com/init/photolog/add_photo',
data)