将Reportlab生成的图片保存到我的MEDIA文件夹(在Amazon S3)

1 投票
1 回答
1275 浏览
提问于 2025-04-18 10:50

我实现了一个库,用来生成条形码图片(http://kennethngedo.wordpress.com/2014/02/07/how-to-generate-barcode-in-django-using-reportlab/

一切都运行得很好,图片生成得也很正确,但是……这个图片被保存在了项目外面的一个文件夹里。因为我在用Heroku做生产环境,所以我无法访问这个图片。

我使用的是这种Django结构(http://django-skel.readthedocs.org/en/latest/),它特别适合在Heroku上与Amazon S3一起使用。

你们知道怎么把生成的图片上传到我在Amazon上的Media文件夹吗?

这是我的Views.py,在这里生成并保存图片:

from random import randint
from reportlab.lib.units import mm
from reportlab.graphics.barcode import *
from reportlab.graphics.shapes import Drawing, String
from django.shortcuts import render_to_response


class MyBarcodeDrawing(Drawing):
    def __init__(self, text_value, *args, **kw):
        barcode = createBarcodeDrawing('Code128', value=text_value, barHeight=10*mm, humanReadable=True)
        Drawing.__init__(self,barcode.width,barcode.height,*args,**kw)
        self.add(barcode, name='barcode')


def barcode_generator(barcode_value):
    text = barcode_value
    filename = "nightology_barcode_" + barcode_value
    path_to_save = "media/barcodes/"
    b = MyBarcodeDrawing(text)
    b.save(formats=['gif','pdf'],outDir=path_to_save,fnRoot=filename)
    barcodePicUrl = "barcode/"+ filename + ".gif"
    return barcodePicUrl

希望有人能帮我一下……我会非常感激的。

谢谢!

1 个回答

1

我遇到过类似的问题,不过没有涉及到Amazon S3。对我来说,在媒体文件夹里创建一个新文件非常简单。我只需要用default_storage来获取媒体文件夹的路径:

from django.core.files.storage import default_storage
import os

# Get the path to the barcodes folder in the media folder
# check if the folder exists and create it if not

folderPath = default_storage.path('barcodes')
if not default_storage.exists('barcodes'):
    os.mkdir(folderPath)

因为django-skel似乎在使用一个针对Amazon S3的django-storage后端,所以这也应该适用于你的设置。如果Amazon S3的存储后端不是默认的存储后端,你可能需要直接使用S3Storage类。

撰写回答