async def create_product( product_create: ProductCreate = Body(...), brand_repo: BrandRepository = Depends(), category_repo: CategoryRepository = Depends(), store_repo: StoreRepository = Depends(), product_repo: ProductRepository = Depends(), ): """创建商品""" cat_id = product_create.cat_id category = await category_repo.get_category(cat_id) if not category: raise BadRequestException('不存在的商品分类') brand_id = product_create.brand_id brand = await brand_repo.get_brand(brand_id) if not brand: raise BadRequestException('不存在的商品品牌') store_id = product_create.store_id store = await store_repo.get_store(store_id) if not store: raise BadRequestException('不存在的商铺') product = await product_repo.create_product(product_create) return product
def remove_student_from_term( *, db: Session = Depends(deps.get_db), division_id: str, student_id: str, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("term")), ) -> Any: if division := crud.division.get(db, division_id): if student := crud.student.get(db, student_id): if student in division.students: logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) " f"is deleting Student {student_id} ({student.user.email}) " f"from Division {division_id} ({division.course.name} {division.division_code})" ) division.students.remove(student) try: db.commit() except exc.IntegrityError as e: logging.error(e) db.rollback() raise ConflictException(detail=e.__str__()) except Exception as e: logging.error(e) db.rollback() raise BadRequestException(detail=e.__str__()) return student raise NotFoundException( detail= f"Student with id {student_id} not found in Division with if {division_id}" )
class CRUDStudent(CRUDBase[Student, StudentCreate, StudentUpdate]): def get(self, db: Session, id: str) -> Optional[Student]: return db.query(Student).filter(Student.user_id == id).first() def create(self, db: Session, *, obj_in: StudentCreate) -> Student: db_obj = Student(user_id=obj_in.user_id, term_id=obj_in.term_id) db.add(db_obj) try: db.commit() except Exception as e: logging.error(f"{e.__class__} - {e.__str__}") db.rollback() db.refresh(db_obj) return db_obj def update(self, db: Session, *, db_obj: Student, obj_in: StudentUpdate | dict[str, Any]) -> Student: if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) return super().update(db, db_obj=db_obj, obj_in=update_data) def remove(self, db: Session, *, id: str) -> Student: if obj := db.query(Student).filter(Student.user_id == id).first(): db.delete(obj) try: db.commit() except Exception as e: logging.error(f"{e.__class__} - {e.__str__}") db.rollback() return obj raise BadRequestException( detail=f"Could not delete object with id {id}")
def register(job: CreateJob): """ Create a job and add it to a staging environment. The job will need to be confirmed via email before it's added to the worker. Performs platform credential validation. """ client = JobiiliClient(job.user, job.password) client.login() document = JobDocument(email=job.email, request=job.request, password=job.password, user=job.user, options=job.options) try: document.save() email_sender = EmailSender("confirm.html") template_params = { "confirmation_url": __generate_confirmation_url(document) } email_sender.send_email( email_to=document.email, email_from="internshipper.io <*****@*****.**>", subject="Confirm your subscription to internshipper.io", template_params=template_params) return {"success": True, "identity": client.identity} except Exception as exception: logging.error("Exception in job creation") logging.error(exception) raise BadRequestException( "Jobiili request was likely malformed") from exception
async def create_items( current_product: dict = Depends(get_product_by_id), item_bulk_create: List[ItemCreate] = Body(...), category_repo: CategoryRepository = Depends(), product_repo: ProductRepository = Depends(), ): """新增商品sku""" product_id = current_product['id'] cat_id = current_product['cat_id'] category = await category_repo.get_category(cat_id) if not category: raise BadRequestException('不存在的商品分类') try: await product_repo.bulk_create_sku(product_id, item_bulk_create) except OperationalError: raise BadRequestException('创建sku错误') return dict()
async def verify_session_key(req: Request): session_key = req.headers.get("x-session-key") try: if session_key is None: raise BadRequestException(message="x-session-key 값이 필요합니다") with transaction() as db: session = Sessions(session_key=session_key).find_by_session_key(db) setattr(req, "uid", int(session.user_rowid)) return True except NotFoundSessionException: raise
def update_file( *, db: Session = Depends(deps.get_db), file_id: str, file_in: schemas.FileUpdate, current_professor: models.Professor = Depends(deps.get_current_professor), ) -> Any: """ Update the attributes of an uploaded file (basically grade an assignment) """ if file := crud.file.get(db, id=file_id): if file.course_id in {division.course_id for division in current_professor.divisions}: if file.file_type == "submission": return crud.file.update(db, db_obj=file, obj_in=file_in) raise BadRequestException(detail=f"Cannot update a file of type {file.file_type}")
def update_user( *, db: Session = Depends(deps.get_db), user_id: str, user_in: schemas.UserUpdate, current_admin: models.Admin = Depends( deps.get_current_admin_with_permission("user")), ) -> Any: """ Update a user. """ # Fetch existing User object from db if user := crud.user.get(db, id=user_id): if user_in.type: raise BadRequestException(detail="User roles cannot be changed") if user_in.is_admin is not None and user.type != "professor": raise BadRequestException( detail=f"A {user.type} cannot have admin roles changed!", ) logging.info( f"Admin {current_admin.user_id} ({current_admin.user.email}) is updating User {user.id} ({user.email}) to" f"{user_in.__dict__}") return crud.user.update(db, db_obj=user, obj_in=user_in)
def confirm_job(job_id: str): """ Confirms the job and adds it to the worker as a periodic task. """ document = __try_find_document(job_id) if not document.confirmed: document.update(confirmed=True) return RedirectResponse("/#%s" % __compose_redirect_data({ "action": "CONFIRM_JOB", "payload": document.to_dict(remove_sensitive_data=True, minimize=True) })) raise BadRequestException("Subscription already confirmed")
def reset_password( token: str = Body(...), new_password: str = Body(...), db: Session = Depends(deps.get_db), ) -> Any: """ Reset password """ if email := verify_password_reset_token(token): if user := crud.user.get_by_email(db, email=email): if crud.user.is_active(user): hashed_password = get_password_hash(new_password) user.hashed_password = hashed_password db.add(user) db.commit() return {"msg": "Password updated successfully"} raise BadRequestException(detail="Inactive user")
def get_user_from_token(token: str, token_type: str, db: Session) -> models.User: try: payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]) token_data = schemas.TokenPayload(**payload) if token_data.type != token_type: raise BadRequestException( detail="Invalid token", ) except ExpiredSignatureError: raise ForbiddenException(detail="Token has expired") except (jwt.JWTError, ValidationError) as e: logging.error(e.__str__()) raise ForbiddenException( detail="Could not validate credentials", ) if user := crud.user.get(db, id=token_data.sub): if user.is_active: return user raise ConflictException("User account is disabled")
async def get_items( product_id: int = Path(..., ge=1, description='商品id'), product_repo: ProductRepository = Depends(), ): product = await product_repo.get_product(product_id) if not product: raise BadRequestException('不存在的商品') items, _ = await product_repo.get_items() item_ids = [item.id for item in items] item_specs = await product_repo.get_item_specs(item_ids=item_ids, item_id_sort=True) spec_item_group = groupby(item_specs, key=attrgetter('item_id')) item_spec_map = { str(item_id): list(group) for item_id, group in spec_item_group } entities = list() for item in items: entity = jsonable_encoder(item) entity['specs'] = item_spec_map.get(str(item.id), []) entities.append(entity) return entities
@router.get("/", response_model=dict[str, list[Lecture]]) def get_timetable( db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_user), ) -> Any: if user := crud.user.get(db, id=current_user.id): if user.type == "student" and (student := crud.student.get( db, id=user.id)): return generate_timetable(db, student.divisions) elif user.type == "professor" and (professor := crud.professor.get( db, id=user.id)): return generate_timetable(db, professor.divisions) else: raise BadRequestException( detail= f"No timetable can be generated for user type {user.type}") raise BadRequestException(detail="User object not found!") @router.get("/{division_id}", response_model=dict[str, list[Lecture]]) def get_timetable_division( *, db: Session = Depends(deps.get_db), _: models.User = Depends(deps.get_current_admin_with_permission("course")), division_id: str, ) -> Any: if division := crud.division.get(db, id=division_id): return generate_timetable(db, [division]) raise NotFoundException(detail=f"Division with id {division_id} not found")
send_reset_password_email(email_to=user.email, email=email, token=password_reset_token) return {"msg": "Password recovery email sent"} raise NotFoundException( detail="The user with this username does not exist in the system.", ) @router.post("/reset-password/", response_model=schemas.Msg) def reset_password( token: str = Body(...), new_password: str = Body(...), db: Session = Depends(deps.get_db), ) -> Any: """ Reset password """ if email := verify_password_reset_token(token): if user := crud.user.get_by_email(db, email=email): if crud.user.is_active(user): hashed_password = get_password_hash(new_password) user.hashed_password = hashed_password db.add(user) db.commit() return {"msg": "Password updated successfully"} raise BadRequestException(detail="Inactive user") raise NotFoundException( detail="The user with this username does not exist in the system.", ) raise BadRequestException(detail="Invalid token")
def test_bad_request_exception_should_be_code_400_and_msg_is_default_value( self): ex = BadRequestException() self.assertEqual(ex.code, 400) self.assertEqual(ex.description, 'Bad Request Exception')
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model: Type[ModelType]): """ CRUD object with default methods to Create, Read, Update, Delete (CRUD). **Parameters** * `model`: A SQLAlchemy model class * `schema`: A Pydantic model (schema) class """ self.model = model def get(self, db: Session, id: str) -> Optional[ModelType]: return db.query(self.model).filter(self.model.id == id).first() def get_multi(self, db: Session, *, skip: int = 0, limit: int = 100) -> list[ModelType]: return db.query(self.model).all() def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data) # type: ignore db.add(db_obj) try: db.commit() except Exception as e: logging.error(f"{e.__class__} - {e.__str__}") db.rollback() db.refresh(db_obj) return db_obj def update(self, db: Session, *, db_obj: ModelType, obj_in: UpdateSchemaType | dict[str, Any]) -> ModelType: obj_data = jsonable_encoder(db_obj) if isinstance(obj_in, dict): update_data = obj_in else: update_data = obj_in.dict(exclude_unset=True) for field in obj_data: if field in update_data: setattr(db_obj, field, update_data[field]) db.add(db_obj) try: db.commit() except Exception as e: logging.error(f"{e.__class__} - {e.__str__}") db.rollback() db.refresh(db_obj) return db_obj def remove(self, db: Session, *, id: str) -> ModelType: if obj := db.query(self.model).get(id): db.delete(obj) try: db.commit() except Exception as e: logging.error(f"{e.__class__} - {e.__str__}") db.rollback() return obj raise BadRequestException( detail=f"Could not delete object with id {id}")
@router.get("/course", response_model=list[schemas.File]) def get_all_files_course( *, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_non_admin_user), ) -> Any: """ Retrieve files. """ if current_user.type == "student" and (student := crud.student.get(db, id=current_user.id)): courses = (division.course_id for division in student.divisions) elif current_user.type == "professor" and (professor := crud.professor.get(db, id=current_user.id)): courses = (division.course_id for division in professor.divisions) else: raise BadRequestException(detail=f"Could not fetch courses for user {current_user.id}") response = [] for course_id in courses: for file in crud.file.get_by_course(db, course_id=course_id): if file.file_type in ("assignment", "material"): response.append(file) return response @router.get("/{file_id}", response_model=schemas.File) def get_file_by_id( *, db: Session = Depends(deps.get_db), current_user: models.User = Depends(deps.get_current_non_admin_user), file_id: str, ) -> Any:
else: errors["not a student"].append(user_id) else: errors["not a user"].append(user_id) # Commit all the students added to the student try: db.commit() except exc.IntegrityError as e: logging.error(e.__str__()) db.rollback() raise ConflictException(detail=e.__str__()) except Exception as e: logging.error(e.__str__()) db.rollback() raise BadRequestException(detail=e.__str__()) if errors.keys(): response["errors"] = errors return response raise NotFoundException(detail="The division with this ID does not exist!") @router.delete("/{division_id}/students/{student_id}", response_model=schemas.Student) def remove_student_from_term( *, db: Session = Depends(deps.get_db), division_id: str, student_id: str,