def create_user( data: UserCreate, background_tasks: BackgroundTasks, db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for create user """ user = crud_user.get_user_by_email(db, data.email) if user: raise HTTPException(status_code=400, detail='Endereço de email já registrador!') user = crud_user.create(db, data) rdc.invalidate_cache_prefix("providers-list") token = security.generate_token(str(user.id), "activate", datetime.utcnow() + timedelta(days=31)) background_tasks.add_task(mail.send_account_activation_email, user.name, user.email, token) return { 'detail': 'Enviamos um e-mail para você confirma seu cadastro, por favor verifique sua caixa de entrada.' }
def test_set_to_cache(rdc: RedisCache) -> None: key = "teste:1" value = 10 rdc.set_to_cache(key, value) cache = pickle.loads(rdc.get(key)) assert cache assert cache == 10 rdc.delete(key)
def test_get_from_cache(rdc: RedisCache) -> None: key = "teste:2" value = 20 rdc.setex(key, timedelta(seconds=3600), value=pickle.dumps(value)) cache = rdc.get_from_cache(key) assert cache assert cache == value rdc.delete(key)
def create_appointments( data: AppointmentCreate, background_tasks: BackgroundTasks, user: User = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for create appointment """ db_provider = crud_user.get_user_by_id(db, str(data.provider_id)) if not db_provider: raise HTTPException(status_code=404, detail="Cabeleireiro não encontrado") current_date = datetime.now() compare_date = data.date.replace(tzinfo=None) if compare_date < current_date: raise HTTPException( status_code=400, detail="Você não pode marcar agendamento em datas passadas") if data.date.hour < 8 or data.date.hour > 17: raise HTTPException( status_code=400, detail="Você só pode cria agendamentos entre 8:00 e 17:00") if data.provider_id == user.id: raise HTTPException( status_code=400, detail="Você não pode marca agendamento consigo mesmo") validate_date = crud_appointment.get_appointment_by_date( db, data.provider_id, data.date) if validate_date: raise HTTPException(status_code=400, detail="Este horario já esta agendado") appointment = crud_appointment.create(db, data, user) msg = f"Novo agendamento de {user.name} {user.surname} para o {date.format_date(data.date)}" background_tasks.add_task(crud_notification.create, str(data.provider_id), msg) date_time = data.date rdc.invalidate_cache( f"providers-appointments:{data.provider_id}:{date_time.year}:{date_time.month}:{date_time.day}" ) rdc.invalidate_cache(f"user-appointments:{user.id}") return appointment
def list_providers( user: UserModel = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for list providers """ cache_key = f"providers-list:{str(user.id)}" providers = rdc.get_from_cache(cache_key) if not providers: providers = crud_user.get_all_providers(db, user) rdc.set_to_cache(cache_key, providers) return providers
def list_self_provider_appointments( query: ProviderAppointmentsQuery = Depends(), user: UserModel = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis), ) -> Any: """ Endpoint for list self provider appointments """ cache_key = f"providers-appointments:{str(user.id)}:{query.year}:{query.month}:{query.day}" appointments = rdc.get_from_cache(cache_key) if not appointments: appointments = crud_appointment.get_appointments_by_DMY(db, query, user) rdc.set_to_cache(cache_key, parse_obj_as(List[ProviderAppointments], appointments)) return appointments
def list_self_provider_appointments( user: UserModel = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis), ) -> Any: """ Endpoint for list self user appointments """ cache_key = f"user-appointments:{str(user.id)}" appointments = rdc.get_from_cache(cache_key) if not appointments: appointments = crud_appointment.get_appointments_by_user(db, user) rdc.set_to_cache(cache_key, parse_obj_as(List[UserAppointments], appointments)) return appointments
def get_redis() -> Generator: """ Get redis database """ try: rdc = RedisCache() yield rdc finally: pass
def test_invalidate_cache(rdc: RedisCache) -> None: key = "teste:4" value = 20 rdc.setex(key, timedelta(seconds=3600), value=pickle.dumps(value)) cache = rdc.get(key) assert cache rdc.invalidate_cache(key) cache = rdc.get(key) assert cache is None rdc.delete(key)
def update_user( data: UserUpdate, user: UserModel = Depends(deps.get_user), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis) ) -> Any: """ Endpoint for update current user """ db_user = crud_user.get_user_by_email(db, data.email) if db_user and db_user.id != user.id: raise HTTPException(status_code=400, detail='Endereço de email já registrador!') data.avatar = user.avatar data.is_active = user.is_active if not data.address and user.address: data.address = user.address user = crud_user.update(db, user, data) rdc.invalidate_cache_provider(user) if user.address: #<-- if have an address, is a provider rdc.invalidate_cache_user(user) rdc.invalidate_cache_prefix("providers-list") return user
def test_invalidate_cache_prefix(rdc: RedisCache) -> None: suffix = utils.random_lower_string() prefix = "teste:5" key = f"{prefix}:{suffix}" value = 30 rdc.setex(key, timedelta(seconds=3600), value=pickle.dumps(value)) cache = rdc.get(key) assert cache rdc.invalidate_cache_prefix(prefix) cache = rdc.get(key) assert cache is None
def test_invalidate_cache_user(db: Session, rdc: RedisCache) -> None: user = utils.create_random_user(db) provider = utils.create_random_provider(db) appointment = utils.create_random_appointment(db, provider, user) provider.provider_appointments.append(appointment) key = f"user-appointments:{str(user.id)}" value = 40 rdc.setex(key, timedelta(seconds=3600), value=pickle.dumps(value)) cache = rdc.get(key) assert cache rdc.invalidate_cache_user(provider) cache = rdc.get(key) assert cache is None
async def upload_avatar(user: UserModel = Depends(deps.get_user), file: UploadFile = File(...), db: Session = Depends(deps.get_db), rdc: RedisCache = Depends(deps.get_redis)) -> Any: """ Endpoint for upload user avatar """ fileRead = await file.read() if user.avatar: avatar = media.update(fileRead, user.avatar) else: avatar = media.save(fileRead) user_in = UserUpdate(**jsonable_encoder(user)) user_in.avatar = avatar user = crud_user.update(db, user, user_in) rdc.invalidate_cache_provider(user) if user.address: #<-- if have an address, is a provider rdc.invalidate_cache_prefix("providers-list") rdc.invalidate_cache_user(user) return user
def test_get_from_cache_none(rdc: RedisCache) -> None: key = "teste:3" cache = rdc.get_from_cache(key) assert cache is None rdc.delete(key)
def rdc() -> Generator: """ Get redis database """ yield RedisCache()