I know how to accomplish that with a FORM and a db.table.insert, however I would like to use Crud if it's possible. Here is a simplified version (without any error checking) of what I've tried:
# In models/db_documents.py
db.define_table('documents',
Field('name'),
Field('description'),
Field('url'),
Field('file_', 'upload'))
# In controllers/documents.py
import urllib2
from gluon.tools import Crud
def upload_document():
"""
Let users store files either by:
- uploading the file, or
- providing a URL where the file is located
"""
def download_document(form):
"""Download the file if the user provided a URL,
and store it in
form.vars.file_
"""
if form.vars.url != '':
form.vars.file_ = urllib2.urlopen(form.vars.url) # Doesn't work
crud = Crud(db)
crud.settings.create_onvalidation.documents.append(download_document)
form = crud.create(db.documents, next='document_uploaded')
return {'form': form}
It works well in the first case, 'upload a file', but I don't know how to address the second case, 'provide a URL'. Specifically I don't know how to insert the file in the database after having downloaded it with urllib2. In the code you can see that I tried with:
form.vars.file_ = urllib2.urlopen(form.vars.url)
Surprisingly, assigning a string to form.vars.file_ works in some way. I mean, doing:
form.vars.file_ = urllib2.urlopen(form.vars.url).read() # Assign a string
form.vars.file_ = urllib2.urlopen(form.vars.url) # Assign a file-like object
web2py creates a text file named 'file.txt' and stores the content of the string in it. If there is a way to change the default 'file.txt' name I think I will be fine too. I want to preserve the original name and extension.
Cheers,
Manu