def post(self): try: data = user_schema.load(request.get_json() or {}) except ValidationError as err: first_invalid_field = list(err.messages.keys())[0] message = err.messages[first_invalid_field] abort(400, f'{first_invalid_field}: {message}') if User.query.filter_by(username=data['username']).first(): raise exceptions.UsernameAlreadyUsed if User.query.filter_by(email=data['email']).first(): raise exceptions.EmailAddressAlreadyUsed user = User(**data) db.session.add(user) db.session.commit() payload = { 'token': login(user_id=user.id), 'user': user_schema.dump(user) } response = jsonify(payload) response.status_code = 201 response.headers['Location'] = url_for('api.user_detail', user_id=user.id) return response
def create_user(): user_to_create, errors = user_schema.load(request.get_json()) req_json = request.get_json() if not req_json.get('password', None): errors.update({'password': ['Missing data for required field.']}) raise InvalidRequest(errors, status_code=400) save_model_user(user_to_create, pwd=req_json.get('password')) return jsonify(data=user_schema.dump(user_to_create).data), 201
def create_user(): user, errors = user_schema.load(request.get_json()) req_json = request.get_json() # TODO password policy, what is valid password if not req_json.get('password'): errors = {'password': ['Missing data for required field.']} return jsonify(result="error", message=errors), 400 if errors: return jsonify(result="error", message=errors), 400 user.password = req_json.get('password') save_model_user(user) return jsonify(data=user_schema.dump(user).data), 201
def put(self, user_id): user = User.query.get_or_404(user_id) raw_data = request.get_json() or {} data = user_schema.load(raw_data, partial=True) if 'username' in data and \ data['username'] != user.username and \ User.query.filter_by(username=data['username']).first(): raise exceptions.UsernameAlreadyUsed if 'email' in data and \ data['email'] != user.email and \ User.query.filter_by(email=data['email']).first(): raise exceptions.EmailAddressAlreadyUsed user.update(**data) db.session.commit() return user_schema.dump(user)