如何使用Python和Django在包含图像的S3对象上循环?

mcdcgff0  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(115)

对于上下文,我的AWS S3媒体文件夹由包含广告图像的文件夹对象组成。桶中的每个对象都是一个广告
在本地,我可以在一个文件夹中的每个图像循环,并将其呈现到广告页面,但我不能让它在生产中工作。
呈现位置的相关视图如下所示:

def carmodel(request, carmodel_id):
carmodel = get_object_or_404(CarModel, id=carmodel_id)
folder_name = carmodel.title.replace(" ", '%20')
image_folder = os.listdir('media/'+carmodel.title)

return render(request, 'vehicles/vehicle.html', 
              {"carmodel": carmodel, "image_folder":image_folder, 
              "folder_name":folder_name})

字符串
每个文件夹都使用carmodels标题命名。在vehicles.html文件中,我循环它,就像这样。

{% for image in image_folder %}
          <img src="/media/{{ folder_name }}/{{ image }}" class="slider-thumbnail">
        {% endfor %}


我知道carmodel视图中image_folder变量的os.listdir在生产环境中不起作用。但我一直在想怎么补救。
我最终尝试通过使用MEDIA_URL来构建媒体URL,然后是文件夹名称,最后是每个图像的迭代。希望这有意义!

k3fezbri

k3fezbri1#

import boto3

def get_image_names_from_s3(bucket_name, folder_name):
    # Initialize the S3 client
    s3 = boto3.client('s3')
    
    # Fetch the objects (files) in the given folder
    response = s3.list_objects_v2(Bucket=bucket_name, Prefix=folder_name)
    
    # Extract the image file names from the response
    image_files = [content['Key'].split('/')[-1] for content in response.get('Contents', []) if content['Key'].lower().endswith(('.jpg', '.jpeg', '.png'))]
    
    return image_files

def yourview(request):
    bucket_name = 'your_bucket_name'
    folder_name = 'folder/sub_folder/'  # Ensure it ends with '/'
    image_names = get_image_names_from_s3(bucket_name, folder_name)
    context = {'names': image_names}
    return render(request, 'yourpage.html', context)

{% for i in names %}
<div class="col-12 col-md-8 my-3">
    <div class="yourclass" data-setbg="{% static 'path_to_link'|add:i %}" alt="">
    </div>
</div>
{% endfor %}

字符串

相关问题