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()
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