2013-12-18 45 views
1

我有這樣的模式:wtforms,NDB和Blob存儲

class Product(ndb.Model): 
    title = ndb.StringProperty() 
    description = ndb.TextProperty() 
    img = ndb.BlobKeyProperty(indexed=False) 

我需要一個HTML表單,上面寫着字段(標題和描述)的值,並讀取圖像(從文件字段),和將值NDB對象,圖像保存在Blobstore中並正確更新字段BlobKeyProperty。

當我同wtforms工作,我試圖像的形式做了以下幾點:

class ProductForm(Form): 
    title = fields.TextField('Title', [validators.Required(), validators.Length(min=4, max=25)]) 
    description = fields.TextAreaField('Description') 
    img = fields.FileField('img') 

形式顯示文件場正常,但在POST,這是行不通的,因爲我不知道如何讀取文件,將文件保存到Blobstore並更新BlobKeyProperty。

我的處理程序是這樣的:

class ProductHandler(BaseHandler): 
    def new(self): 
     if self.request.POST: 
      data = ProductForm(self.request.POST) 
      if data.validate(): 
       model = Product() 
       data.populate_obj(model) 
       model.put() 
       self.add_message("Product add!", 'success') 
       return self.redirect_to("product-list") 
      else: 
       self.add_message("Product not add!", 'error') 
     params = { 
      'form': ProductForm(), 
      "kind": "product", 
     } 
     return self.render_template('admin/new.html', **params) 

錯誤預計海峽,得到了u'image.jpg」

如果有人能幫助我,我將不勝感激!

回答

0

我發現的唯一的解決方案是使用在https://developers.google.com/appengine/docs/python/blobstore/#Python_Writing_files_to_the_Blobstore

描述我爲FileField或一個wtform驗證一個棄用低級API。

我改變:

img = fields.FileField('img') 

要:

img = fields.FileField('img', [create_upload_file]) 

而且我寫這個驗證:

def create_upload_file(form, field): 
    file_name = files.blobstore.create(mime_type=field.data.type, _blobinfo_uploaded_filename=field.data.filename) 
    with files.open(file_name, 'a') as f: 
     f.write(field.data.file.read()) 
    files.finalize(file_name) 
    blob_key = files.blobstore.get_blob_key(file_name) 
    field.data = blob_key 

驗證程序創建Blob存儲團塊,然後將其更改領域從FieldStorage到blob_key的數據。

我不認爲這是最好的解決方案,但它現在的作品。