def wrapper(*args, **kwargs): req_obj = req_ if not req_obj: req_obj = self.get_request_from_view_args( func, args, kwargs) # NOTE: At this point, argmap may be a Schema, or a callable parsed_args = self.parse( argmap, req=req_obj, locations=locations, validate=validate, error_status_code=error_status_code, error_headers=error_headers, ) if as_kwargs: # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! # ONLY CHANGE FROM ORIGINAL kwargs.update(animalify(parsed_args, types='snake')) # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! return func(*args, **kwargs) else: # Add parsed_args after other positional arguments new_args = args + (parsed_args, ) return func(*new_args, **kwargs)
def test_put_user_settings_email_subscriptions_bad_key(self): self.login_default_user() subs = animalify(get_default_email_subscriptions()) subs['badKey'] = False resp = self.app.put("/api/v1/users/{}/settings".format(self.user.id), data=json.dumps({'emailSubscriptions': subs}), content_type='application/json') self.assert400(resp)
def force_type(cls, rv, environ=None): if isinstance(rv, dict) or isinstance(rv, list) or isinstance( rv, tuple): rv = jsonify(animalify(rv)) elif rv is None: rv = jsonify(data=None), 204 return super(JSONResponse, cls).force_type(rv, environ)
def test_update_user_400_when_required_param_not_passed(self): self.login_default_user() updated_user = animalify(copy.deepcopy(user_schema.dump(self.user))) updated_user["displayName"] = 'new display name' del updated_user["avatar"] user_update_resp = self.app.put("/api/v1/users/{}".format( self.user.id), data=json.dumps(updated_user), content_type='application/json') self.assert400(user_update_resp)
def test_put_user_settings_email_subscriptions(self): self.login_default_user() subs = animalify(get_default_email_subscriptions()) subs['myCommentReply'] = False resp = self.app.put("/api/v1/users/{}/settings".format(self.user.id), data=json.dumps({'emailSubscriptions': subs}), content_type='application/json') self.assert200(resp) self.assertIsNotNone(resp.json['emailSubscriptions']) self.maxDiff = None self.assertEquals(resp.json['emailSubscriptions'], subs)
def test_update_user_remove_social_and_avatar(self): updated_user = animalify(copy.deepcopy(user_schema.dump(self.user))) updated_user["displayName"] = 'new display name' updated_user["avatar"] = None updated_user["socialMedias"] = None user_update_resp = self.app.put("/api/v1/users/{}".format( self.user.account_address), data=json.dumps(updated_user), headers=self.headers, content_type='application/json') self.assert200(user_update_resp) user_json = user_update_resp.json self.assertFalse(user_json["avatar"]) self.assertFalse(len(user_json["socialMedias"])) self.assertEqual(user_json["displayName"], updated_user["displayName"]) self.assertEqual(user_json["title"], updated_user["title"])
def test_update_user_remove_social_and_avatar(self, mock_remove_avatar): self.login_default_user() updated_user = animalify(copy.deepcopy(user_schema.dump(self.user))) updated_user["displayName"] = 'new display name' updated_user["avatar"] = '' updated_user["socialMedias"] = [] user_update_resp = self.app.put("/api/v1/users/{}".format( self.user.id), data=json.dumps(updated_user), content_type='application/json') self.assert200(user_update_resp, user_update_resp.json) user_json = user_update_resp.json print(user_json) self.assertFalse(user_json["avatar"]) self.assertFalse(len(user_json["socialMedias"])) self.assertEqual(user_json["displayName"], updated_user["displayName"]) self.assertEqual(user_json["title"], updated_user["title"]) mock_remove_avatar.assert_called_with(test_user["avatar"]["link"], self.user.id)
def setUp(self): super().setUp() self.rfw0 = self.make_rfw() self.rfw0_json = animalify(RFWSchema().dump(self.rfw0))
def validate_and_execute(*args, **kwargs): # grabs incoming data (multiple methods) request_data = utils.get_request_data() # fall-back type annotations from function signatures # when no parameter type is specified (python >3.5 only) type_annotations = None if sys.version_info >= (3, 5): signature = inspect.signature(view_func) type_annotations = { k: v.annotation for k, v in signature.parameters.items() if v.annotation is not inspect._empty } for param in parameters: # normalize param key for the view_func(*args, **kwargs) call param_key_safe = to_snake_case(param.key.replace('-', '_')) # checks if param is required if param.key not in request_data[param.location]: if param.required: return func_err(messages["required"] % param.key, http_status=400) else: # set default value, if provided if param.default is not None: kwargs[param_key_safe] = param.default else: kwargs[param_key_safe] = None continue # set the param type from function annotation (runs only once) if type_annotations and param.type is None: if param.key in type_annotations: param.type = type_annotations[param.key] else: return func_err(messages["type_required_py3.5"] % param.key) # validate the param value value = request_data[param.location].get(param.key) if type(value) != param.type: if param.type in NUMERIC_TYPES: try: value = param.type( value) # opportunistic coercing to int/float/long except ValueError: return func_err(messages["type_error"] % (param.key, param.type)) elif param.type in STRING_LIKE: pass elif param.type is ANY: pass elif param.type is datetime: try: value = dateutil.parser.parse(value) except: return func_err(messages["datetime_parse_error"] % (param.key, str(value))) elif param.type is bool and type(value) in STRING_LIKE: if value.lower() in ('true', 'y'): value = True elif value.lower() in ('false', 'n'): value = False else: return func_err(messages["type_error"] % (param.key, param.type)) else: return func_err(messages["type_error"] % (param.key, param.type)) # validate via custom validator, if provided if param.kwargs.get('validator', None): try: result = param.kwargs["validator"](value) if isinstance(result, Response): return result elif result: raise Exception( "validator returned an unknown format. " "either return nothing, raise an Exception or " "return a `flask.Response` object.") except Exception as ex: return func_err("parameter '%s' error: %s" % (param.key, str(ex))) kwargs[param_key_safe] = value try: result = view_func(*args, **kwargs) except HTTPException: raise except Exception as ex: return func_err(str(ex)) if isinstance(result, (Response, WResponse)): return result elif result is None: return jsonify(data=None), 204 elif isinstance(result, tuple): if not len(result) == 2 or not isinstance(result[1], int): return func_err(messages["bad_return_tuple"]) return jsonify(animalify(result[0], 'camel')), result[1] elif not isinstance(result, SUPPORTED_TYPES): raise TypeError("Bad return type for api_result") return jsonify(animalify(result))