1

我正在尝试使用 falcon 框架作为后端来接收 pdf 文件。我是后端的初学者,并试图了解正在发生的事情。所以总结一下,有2个类。其中之一是我正在工作的朋友。

这是后端代码:

#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)

它完全一样并且没有给出相同的答案,我通过这样做添加了路线 api.add_route('/v1/files/{reg}/policies',VehicleResourcesV1.VehiclePolicyResource())

并通过在终端中使用此命令: HTTP POST localhost:5000/v1/files/SJQ52883Y/policies@/Users/alfreddatui/Autoarmour/aa-atlas/static/asd.pdf 它试图获取文件。但它一直说,不支持的媒体类型。而其他代码,接收图像,与上面的代码相同,它可以工作。

任何想法 ?

4

2 回答 2

3

Falcon 对使用Content-Type: application/json.

对于其他内容类型,您需要为您的请求提供媒体处理程序。

这是为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)
            )

更新媒体处理程序以支持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)
于 2017-09-11T09:04:58.390 回答
0

我明白了,我只是注意到 Falcon 默认会接收 JSON 文件(如果我错了,请纠正我)所以我需要对 pdf 和图像文件进行例外处理。

于 2017-09-11T08:47:40.250 回答