【问题标题】:wtforms, ndb and blobstorewtforms、ndb 和 blobstore
【发布时间】:2013-12-18 23:11:55
【问题描述】:

我有这个模型:

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)

Error is Expected str, got u'image.jpg'

如果有人可以帮助我,我将不胜感激!

【问题讨论】:

    标签: blobstore app-engine-ndb wtforms


    【解决方案1】:

    我发现的唯一解决方案是使用https://developers.google.com/appengine/docs/python/blobstore/#Python_Writing_files_to_the_Blobstore中描述的已弃用低级 API

    我为 FileField 制作了一个 wtform 验证器。

    我变了:

    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
    

    验证器在 blobstore 中创建 blob,然后将字段数据从 FieldStorage 更改为 blob_key。

    我不认为这是最好的解决方案,但它现在有效。

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2013-07-01
      • 2023-03-13
      • 2013-07-14
      • 2015-03-03
      • 2014-08-11
      • 1970-01-01
      • 2012-10-12
      • 1970-01-01
      相关资源
      最近更新 更多