Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the parsers used for in the Django Rest Framework?

I have a simple file model

class Documents(models.Model):
    """ uploaded documents"""

    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    upload = models.FileField(storage=PrivateMediaStorage())
    filename = models.CharField(_('documents name'), max_length=255, blank=True, null=True)
    datafile = models.FileField()
    created = models.DateTimeField(auto_now_add=True)
    type = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True)

To display the list of uploaded documents and add new files, I use the class

class DocumentsListView(viewsets.ViewSetMixin,generics.ListCreateAPIView):
    queryset = Documents.objects.all()
    serializer_class = DocumentsSerializer

    def perform_create(self, serializer):
        serializer.save(author=self.request.user)

serializer.py

class DocumentsSerializer(AwsUrlMixin, serializers.ModelSerializer):
    type_name = serializers.CharField(source='type.type', read_only=True)
    type = serializers.PrimaryKeyRelatedField(queryset=Doctype.objects.all())
    view_file = serializers.SerializerMethodField()
    author = serializers.CharField(source='author.username', read_only=True)
    created = serializers.DateTimeField(format=date_format, input_formats=None, default_timezone=None, read_only=True)

    class Meta:
        model = Documents
        fields = ('id', 'author', 'filename', 'datafile', 'type', 'type_name', 'created', 'view_file')

I use the standard DRF interface and I display everything normally and add new files to the database.

While reading the documentation I came across parsers such as MultipartParser, FileUploadParser, which are also used when adding new files. I can't underatand when to use them and what function they perform, because now everything works without them.

The documentation hasn't given me a clear understanding of when I need to use parsers.

I try to add

parser_classes = (MultiPartParser, FileUploadParser)

to views.py and nothing change. Everything works as it did before. I'd appreciate it if you'd make that clear to me.

like image 640
Jekson Avatar asked Aug 28 '19 09:08

Jekson


2 Answers

Parsers in Django REST are used to parse the content of incoming HTTP request. In HTTP request we receive the data as a string format. Parsers will parse the HTTP contents in to python data types based on the Content-Type header received in the HTTP request. Django REST Framework provides a number of built-in parsers which parses different types of contents like application/json, multipart/form-data, application/xml, etc., based on the Content-Type header received in the HTTP request.

Parser Classes in Django REST:

  • JSONParser

    • It parses the incoming request JSON content into python content type dict.
    • It is used if "Content-Type" is set to "application/json".
  • FormParser

    • It parses the incoming request form contents into QueryDict.
    • It is used if "Content-Type" is set to "application/x-www-form-urlencoded".
  • MultiPartParser

    • It parses the incoming request form contents into QueryDict.
    • It is used if "Content-Type" is set to "multipart/form-data".
    • request.data will be a QueryDict containing all the form parameters.
    • request.files will be a QueryDict containing all the form files.
    • FormParser and MultiPartParser together used for full support of HTML form data.
  • FileUploadParser

    • It is used to parse a single file sent in HTTP request.

    • It expects a url keyword argument "filename". If it's not provided then we should provide the filename in the Content-Disposition HTTP header. For example Content-Disposition: attachment; filename=upload.jpg.

    • request.file is used to access the contents of uploaded file.

Reference: https://learnbatta.com/blog/parsers-in-django-rest-framework-85/

like image 112
anjaneyulubatta505 Avatar answered Oct 09 '22 12:10

anjaneyulubatta505


Parsers help your views to parse the data submitted in a specific format. Basically they map the Content-Type header of the HTTP request to the code required to parse that type into a python structure that your Serializer can understand.

If you're submitting content in the content types listed here, you don't need to do anything nor add any parser to your views. DRF already uses these parsers for these content types.

Only if your client is going to submit data in a different form, e.g. in XML or in yaml, will you need to add your own parser, many of which have already been written by someone else and can be found online. The reason adding the parsers you mentioned to your view doesn't do anything is that they are already the defaults used by DRF.

So let's say you have to integrate with an old-fashioned API (typically enterprises) that uses SOAP (God forbid...) then you'll have to bring in your own parser.

like image 43
dirkgroten Avatar answered Oct 09 '22 10:10

dirkgroten