def on_delete(self, request, response, id): """Delete a Group.""" group = Session.query(Group).get(id) if group is None: raise HTTPNotFound Session.delete(group) response.status = HTTP_NO_CONTENT
def on_delete(self, request, response, email): """Delete a User.""" user = Session.query(User).get(email) if user is None: raise HTTPNotFound Session.delete(user) response.status = HTTP_NO_CONTENT
def on_get(self, request, response, email): """Retrieve a User.""" schema = UserSchema() user = Session.query(User).get(email) if user is None: raise HTTPNotFound response.document = schema.dump(user).data
def on_get(self, request, response, id): """Retrieve a Group.""" schema = GroupSchema() group = Session.query(Group).get(id) if group is None: raise HTTPNotFound response.document = schema.dump(group).data
def validate_users(self, data, many): """Validate that the submitted users all exist.""" users = data.get('users', []) users = {user['email'] for user in users} query = Session.query(User).filter(User.email.in_(users)) do_not_exist = users - {user.email for user in query.all()} if do_not_exist: raise ValidationError('Users: {} do not exist'.format( do_not_exist.__repr__()))
def on_post(self, request, response): """Create a new User.""" schema = UserSchema() try: result = schema.load(request.document) except ValidationError as error: raise HTTPBadRequest( 'Invalid document submitted', error.messages, ) user = result.data Session.add(user) # Commit early to return the id in the uri Session.commit() response.document = { 'uri': 'http://localhost:8000/user/{}'.format(user.email) } response.status = HTTP_CREATED
def get_one_or_create(cls, create_kwargs=None, **kwargs): """Race free django-style get or create.""" query = Session.query(cls).filter_by(**kwargs) try: return query.one() except NoResultFound: Session.begin_nested() kwargs.update(create_kwargs or {}) new = cls(**kwargs) Session.add(new) try: Session.commit() return new except IntegrityError: Session.rollback() return query.one()