def get_or_create(longurl, author=None): try: return Session.query(Link).filter_by(long_url=longurl).one() except NoResultFound: l = Link() l.long_url = longurl l.userkey = author Session.add(l) if asbool(config.get('test_shortener')): # add and commit to get the id, then shorten Session.commit() Session.flush() l.shorten() Session.commit() return l