Created
June 19, 2016 10:07
-
-
Save toughrogrammer/46a1f4192a65293b4de91a3188afd7a2 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 fields.get_value('is_anonymous', obj): | |
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') | |
} | |
} | |
class Document: | |
def __init__(self, id, writer, title, content, ip, is_anonymous): | |
self.id = id | |
self.writer = writer | |
self.title = title | |
self.content = content | |
self.ip = ip | |
self.is_anonymous = is_anonymous | |
class User: | |
def __init__(self, id, name): | |
self.id = id | |
self.name = name | |
@api_root.resource('/documents') | |
class DocumentListAPI(Resource): | |
@marshal_with(document_list_fields, envelope='items') | |
def get(self): | |
writer1 = User(100, 'writer1') | |
writer2 = User(101, 'writer2') | |
documents = [ | |
Document(1, writer1, 'title1', 'content1', '1.2.3.4', True), | |
Document(2, writer1, 'title2', 'content2', '5.6.7.8', False), | |
Document(3, writer2, 'title3', 'content3', '9.10.11.12', True), | |
] | |
return documents |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment