首页 文章

如何通过API(最好使用flask-restplus)封送腌制物品?

提问于
浏览
2

我有一个完整记录和完成的API,使用flask-restplus在python 3.5 / flask中构建 . 我想添加一个功能块 - 返回一个pickle对象作为我的一个响应的一部分 .

欢迎使用不特定于flask-restplus的一般解决方案,但由于我的API已完全记录并完成(除了这一点),我宁愿挂起而不是从根本上改变我正在使用的框架 .

我的模型架构看起来像这样(简化):

get_fields = api.model('get-myresource', {
    'id':                fields.Integer(description='Id of the resource.'),
    'other_field':       fields.Integer(description='some other fields too.'),
    'pickled_obj':       fields.Raw(description='Marshalling fields.Raw fails, as the serialised binary cant be expressed as json'),
})

我想要形成api响应的示例类(要被pickle)和模型:

class MyClass(object):
    # An instance of this class will be serialised with pickle
    a_prop = None

    def a_method(self):
        return 'some_result'

obj_instance = MyClass()

class MyDataModel(object):
    # It's actually a SQLAlchemy model, where one of the columns is PickleType, but for the sake of a canonical example...
    id = 1
    other_field = 2
    pickled_obj = pickle.dumps(obj_instance)

并且api endpoints 方法声明为:

import pickle
from flask import request
from flask_restplus import Resource, Namespace
from .my_schema_file import get_fields

api = Namespace('myresource', description='Whatever')

@api.route('')
class MyResource(Resource):

    @api.response(200, 'Resource(s) returned successfully', get_fields)
    @api.response(400, 'Bad Request')
    @api.response(404, 'Not Found')
    @api.response(500, 'Application Error')
    @api.marshal_with(get_fields, code=200, description='Resource(s) returned successfully')
    def get(self):

        # Argument parsing and fetch from the database
        data = MyDataModel()


        return data, 200

在这个例子中我给出了,使用fields.Raw()作为pickle对象的编组器不起作用(没有json表示) . 那么我该怎么办才能最大限度地减少我的API框架的重组呢?

[编辑:修复原始Q中的语法错误]

1 回答

  • 0

    最终答案:

    最后,我们不再使用泡菜,以避免版本控制问题,当我们更新我们的类然后尝试unpickle旧版本 .

    我们最终使用this SO answer中的建议,即使用jsonpickle库来序列化任意类对象并将其吐出API .

相关问题