Last active
June 19, 2016 10:09
-
-
Save toughrogrammer/790187793b9dc36c1b9df0ca8e7b5550 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from app import api_root | |
from flask_restful import Resource, marshal_with, fields | |
class IPField(fields.Raw): | |
def format(self, value): | |
parts = value.split('.') | |
parts[1] = '***' | |
return '.'.join(parts) | |
class AnonymousField(fields.Raw): | |
def output(self, key, obj): | |
if obj['is_anonymous']: | |
return None | |
else: | |
return fields.get_value(self.attribute, obj) | |
document_list_fields = { | |
'id': fields.Integer(attribute='id'), | |
'title': fields.String(attribute='title', default='title of document'), | |
'content': fields.String(attribute='content'), | |
'ip': IPField(attribute='ip'), | |
'writer': { | |
'id': AnonymousField(attribute='writer.id'), | |
'name': AnonymousField(attribute='writer.name') | |
} | |
} | |
@api_root.resource('/documents') | |
class DocumentListAPI(Resource): | |
@marshal_with(document_list_fields, envelope='items') | |
def get(self): | |
writer1 = {'id': 100, 'name': 'writer1'} | |
writer2 = {'id': 101, 'name': 'writer2'} | |
items = [ | |
{'id': 1, 'writer': writer1, 'title': 'title1', 'content': 'content1', 'ip': '1.2.3.4', 'is_anonymous': True}, | |
{'id': 2, 'writer': writer1, 'title': None, 'content': 'content2', 'ip': '5.6.7.8', 'is_anonymous': False}, | |
{'id': 3, 'writer': writer2, 'title': 'title3', 'content': 'content3', 'ip': '9.10.11.12', 'is_anonymous': True} | |
] | |
return items |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment