Get rid of Mongo $ signs in JSON

前端 未结 2 1904
鱼传尺愫
鱼传尺愫 2021-01-21 00:36

I am building python backend for SPA (Angular) using MongoDB.

Here is what I use: Python 3.4, MongoDB 3, Flask, flask-mongoe

2条回答
  •  渐次进展
    2021-01-21 01:11

    I found a neat solution to my problem in flask-restful extension which I use.

    It provides fields module.

    Flask-RESTful provides an easy way to control what data you actually render in your response. With the fields module, you can use whatever objects (ORM models/custom classes/etc.) you want in your resource. fields also lets you format and filter the response so you don’t have to worry about exposing internal data structures.

    It’s also very clear when looking at your code what data will be rendered and how it will be formatted.

    Example:

    from flask_restful import Resource, fields, marshal_with
    
    resource_fields = {
        'name': fields.String,
        'address': fields.String,
        'date_updated': fields.DateTime(dt_format='rfc822'),
    }
    
    class Todo(Resource):
        @marshal_with(resource_fields, envelope='resource')
        def get(self, **kwargs):
            return db_get_todo()  # Some function that queries the db
    

    Flask-RESTful Output Fields Documentation

提交回复
热议问题