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

时间:2014-06-23 22:56:11

标签: python django heroku amazon-s3 reportlab

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

一切正常,图像生成正确,但是...图像是在项目外的文件夹中创建的,而我正在使用Heroku进行制作,我无法访问图像。

我正在使用这个Django结构(http://django-skel.readthedocs.org/en/latest/),专门用于在Amazon S3上使用Heroku。

你知道吗,我怎样才能在亚马逊上的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 个答案:

答案 0 :(得分: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类。