Flask-restful笔记2

Flask-restful

对于一个视图函数,你可以指定好一些字段用于返回。以后可以使用ORM模型或者自定义的模型的时候,他会自动的获取模型中的相应的字段,生成json数据,然后再返回给客户端。这其中需要导入flask_restful.marshal_with装饰器。并且需要写一个字典,来指示需要返回的字段,以及该字段的数据类型。示例代码如下:


class ProfileView(Resource):
    resource_fields = {
    
    
        'username': fields.String,
        'age': fields.Integer,
        'school': fields.String
    }
    @marshal_with(resource_fields)
    def get(self,user_id):
        user = User.query.get(user_id)
        return user

在get方法中,返回user的时候,flask_restful会自动的读取user模型上的username以及age还有school属性。组装成一个json格式的字符串返回给客户端。

重命名属性:

很多时候你面向公众的字段名称是不同于内部的属性名。使用 attribute可以配置这种映射。比如现在想要返回user.school中的值,但是在返回给外面的时候,想以education返回回去,那么可以这样写:


resource_fields = {
    
    
    'education': fields.String(attribute='school')
}

默认值:

在返回一些字段的时候,有时候可能没有值,那么这时候可以在指定fields的时候给定一个默认值,示例代码如下:


resource_fields = {
    
    
    'age': fields.Integer(default=18)
}

复杂结构:

有时候想要在返回的数据格式中,形成比较复杂的结构。那么可以使用一些特殊的字段来实现。比如要在一个字段中放置一个列表,那么可以使用fields.List,比如在一个字段下面又是一个字典,那么可以使用fields.Nested。以下将讲解下复杂结构的用法:

class ArticleView(Resource):
    resource_fields = {
    
    
        'aritlce_title':fields.String(attribute='title'),
        'content':fields.String,
        'author': fields.Nested({
    
    
            'username': fields.String,
            'email': fields.String
        }),
        'tags': fields.List(fields.Nested({
    
    
            'id': fields.Integer,
            'name': fields.String
        })),
        'read_count': fields.Integer(default=80)
    }
    @marshal_with(resource_fields)
    def get(self,article_id):
        article = Article.query.get(article_id)
        return article

Flask-restful注意事项:

  1. 在蓝图中,如果使用flask-restful,那么在创建Api对象的时候,就不要再使用app了,而是使用蓝图。
  2. 如果在flask-restful的视图中想要返回html代码,或者是模版,那么就应该使用api.representation这个装饰器来定义一个函数,在这个函数中,应该对html代码进行一个封装,再返回。示例代码如下:

@api.representation('text/html')
def output_html(data,code,headers):
    print(data)
    # 在representation装饰的函数中,必须返回一个Response对象
    resp = make_response(data)
    return resp
class ListView(Resource):
    def get(self):
        return render_template('index.html')
api.add_resource(ListView,'/list/',endpoint='list')

猜你喜欢

转载自blog.csdn.net/chenxuezhong0413/article/details/114649976