2013-12-18 2 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 작업으로

, 내가 좋아하는 형태로 작업을 수행하려고 다음 : 양식이 제대로 파일 필드를 보여줍니다하지만 난하지 않기 때문에 POST에, 그것은 작동하지 않습니다

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

파일을 읽고 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) 

오류는 누군가가 나를 도울 수 있다면, 나는 그것을 감사하겠습니다, STR을 예상 u'image.jpg '

을 받고 있습니다!

답변

0

내가 찾은 유일한 해결책은 내가 FileField와의 wtform 검사기을 https://developers.google.com/appengine/docs/python/blobstore/#Python_Writing_files_to_the_Blobstore

에 설명 된 되지 낮은 수준의 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에 저장합니다.

나는 그것이 최선의 해결책이라고 생각하지 않지만 지금은 효과가있다.

관련 문제