Unsupported Media type, backend, Please guide me

1.3k views Asked by At

I am trying to receive a pdf file by using falcon framework as Backend. I am a beginner at backend and trying to understand what is happening. So summary, there are 2 classes. one of them, are my friends which are working.

this is the backend side code:

#this is my code
class VehiclePolicyResource(object):
    def on_post(self, req, resp, reg):
        local_path = create_local_path(req.url, req.content_type)
        with open(local_path, 'wb') as temp_file:
            body = req.stream.read()
            temp_file.write(body)
#this is my friend code
class VehicleOdometerResource(object):
    def on_post(self, req, resp, reg):
        local_path = create_local_path(req.url, req.content_type)
        with open(local_path, 'wb') as temp_file:
            body = req.stream.read()
            temp_file.write(body)

It is exactly the same and did not give the same answer and I add the route by doing this api.add_route('/v1/files/{reg}/policies',VehicleResourcesV1.VehiclePolicyResource())

and by using this command in terminal : HTTP POST localhost:5000/v1/files/SJQ52883Y/policies@/Users/alfreddatui/Autoarmour/aa-atlas/static/asd.pdf it trying to get the file. But it keep saying, Unsupported media type. WHILE the other code, receiving image, literally the same code as above, it works.

Any idea ?

2

There are 2 answers

1
AudioBubble On

I got it, I just notice that Falcon by default will receive JSON file(please correct me if I am wrong) So I need to make an exception for pdf and image file.

1
Oluwafemi Sule On

Falcon has out of the box support for requests with Content-Type: application/json.

For other content types, you need to provide a media handler for your request.

Here is an attempt at implementing a handler for requests of Content-Type: application/pdf.

import cStringIO
import mimetypes
import uuid
import os

import falcon
from falcon import media
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument

class Document(object):
    def __init__(self, document):
        self.document = document
    # implement media methods here

class PDFHandler(media.BaseHandler):
    def serialize(self, media):
        return media._parser.fp.getvalue()

    def deserialize(self, raw):
        fp = cStringIO.StringIO()
        fp.write(raw)
        try:
            return Document(
                PDFDocument(
                    PDFParser(fp)
                )
            )
        except ValueError as err:
            raise errors.HTTPBadRequest(
                'Invalid PDF',
                'Could not parse PDF body - {0}'.format(err)
            )

Update media handlers to support Content-Type: application/pdf.

extra_handlers = {
    'application/pdf': PDFHandler(),
}

app = falcon.API()
app.req_options.media_handlers.update(extra_handlers)
app.resp_options.media_handlers.update(extra_handlers)