async def upload_avatar(file: UploadFile = File(...), current_user: User = Depends(get_current_user), db: sa.orm.Session = Depends(get_db)): """ Uploads avatar and saves them :param file: File object :param current_user: Current authentificated user :param db: Session instance :return: Upload info """ path = os.path.join('static/user_avatars', file.filename) with open(path, 'wb+') as buffer: shutil.copyfileobj(file.file, buffer) if current_user.avatar: if os.path.exists(current_user.avatar): os.remove(current_user.avatar) try: current_user.avatar = path db.add(current_user) db.commit() except Exception as e: print(e) db.rollback() return {'filename': file.filename, 'path': path}
def transaction_cm(session: sa.orm.Session) -> tp.ContextManager[None]: """Provide a transactional scope around a series of operations.""" try: yield session.commit() except Exception: session.rollback() raise finally: session.close()
def create_user( user: CreateUserSchema, db: sa.orm.Session = get_db, ) -> UserSchema: """ Create new user. """ user = user.dict(exclude_unset=True) user["password"] = hash_password(user["password"]) user = User(**user) db.add(user) try: db.commit() except sa.exc.IntegrityError: db.rollback() raise HTTPException( status_code=400, detail="A user with this email already exists.", ) return user
def create_product( product: CreateProductSchema, db: sa.orm.Session = get_db, ) -> ProductSchema: """ Create new Product. """ product = product.dict(exclude_unset=True) if "image" in product: product["image"] = b64decode(product["image"]) product = Product(**product) db.add(product) try: db.commit() except sa.exc.IntegrityError: db.rollback() raise HTTPException( status_code=400, detail="A product with that name already exists.", ) return product
def session_reset(ssn: sa.orm.Session): """ Reset the session when done """ yield ssn.rollback() ssn.expunge_all()
def test_does_not_lose_history(ssn: sa.orm.Session): """ Extensive test of InstanceHistoryProxy with query counters and lazy loads """ assert ssn.autoflush == False, 'this test relies on Session.autoflush=False' engine = ssn.get_bind() # Prepare ssn.add(User(id=1, name='John', age=18)) ssn.add(Article(id=1, title='Python', author_id=1)) ssn.commit() # === Test 1: ModelHistoryProxy does not lose history when flushing a session ssn.expunge_all( ) # got to reset; otherwise, the session might reuse loaded objects user = ssn.query(User).get(1) with ExpectedQueryCounter(engine, 0, 'Expected no queries here'): old_user_hist = InstanceHistoryProxy(user) # issues no queries # Modify user.name = 'CHANGED' # History works assert old_user_hist.name == 'John' # Flush ssn.flush() # History is NOT broken! assert old_user_hist.name == 'John' # Change another column after flush; history is still NOT broken! user.age = 1800 assert old_user_hist.age == 18 # correct # Undo ssn.rollback() # === Test 1: ModelHistoryProxy does not lose history when lazyloading a column ssn.expunge_all( ) # got to reset; otherwise, the session might reuse loaded objects user = ssn.query(User).options(load_only('name')).get(1) with ExpectedQueryCounter(engine, 0, 'Expected no queries here'): old_user_hist = InstanceHistoryProxy(user) # issues no queries user.name = 'CHANGED' assert old_user_hist.name == 'John' # Load a column with ExpectedQueryCounter(engine, 1, 'Expected 1 lazyload query'): user.age # get an unloaded column # History is NOT broken! assert old_user_hist.name == 'John' # === Test 2: ModelHistoryProxy does not lose history when lazyloading a one-to-many relationship ssn.expunge_all( ) # got to reset; otherwise, the session might reuse loaded objects user = ssn.query(User).get(1) with ExpectedQueryCounter(engine, 0, 'Expected no queries here'): old_user_hist = InstanceHistoryProxy(user) user.name = 'CHANGED' assert old_user_hist.name == 'John' # History works # Load a relationship with ExpectedQueryCounter(engine, 1, 'Expected 1 lazyload query'): list(user.articles) # History is NOT broken! assert old_user_hist.name == 'John' # === Test 3: ModelHistoryProxy does not lose history when lazyloading a one-to-one relationship ssn.expunge_all( ) # got to reset; otherwise, the session might reuse loaded objects article = ssn.query(Article).get(1) with ExpectedQueryCounter(engine, 0, 'Expected no queries here'): old_article_hist = InstanceHistoryProxy(article) article.title = 'CHANGED' assert old_article_hist.title == 'Python' # works # Load a relationship with ExpectedQueryCounter(engine, 1, 'Expected 1 lazyload query'): article.author # History is NOT broken! assert old_article_hist.title == 'Python' # works
def try_to_commit(session: sa.orm.Session): try: session.commit() except sa.exc.IntegrityError: session.rollback() raise HTTPException(status_code=422, detail=tb.format_exc(limit=0))