python - Marshmallow URLFor BuildError 与 ObjectId

标签 python rest flask mongoengine hateoas

如何使用 MongoEngine 和 Flask-Marshmallow 制作 RESTFul API HATEOAS?

我正在使用

class PraiaSerializer(ma.Schema):                                                                                                      
    id = ma.String()                                                                                                                   
    atividades = ma.Nested(AtividadeSerializer, many=True)                                                                             

    class Meta:                                                                                                                        
        additional = ('nome', 'descricao', '_links')                                                                                   

    _links = ma.Hyperlinks({                                                                                                           
        'self': ma.URLFor('praia_detail', id='<id>'),                                                                                  
        'collection': ma.URLFor('praias')                                                                                              
    })               

但是,当向我的路线发送请求时,marshmallow 会抛出 BuildError。

BuildError: ('atividade_detail', MultiDict([('id', ObjectId('55024fdfe138235aeac01380'))]), None)

我应该做什么?

我向我的 ma.Hyperlinks 传递的内容是否有错误?

最佳答案

解决了我的问题!

我正在使用 Flask-RESTFul 编写 API,因此我必须使用端点名称注册我的路由。如果使用纯 Flask,请使用您的函数名称。

api.add_resource(PraiaListView, '/v1/praias', endpoint='praias_resource')
api.add_resource(PraiaView, '/v1/praias/<id>', endpoint='praia_detail')

并使用:

_links = ma.Hyperlinks({                                                                                                           
        'self': ma.URLFor('praia_detail', id='<id>'),                                                                                  
        'collection': ma.URLFor('praias_resource')                                                                                              
    })    

因此 Marshmallow 可以为 _links 字段生成以下输出:

"_links": {
  "collection": "/v1/praias",
  "self": "/v1/praias/55025029e138235aeac01383"
},

关于python - Marshmallow URLFor BuildError 与 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29289809/

相关文章:

python - ColumnTransformer 在 sklearn 中尝试 fit_transform 管道时生成 TypeError

c# - 仅在一处处理 WCF Rest 服务异常

android - OAuth 最佳学习资源

python - Flask SQLAlchemy - 仅为当前 session 设置 expire_on_commit=False

python - Flask webapp 中 url 方案的可能改进

python - Tkinter:窗口打不开

python - 优化 brainfuck 中的细胞增长

Python绑定(bind)C++虚成员函数无法调用

java - 与 REST Web 服务设计相比,使用 Direct Web Remoting 有何优势?

python - 在 MongoEngine 中链接查询