Fields
user_fields = { 'id': fields.Integer, 'username': fields.String, 'email': fields.String, 'user_priority': fields.Integer, 'custom_greeting': fields.FormattedString('Hey there {username}!'), 'date_created': fields.DateTime, 'date_updated': fields.DateTime, 'links': fields.Nested({ 'friends': fields.Url('/Users/{id}/Friends', absolute=True), 'posts': fields.Url('Users/{id}/Posts', absolute=True), }), }
- class fields.String(default=None,attribute=None)
将获得的值编列为字符串 - class fields.Integer(default=o,**kwargs)
将获得的值编列为Int型 - class fields.DateTime(dt_format=’rfc822’, **kwargs)
以UTC的格式返回格式化后的时间字符串 - class fields.FormattedString(src_str)
在fields的response中插入其他的值
Ex:
fields = { 'name': fields.String, 'greeting': fields.FormattedString("Hello {name}") } data = { 'name': 'Doug', } marshal(data, fields)
- class fields.Nested(nested, allow_null=False, **kwargs)
在响应中创建子对象 - class fields.Url(endpoint=None,absolute=False,scheme=None)
UrI的字符串表示,接受一个字符串作为参数,absolute确定生成的Urls是否包含主机名。
参考:http://www.pythondoc.com/Flask-RESTful/intermediate-usage.html
- class fields.List(cls_or_instance, **kwargs)
可用于一个参数对应多个值的情况
详见:http://www.pythondoc.com/Flask-RESTful/fields.html#list-field
# marshal
flask.ext.restful.
marshal
(data, fields, envelope=None)¶
Takes raw data (in the form of a dict, list, object) and a dict of fields to output and filters the data based on those fields.
Parameters: |
|
---|
>>> from flask.ext.restful import fields, marshal >>> data = { 'a': 100, 'b': 'foo' } >>> mfields = { 'a': fields.Raw }
>>> marshal(data, mfields) OrderedDict([('a', 100)])
>>> marshal(data, mfields, envelope='data') OrderedDict([('data', OrderedDict([('a', 100)]))])
官方API文档:http://www.pythondoc.com/Flask-RESTful/api.html
将原始数据过滤后序列化输出,输出结果的形式与fields参数有关。
data为原始数据,envelope为封装序列化的结果。
fields.Raw:
如mfields={‘a’:fields.Raw} ,原始数据data中’a’:100,故marshal的结果中fields.Raw为100。
OrderedDict,实现了对字典对象中元素的排序。
marshal_with
flask.ext.restful.
marshal_with
(fields, envelope=None)¶
A decorator that apply marshalling to the return values of your methods.
>>> from flask.ext.restful import fields, marshal_with >>> mfields = { 'a': fields.Raw } >>> @marshal_with(mfields) ... def get(): ... return { 'a': 100, 'b': 'foo' } ... ... >>> get() OrderedDict([('a', 100)])
>>> @marshal_with(mfields, envelope='data') ... def get(): ... return { 'a': 100, 'b': 'foo' } ... ... >>> get() OrderedDict([('data', OrderedDict([('a', 100)]))])
see flask.ext.restful.marshal()
marshal_with的用法则和marsh很类似。
原文: