def __init__(self): self.id = fields.Integer self.view = fields.FormattedString("/episodes/{id}") self.api = fields.FormattedString("/api/episodes/{id}") self.title = fields.String self.season = fields.Integer self.image = fields.String
def post(self, course_id): ''' uri: /api/course/<course_id>/files A new course is created here ''' args = self.parser.parse_args() name = args.name file_type = args.file_type user_id = args.user_id user = User.query.filter(User.id == user_id).all() file = File.query.filter( db.and_(Course.id == course_id, File.name == name)).all() if len(file) == 1: # File already exists return marshal( {'name': name}, {'msg': fields.FormattedString('file {name} exists.')}), 409 else: # create a new course here file_url = create_file(course_id, name) file = File(name=name, file_type=file_type, contributes=user, file_url=file_url, created_time=datetime.now(), updated_time=datetime.now(), file_size=0.0, file_info=f'created {name}', course_id=course_id) db.session.add(file) db.session.commit() return marshal(file, file_fields), 201
def test_formatting_field_dict(self): obj = { "sid": 3, "account_sid": 4, } field = fields.FormattedString("/foo/{account_sid}/{sid}/") self.assertEquals(field.output("foo", obj), "/foo/4/3/")
def post(self): data = book_req_parser.parse_args() book = BookModel( name=data.get('name'), publish_date=data.get('publish_date'), price=data.get('price'), author_id=get_jwt_identity() ) book.save() output_fields = BOOK_OUTPUT_FIELDS.copy() output_fields['message'] = fields.FormattedString('book successfully created') return marshal(book, BOOK_OUTPUT_FIELDS), 201
def post(self): data = req_parser.parse_args() user = User.get_user_by_email(data['email']) if not user: return {'message': 'user not found'}, 404 if user.has_role('author'): return { 'message': "this account already has 'Author' privilege" }, 409 if not user.has_role('author'): user.add_role('author') output_fields = USER_OUTPUT_FIELDS.copy() output_fields['message'] = fields.FormattedString( 'role added to the account') # noqa return marshal(user, output_fields)
def put(self, book_id): data = book_req_parser.parse_args() book = BookModel.get_book_by_id(book_id) if not book: return {'message': 'book not found'}, 404 if book.author.id != get_jwt_identity(): return {'message': 'you are not allowed to update this book'}, 401 book.name = data.get('name') book.publish_date = data.get('publish_date') book.price = data.get('price') book.save() output_fields = BOOK_OUTPUT_FIELDS.copy() output_fields['message'] = fields.FormattedString('book has been updated') return marshal(book, BOOK_OUTPUT_FIELDS), 200
def test_formatting_field_tuple(self): obj = (3, 4) field = fields.FormattedString("/foo/{0[account_sid]}/{0[sid]}/") self.assertRaises(MarshallingException, lambda: field.output("foo", obj))
def test_formatted_string(self): field = fields.FormattedString("{hey}") self.assertEquals("3", field.output("hey", Foo()))
def test_formatted_string_invalid_obj(self): field = fields.FormattedString("{hey}") self.assertRaises(MarshallingException, lambda: field.output("hey", None))
default=1, choices=range(5), help='The user\'s priority', ) 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('user_friends'), 'posts': fields.Url('user_posts'), }), } class User(Resource): @marshal_with(user_fields) def post(self):
'email', dest='email', type=email, location='form', required=True, help='The user\'s email', ) post_parser.add_argument( 'user_priority', dest='user_priority', type=int, location='form', default=1, choices=range(5), help='The user\'s priority', ) 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('user_friends'), 'posts': fields.Url('user_posts'), }), } class User(Resource): @marshal_with(user_fields) def post(self): args = post_parser.parse_args() user = create_user(args.username, args.email, args.user_priority) return user
def test_deduce_swagger_type_fields_formatted_string(): new_instance = fields.FormattedString("Hello {name}") assert swagger.deduce_swagger_type(new_instance) == {"type": "string"}
def __init__(self): super().__init__() self.view = fields.FormattedString("/artists/{id}") self.lastfm_name = fields.String self.lastfm_image = fields.String
def __init__(self): self.id = fields.Integer self.name = fields.String self.view = fields.FormattedString("/genres/{name}")
# 先定义一个gender类,要求接收的参数不是male就是female,否则调用abort class Gender(fields.Raw): def format(self, value): return value if value in {'male', 'female'} else abort(500) # 然后自定义一个格式化的数据,这个数据就是返回给前端的response,这里对response的格式、类型等做了限定: # 比如id只能是int,如果是str就会报错。 user_fields = { 'id': fields.Integer, # 如果给本fields发送的请求中不含有name(实操下来发现就是name = None),则response默认值unnamed 'name': fields.String(default='unnamed'), 'nickname': fields.String, 'gender': Gender, # 可以自定义格式化数据 'greeting': fields.FormattedString('hello {nickname}'), } # 这似乎是一个中间件,资源调用这个中间件,然后中间件再去查询fields class QueryUser(object): # 给name参数设置默认值None,这样才能触发fields中的default def __init__(self, id, gender, nickname, name=None): self.id = id self.gender = gender self.nickname = nickname self.name = name # 这才是资源本体 class User(Resource):
parser = reqparse.RequestParser() parser.add_argument('id') parser.add_argument('name', type=dict) user_schema = { 'schemas': fields.List(fields.String, default=["urn:ietf:params:scim:schemas:core:2.0:User"]), 'id': fields.String(attribute="eduPersonPrincipalName"), 'userName': fields.String(attribute='eduPersonPrincipalName'), 'meta': { 'resourceType': fields.String(default='User'), 'location': fields.FormattedString('/Users/{eduPersonPrincipalName}') } } error_schema = { 'status': fields.Integer, 'detail': fields.String, 'schemas': fields.List(fields.String, default=['urn:ietf:params:scim:api:messages:2.0:Error']), } internal_user_schema = { 'eduPersonPrincipalName': fields.String(attribute='id'),
def test_formatting_field(self): obj = Mock() obj.sid = 3 obj.account_sid = 4 field = fields.FormattedString("/foo/{account_sid}/{sid}/") self.assertEquals(field.output("foo", obj), "/foo/4/3/")
class BaseResource(Resource): def __init__(self, **kwargs): self.logger = kwargs['logger'] self.books_dao = kwargs['books_dao'] get_book_dto = { 'id': fields.String, 'title': fields.String, 'author': fields.String, 'description': fields.String, 'price': fields.Float, 'cover': fields.String, 'links': { 'self': fields.FormattedString('{host}books/{id}') } } class PublicBookList(BaseResource): """ Resource for all the books """ @marshal_with(get_book_dto, envelope='data') def get(self): """ Return a JSON array of all books """ # Search by title args = request.args