2017-09-11 6 views
0

バックエンドとしてfalconフレームワークを使用してpdfファイルを受信しようとしています。 私はバックエンドの初心者で、何が起こっているのかを理解しようとしています。要約すると、2つのクラスがあります。そのうちの1人は働いている私の友人です。サポートされていないメディアタイプ、バックエンド、私を案内してください

これは、バックエンド側のコードです:

#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/[email protected]/Users/alfreddatui/Autoarmour/aa-atlas/static/asd.pdf ファイルを取得しようとしています。しかし、サポートされていないメディアの種類が続いています。 上記の文字コードと同じコードを他のコードが受け取っている間は、それは動作します。

+0

ごめん間違ったコマンド: HTTPのPOSTのはlocalhost:5000/V1 /ファイル/ SJQ9957Y /政策@ /ユーザ/ alfreddatui/Autoarmour静的/ AA-アトラス//asd.pdf 'create_local_path'で何が起こっているのか –

+0

?渡されたコンテンツタイプが請求書に適合しない場合に例外が発生する –

+0

申し訳ありませんが、ディレクトリを指す文字列を作成します(ファイルを保存したい) これはコードです '' 'def create_local_path (url、content_type): image_type = url.split( '/')[ - 1] ext = mimetypes.guess_extension(content_type) name = '{}/{} {}'。フォーマット(image_type、uuid.uuid4 ()、ext) return os.path.join( './ temp /'、name) '' ' –

答えて

0

私はそれを得ました。デフォルトではFalconはJSONファイルを受け取ります(私が間違っていると私を修正してください)。 だから私はpdfと画像ファイルの例外を作成する必要があります。

+1

あなたは 'application/json'のリクエストコンテンツタイプのデフォルトハンドラについては正しいです –

0

ファルコンは、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) 
関連する問題