Download images using RESTAPI

I am working with an application using the Django Rest Framework.

models.py

class Image(models.Model): image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,) image_path = models.URLField(max_length=200) order = models.IntegerField() version = models.CharField(max_length=10) 

serializers.py

 class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image field = ('id', 'image_path' , 'order' , 'version') 

views.py

 class ImageList(generics.ListCreateAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer class ImageDetail(generics.RetrieveUpdateDestroyAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer 

URL patterns

 url(r'^image/$',views.ImageList.as_view(),name='image_list'), url(r'^image/(?P<pk>[0-9]+)/$',views.ImageDetail.as_view(),name='image_detail') 

This is just part of the whole system. I want to upload images using RESTAPI and then upload it to amazon s3 and then get the url and save it in the image_path field of the model image. I saw previous solutions for uploading files using REST ( like this ), but nothing worked for my case. Can anyone suggest how I can do this?

+7
python django django-rest-framework amazon-s3
source share
2 answers

Well, finally, I figured out how to do this. I changed image_path to ImageField as suggested by Saurabh Goyal. I used this code:

 class Image(models.Model): image_meta = models.ForeignKey('Image_Meta',on_delete=models.CASCADE,) image_path = models.ImageField(upload_to='images-data') order = models.IntegerField() version = models.CharField(max_length=10) 

N provided my Amazon s3 details, as in the local_settings.py file, like:

 AWS_S3_ACCESS_KEY_ID = "Access_key_id" AWS_S3_SECRET_ACCESS_KEY = "secret_access_key" AWS_STORAGE_BUCKET_NAME = "bucket_name" 

and added this to settings.py :

 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' 

and voila !! It worked. Hope this helps someone get the same problem as me.

0
source share

We know that images / files are uploaded using multipart / form-data . By default, DRF does not parse data with multiple data.

To make multi-parameter drf data, you must tell the DRP view to use the MultiPartParser parser.

 from rest_framework.parsers import MultiPartParser class ImageList(generics.ListCreateAPIView): ... ... parser_classes = (MultiPartParser) ... 

I recommend having an imagefield in your serializer for the image field and processing it there to upload to Amazon and populate the URLField

0
source share

All Articles