python - Django QR 代码生成 PIL 图像使用 S3 保存不起作用

标签 python django amazon-s3 django-models django-1.8

我正在尝试根据模型生成二维码。我在 Heroku 托管该应用程序并使用 AWS S3 作为存储。 S3 存储与其他模型元素配合得很好,只是 QR 代码生成模型出现了问题。我使用此链接作为引用: https://gilang.chandrasa.com/blog/generate-qr-code-in-django-model/ 我的模型是:

class BusinessQRCode(models.Model):
    business = models.ForeignKey(Business, null=True)
    location_name = models.CharField(max_length=255)
    qrcode = models.ImageField(upload_to='documents/{}'.format(time.strftime("%Y/%m/%d")), blank=True, null=True)

    def save(self):
        super(BusinessQRCode, self).save()
        self.generate_qrcode()

    def generate_qrcode(self):
        from activation.models import RandomFileName

        qr = qrcode.QRCode(
            version=1,
            error_correction=qrcode.constants.ERROR_CORRECT_L,
            box_size=10,
            border=4,
        )
        qr.add_data('Some data')
        qr.make(fit=True)

        filename = 'qrcode-%s.png' % self.id

        img = qr.make_image()

        from django.conf import settings
        img.save(settings.MEDIA_ROOT + filename)

        # reopen = open(settings.MEDIA_ROOT + filename, "rb")
        # django_file = File(reopen)
        self.qrcode.save(filename,img, save=True)

上面的代码给了我这个错误:

TypeError

TypeError: seek() takes exactly 2 arguments (3 given)

我也尝试过使用注释代码,即打开文件并尝试保存它,但它不起作用,它只是永远不会停止加载。我的意思是最后这部分代码:

reopen = open(settings.MEDIA_ROOT + filename, "rb")
django_file = File(reopen)
self.qrcode.save(filename,django_file, save=True)

我做错了什么?

最佳答案

I have tried using the commented code as well, that is opening the file and than trying to save it, but it doesnt work, it just never stops loading.

我认为最后一种方法应该可行,但由于您在保存 ImageField 时使用 save=True ,这也会触发父模型的 save() 方法。所以你最终会陷入无限循环。

更改保存图像字段和模型的顺序。

def save(self):
    # Generate qrcode before calling super.save
    self.generate_qrcode() 
    super(BusinessQRCode, self).save()

def generate_qrcode(self):

    ...

    with open(settings.MEDIA_ROOT + filename, "rb") as reopen:
        django_file = File(reopen)
        self.qrcode.save(filename,django_file, save=False)

关于python - Django QR 代码生成 PIL 图像使用 S3 保存不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42042424/

相关文章:

python - 只要有待处理的取消屏蔽任务,但不再存在,我如何运行 asyncio 循环?

python - 如何为 Google App Engine 项目构建 sphinx(阅读文档)文档?

amazon-s3 - 未经身份验证的认知角色用户的 Amazon S3 存储桶权限

python - Django 开发服务器 CPU 密集型——如何分析?

node.js - 如何使用 nodejs 从 s3 检索图像

java - 如何使用 AWS S3 Android 恢复上传

python - fatal error : 'mymodule.h' file not found - Cython compile fails to find header

python - 自动检测/转换数据类型?

python - Django - 通过 ajax 请求提供文件

python - 在Django GeoJSON序列化器字段中指定相关模型的字段