Python记录的异常只是' __退出__'

时间:2017-06-02 17:41:04

标签: python django exception

我在Django中的一个视图函数中收到一个内部服务器错误,它接受一个图像文件并将其保存到我的某个模型中。视图函数在开发中工作,但在生产中给我一个内部服务器错误。我试图在try / except块中包装失败的代码部分,但是它记录的例外只是说'__exit__'我不确定这意味着什么,或者它是什么样的异常是。我试着查看那个例外意味着什么,但找不到任何东西。是否与打开文件有关,并且有关闭它的问题?断开的视图函数的确切部分是它所说的......

if name == 'one':
                trade_in.photo_one = file

查看

def edit_photos(request):
    trade_in = account_trade_in(request)
    if not trade_in:
        return HttpResponse(json.dumps({'error': 'Something went wrong, unable to edit photos'}), content_type='application/json')

    if request.method == 'POST':
        try:
            file = request.FILES['file']

            name = request.POST['photo']

            if name == 'one':
                trade_in.photo_one = file
            elif name == 'two':
                trade_in.photo_two = file
            elif name == 'three':
                trade_in.photo_three = file
            elif name == 'four':
                trade_in.photo_four = file
            elif name == 'five':
                trade_in.photo_five = file
            elif name == 'six':
                trade_in.photo_six = file

            trade_in.save()
        except Exception as e:
            logging.error(e)
            return HttpResponse(json.dumps({'error': e}), content_type='application/json')

    json_trade_in = json.dumps(trade_in.get_json())

    return HttpResponse(json_trade_in, content_type='application/json')

模型

class TradeInDetails(models.Model):

    account = models.OneToOneField(Account)
    photo_one = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})
    photo_two = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})
    photo_three = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})
    photo_four = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})
    photo_five = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})
    photo_six = StdImageField(upload_to=UploadToClassNameDirUUID(), blank=True, null=True,
                                     variations={'thumbnail': (120, 120, True)})

    lender = models.CharField(max_length=255, null=True, blank=True)
    amount_owed = models.CharField(max_length=255, null=True, blank=True)
    year = models.CharField(max_length=255, null=True, blank=True)
    mileage = models.CharField(max_length=255, null=True, blank=True)
    make = models.ForeignKey('vehicle.VehicleMake', null=True, blank=True)
    model = models.ForeignKey('vehicle.VehicleModel', null=True, blank=True)

    class Meta:
        verbose_name = 'Trade In Photos'
        verbose_name_plural = 'Trade In Photos'

完整堆栈跟踪

  Traceback (most recent call last):
  File "/home/socialauto/social-auto-web/account/ajax_views.py", line 553, in edit_photos
    trade_in.save()
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 708, in save
    force_update=force_update, update_fields=update_fields)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 736, in save_base
    updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 798, in _save_table
    for f in non_pks]
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 798, in <listcomp>
    for f in non_pks]
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/files.py", line 311, in pre_save
    file.save(file.name, file, save=False)
  File "/home/socialauto/social-auto-web/third_party/stdimage/models.py", line 48, in save
    self.render_variations()
  File "/home/socialauto/social-auto-web/third_party/stdimage/models.py", line 58, in render_variations
    self.render_variation(self.name, variation, replace, self.storage)
  File "/home/socialauto/social-auto-web/third_party/stdimage/models.py", line 76, in render_variation
    with Image.open(f) as img:
AttributeError: __exit__

标准图像模型方法投掷错误

@classmethod
    def render_variation(cls, file_name, variation, replace=False,
                         storage=default_storage):
        """Render an image variation and saves it to the storage."""
        variation_name = cls.get_variation_name(file_name, variation['name'])
        if storage.exists(variation_name):
            if replace:
                storage.delete(variation_name)
                logger.info('File "{}" already exists and has been replaced.')
            else:
                logger.info('File "{}" already exists.')
                return variation_name

        resample = variation['resample']

        with storage.open(file_name) as f:
            with Image.open(f) as img:
                save_kargs = {}
                file_format = img.format

                if cls.is_smaller(img, variation):
                    factor = 1
                    while img.size[0] / factor \
                            > 2 * variation['width'] \
                            and img.size[1] * 2 / factor \
                            > 2 * variation['height']:
                        factor *= 2
                    if factor > 1:
                        img.thumbnail(
                            (int(img.size[0] / factor),
                             int(img.size[1] / factor)),
                            resample=resample
                        )

                    size = variation['width'], variation['height']
                    size = tuple(int(i) if i != float('inf') else i
                                 for i in size)

                    if file_format == 'JPEG':
                        # http://stackoverflow.com/a/21669827
                        img = img.convert('RGB')
                        save_kargs['optimize'] = True
                        save_kargs['quality'] = 'web_high'
                        if size[0] * size[1] > 10000:  # roughly <10kb
                            save_kargs['progressive'] = True

                    if variation['crop']:
                        img = ImageOps.fit(
                            img,
                            size,
                            method=resample
                        )
                    else:
                        img.thumbnail(
                            size,
                            resample=resample
                        )

                with BytesIO() as file_buffer:
                    img.save(file_buffer, file_format, **save_kargs)
                    f = ContentFile(file_buffer.getvalue())
                    storage.save(variation_name, f)
        return variation_name

0 个答案:

没有答案