def query_restaurant_activity_for_admin(self): # todo 效验是否admin args_spec = { 'city_ids': Arg(), 'begin_date': Arg(str), 'end_date': Arg(str), 'offset': Arg(int), 'limit': Arg(int), } args = args_parser.parse(args_spec) q = thirdparty_svc.ers.TRestaurantActivityQuery() for k, v in args.iteritems(): setattr(q, k, v) with thrift_client('ers') as ers: result = ers.query_restaurant_activity_for_admin(q) return result
def get_activities(cls): args_spec = { 'city_ids': Arg(int, multiple=True, allow_missing=True), } city_ids = args_parser.parse(args_spec).get('city_ids', []) if not city_ids: city_ids = cls.get_user_city_ids() today = get_today_date_str() rest_activities = rst_act_base.query( begin_date=today, end_date=today, city_ids=city_ids, is_valid=True) food_activities = food_act_base.query( begin_date=today, end_date=today, city_ids=city_ids, is_valid=True) rest_act_result = [] for act in rest_activities: rest_act_result.append({ 'activity_id': act.id, 'activity_name': RestaurantActivityMixin.get_name(act) }) food_act_result = [] for act in food_activities: food_act_result.append({ 'activity_id': act.id, 'activity_name': act.name }) return { 'food_activities': food_act_result, 'rest_activities': rest_act_result }
class Handler(webapp2.RequestHandler): @parser.use_args({'myfile': Arg(multiple=True)}, locations=('files', )) def post(self, args): self.response.content_type = 'application/json' _value = lambda f: f.getvalue().decode('utf-8') data = dict((i.filename, _value(i.file)) for i in args['myfile']) self.response.write(json.dumps(data))
def test_it_should_get_single_values(self): query = {name: value} arg = Arg(multiple=False) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result == value
def test_it_should_return_empty_list_if_multiple_and_not_present(self): query = {} arg = Arg(multiple=True) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result is Missing
def test_it_should_get_multiple_values(self): query = {name: [value, value]} arg = Arg(multiple=True) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result == [value, value]
def test_it_should_return_missing_if_not_present(self): query = {} arg = Arg(multiple=False) request = make_json_request(query) result = parser.parse_json(request, name, arg) assert result is Missing
class Handler(object): request = make_json_request({'foo': 41}) @use_kwargs({'foo': Arg(int)}, validate=lambda args: args['foo'] > 42) def get(self, args): return True
def set_order_valid(): args_spec = { 'order_id': Arg(int), } args = args_parser.parse(args_spec) order_id = args['order_id'] return order_base.set_valid(order_id)
def test_arg2parameters_with_dest(self): args = { 'X-Neat-Header': Arg(str, location='headers', dest='neat_header') } result = swagger.args2parameters(args) header = result[0] assert header['name'] == 'X-Neat-Header'
def test_use_kwargs_with_url_params(app, testapp): @app.route('/foo/<name>') @parser.use_kwargs({'myvalue': Arg(int)}) def foo(myvalue, name): return {'myvalue': myvalue} assert testapp.get('/foo/Fred?myvalue=42').json == {'myvalue': 42}
def test_use_args_decorator(app, testapp): @app.route('/foo/', method=['GET', 'POST']) @parser.use_args({'myvalue': Arg(int)}) def echo2(args): return args assert testapp.post('/foo/', {'myvalue': 23}).json == {'myvalue': 23}
class Bar(object): def __init__(self, request): self.request = request @parser.use_args({'myvalue': Arg(int)}) def __call__(self, args): return args
class ReadingList(APIView): route_base = '/reading/' decorators = [jwt_required(realm=None)] ARGS = { 'book_id': Arg(int, required=True) } def _get_book_from_request(self): reqargs = self._parse_request() book = Book.get_by_id(reqargs['book_id']) if not book: raise NotFound(detail='Book with id {0!r} not found.'.format(book.id)) return book def get(self): """Get the reading list for the authenticated user.""" reading_list = current_user.reading_list.all() res = { 'result': serialize_book(reading_list, many=True).data, 'user': serialize_user(current_user._get_current_object()).data } return res def post(self): """Add a book to the authenticated user's reading list. :param-json int book_id: ID of the book to add. """ book = self._get_book_from_request() current_user.add_to_reading_list(book) current_user.save() return { 'result': serialize_book(book).data, 'user': serialize_user(current_user._get_current_object()).data, }, http.OK def put(self): """Toggle the ``read`` status of a book. :param-json int book_id: ID of the book to modify. """ book = self._get_book_from_request() current_user.toggle_read(book) current_user.save() has_read = current_user.has_read(book) return { 'result': serialize_book(book, extra={'read': has_read}).data, 'user': serialize_user(current_user._get_current_object()).data, }, http.OK def delete(self): """Remove a book from the user's reading list. :param-json int book_id: The ID of the book to remove. """ book = self._get_book_from_request() current_user.remove_from_reading_list(book, commit=True) return {}
def test_use_kwargs_doesnt_change_docstring(testapp): @testapp.route('/foo/', methods=['post', 'get']) @parser.use_kwargs({'myvalue': Arg(type_=int)}) def echo(args, id): """Echo docstring.""" return jsonify(args) assert echo.__doc__ == 'Echo docstring.'
def test_multiple_arg_allowed_missing_false_int_conversion(testapp): args = {'ids': Arg(int, multiple=True, allow_missing=False)} with testapp.test_request_context(path='/foo', method='post', data=json.dumps({'fakedata': True}), content_type='application/json'): args = parser.parse(args) assert 'ids' in args
def test_it_should_return_empty_list_if_multiple_and_not_present(self): query = [] arg = Arg(multiple=True) request = make_form_request(query) result = parser.parse_form(request, name, arg) assert result == []
class AlwaysFailHandler(tornado.web.RequestHandler): ARGS = { 'name': Arg(str, validate=always_fail) } @use_args(ARGS) def post(self, args): self.write(args)
class ValidateHandler(tornado.web.RequestHandler): ARGS = { 'name': Arg(str, required=True) } @use_args(ARGS) def post(self, args): self.write(args)
def test_abort_called_on_validation_error(mock_abort, testapp): argmap = {'value': Arg(validate=lambda x: x == 42, type_=int)} with testapp.test_request_context('/foo', method='post', data=json.dumps({'value': 41}), content_type='application/json'): parser.parse(argmap) assert mock_abort.called_once_with(400)
def test_abort_called_on_type_conversion_error(mock_abort, testapp): argmap = {'value': Arg(type_=int)} with testapp.test_request_context('/foo', method='post', data=json.dumps({'value': 'badinput'}), content_type='application/json'): parser.parse(argmap) assert mock_abort.called_once_with(400)
def test_parse_multiple_json(testapp): multargs = {'name': Arg(multiple=True)} with testapp.test_request_context('/foo', data=json.dumps({'name': 'steve'}), content_type='application/json', method='POST'): args = parser.parse(multargs, targets=('json', )) assert args['name'] == ['steve']
def test_multiple_arg_required_int_conversion_required(mock_abort, testapp): args = {'ids': Arg(int, multiple=True, required=True)} with testapp.test_request_context(path='/foo', method='post', data=json.dumps({}), content_type='application/json'): args = parser.parse(args) mock_abort.assert_called_once
class Handler(object): request = make_json_request({'key': 'value'}) @use_kwargs({'key': Arg()}) def get(self, *args, **kwargs): assert args == () assert kwargs == {'key': 'value'} return True
def test_abort_called_when_required_arg_not_present(mock_abort, testapp): args = {'required': Arg(required=True)} with testapp.test_request_context('/foo', method='post', data=json.dumps({}), content_type='application/json'): parser.parse(args) assert mock_abort.called_once_with(400)
def set_order_invalid(): args_spec = { 'order_id': Arg(int), 'order_ids': Arg(default=[]), 'reason_type': Arg(int, default=1), 'remark': Arg(unicode, default=u''), } args = args_parser.parse(args_spec) order_id = args['order_id'] order_ids = args['order_ids'] if order_id: order_ids.append(order_id) reason_type = args['reason_type'] remark = args['remark'] for _id in order_ids: order_base.set_invalid(_id, reason_type, remark) return ''
def test_it_should_get_single_values(self): query = [(name, value)] arg = Arg(multiple=False) request = make_get_request(query) result = parser.parse_querystring(request, name, arg) assert result == bvalue
class IndexResource(restful.Resource): """A welcome page.""" hello_args = {'name': Arg(str, default='Friend')} @use_args(hello_args) def get(self, args): return {'message': 'Welcome, {}!'.format(args['name'])}
def test_it_should_get_multiple_values(self): query = [(name, value), (name, value)] arg = Arg(multiple=True) request = make_form_request(query) result = parser.parse_form(request, name, arg) assert result == [bvalue, bvalue]
class DateAddResource(restful.Resource): dateadd_args = { 'value': Arg(default=dt.datetime.utcnow, use=string_to_datetime), 'addend': Arg(int, required=True, validate=lambda val: val >= 0), 'unit': Arg(str, validate=validate_unit) } @use_kwargs(dateadd_args) def post(self, value, addend, unit): """A datetime adder endpoint.""" if unit == 'minutes': delta = dt.timedelta(minutes=addend) else: delta = dt.timedelta(days=addend) result = value + delta return {'result': result.isoformat()}