如何通过API封送腌制的对象(最好使用flask-restplus)? [英] How can I marshal a pickled object through an API ( preferably using flask-restplus )?

查看:64
本文介绍了如何通过API封送腌制的对象(最好使用flask-restplus)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

欢迎使用非特定于flask-restplus的常规解决方案,但是由于我的API已被完整记录并完成(除了这一点),我宁愿坚持使用此方法,而不是从根本上改变我正在使用的框架./p>

我的模型架构如下(简化):

  get_fields = api.model('get-myresource',{'id':fields.Integer(description ='资源的ID.'),'other_field':fields.Integer(描述='还有其他一些字段.'),'pickled_obj':fields.Raw(description ='Marshalling fields.Raw失败,因为序列化的二进制文件不能表示为json'),}) 

还有一个我想形成api响应的示例类(需要腌制)和模型:

  class MyClass(object):#此类的实例将用pickle序列化a_prop =无def a_method(自己):返回"some_result"obj_instance = MyClass()类MyDataModel(object):#实际上是一个SQLAlchemy模型,其中一列是PickleType,但是为了一个典型的例子...id = 1other_field = 2pickled_obj = pickle.dumps(obj_instance) 

并且api端点方法声明为:

 导入泡菜从烧瓶进口要求从flask_restplus导入资源,命名空间从.my_schema_file导入get_fieldsapi =命名空间('myresource',description ='Whatever')@ api.route('')类MyResource(Resource):@ api.response(200,'资源成功返回',get_fields)@ api.response(400,'错误请求')@ api.response(404,'未找到')@ api.response(500,'应用程序错误')@ api.marshal_with(get_fields,code = 200,description ='成功返回资源')def get():#参数解析和从数据库获取数据= MyDataModel()返回数据,200 

在此示例中,我给出了将fields.Raw()用作腌制对象的封送处理程序的方法,该方法不起作用(没有json表示形式).因此,我应该怎么做才能最大程度地减少API框架的重构?

解决方案

最终答案:

最后,我们放弃使用泡菜,以避免在更新类然后尝试释放旧版本时的版本控制问题.

我们最终在此SO答案中使用了建议,即使用 解决方案

Final answer:

In the end, we moved away from using pickles, to avoid version control problems when we updated our classes then tried to unpickle form old versions.

We ultimately used the suggestion in this SO answer, which was to use the jsonpickle library to serialise the arbitrary class object and spit it out of the API.

这篇关于如何通过API封送腌制的对象(最好使用flask-restplus)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆