How to use is_checked method in Playwright Python

Best Python code snippet using playwright-python

account.py

Source:account.py Github

copy

Full Screen

1import datetime2import random3from django.contrib.auth import authenticate4from django.contrib.auth.models import update_last_login5from django.core.mail import EmailMessage6from django.core.validators import validate_email7from django.db import transaction8from django.utils import timezone9from rest_framework import viewsets, status, permissions10from rest_framework.response import Response11from rest_framework_jwt.authentication import JSONWebTokenAuthentication12from rest_framework_jwt.settings import api_settings13from apps.api.serializers.account import *14from core.account.models import User, UserEmailAuthentication, Administrator, JWTokens15class SignupViewSet(viewsets.ModelViewSet):16 """17 create : 회원가입18 """19 queryset = User.objects.all()20 serializer_class = UserSerializer21 authentication_classes = []22 permission_classes = []23 def send_active_mail(self, domain, uidb64, token):24 """회원가입 인증 메일 보내기"""25 return f'아래 링크를 클릭하면 회원가입 인증이 완료됩니다. \n\n ' \26 f'회원가입 링크 : http://{domain}/users/{uidb64}/{token}\n\n' \27 f'감사합니다.'28 def is_account_exist(self, **kwargs):29 """이메일 가입 여부 및 계정 이름 확인"""30 user_check = False31 for key, value in kwargs.items():32 if kwargs.get('email'):33 user_check = self.queryset.filter(email=value).values(key).exists()34 if kwargs.get('username'):35 user_check = self.queryset.filter(username=value).values(key).exists()36 return user_check37 def is_value_phone_check(self, phone):38 """휴대폰 번호 중복 체크"""39 is_phone = self.queryset.filter(phone=phone).exists()40 return is_phone41 def is_valid_email_check(self, email):42 """이메일 형식 체크"""43 try:44 validate_email(email)45 return True46 except Exception as e:47 print(f'이메일 형식 에러 : {e}')48 return False49 def params_validate(self, request):50 """파라미터 유효성 검사"""51 request_data = request.data52 loss_params = []53 is_params_checked = True54 response_message = {}55 status_code = status.HTTP_200_OK56 # 필수 파라미터 체크57 email = request_data.get('email', None)58 password = request_data.get('password', None)59 username = request_data.get('username', None)60 fullname = request_data.get('fullname', None)61 if email is None:62 loss_params.append('email')63 if password is None:64 loss_params.append('password')65 if username is None:66 loss_params.append('username')67 if fullname is None:68 loss_params.append('fullname')69 if loss_params:70 is_params_checked = False71 response_message = {'400 - 1': f'필수파라미터({",".join(loss_params)})가 없습니다.'}72 status_code = status.HTTP_400_BAD_REQUEST73 return response_message, status_code, is_params_checked74 return response_message, status_code, is_params_checked75 def email_send(self, user):76 """email 인증 확인"""77 user_email = UserEmailAuthentication.objects.filter(user__email=user.email).values('security_code').first()78 try:79 title = '[Instagram] 계정 활성화 이메일'80 content = f'인증번호는 {user_email["security_code"]} 입니다.'81 email = EmailMessage(title, content, to=[user.email])82 email.send()83 except Exception as e:84 print(f'email send Error : {e}')85 def signup(self, request):86 """회원가입을 위한 비지니스 로직"""87 request_data = request.data88 is_checked = False89 response_message = {}90 status_code = status.HTTP_400_BAD_REQUEST91 email = request_data.get('email')92 password = request_data.get('password')93 username = request_data.get('username')94 fullname = request_data.get('fullname')95 phone = request_data.get('phone', None)96 photo = request_data.get('photo', None)97 gender = request_data.get('gender', 0)98 web_site = request_data.get('web_site', None)99 introduction = request_data.get('introduction', None)100 if self.is_valid_email_check(email) is False:101 response_message = {'400 - 2': '입력하신 이메일 형식이 잘못되었습니다.'}102 elif 'Insta-left' in email:103 response_message = {'400 - 5': '입력하신 이메일 ID는 사용하실 수 없습니다.'}104 elif self.is_account_exist(email=email) is True:105 response_message = {'400 - 3': '입력하신 이메일로 가입된 계정이 존재합니다.'}106 elif self.is_account_exist(username=username) is True:107 response_message = {'400 - 4': '입력하신 계정이름이 존재합니다.'}108 elif self.is_value_phone_check(phone):109 response_message = {'400 - 6': '입력하신 휴대폰 번호는 사용중입니다.'}110 else:111 with transaction.atomic():112 user = User.objects.create(113 email=email,114 password=password,115 username=username,116 fullname=fullname,117 phone=phone,118 photo=photo,119 gender=gender,120 web_site=web_site,121 introduction=introduction,122 )123 user.set_password(password)124 user.save()125 UserEmailAuthentication.objects.create(126 user=user,127 security_code=random.randrange(1111, 9999) # 보안 코드128 )129 # 이메일 인증 처리 부분130 self.email_send(user)131 status_code = status.HTTP_200_OK132 response_message = {133 "pk": user.pk,134 "email": user.email135 }136 is_checked = True137 return response_message, status_code, is_checked138 def create(self, request, *args, **kwargs):139 """140 회원가입141 ---142 ## /account/signup/143 """144 try:145 response_message, status_code, is_checked = self.params_validate(request)146 if is_checked:147 response_message, status_code, is_checked = self.signup(request)148 return Response(149 data=response_message if is_checked else response_message,150 status=status_code if is_checked else status_code151 )152 except Exception as e:153 print(f'error : {e}')154 response_message = {'500': '서버 에러'}155 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR156 return Response(data=response_message, status=status_code)157class WithdrawalViewSet(viewsets.ModelViewSet):158 """159 partial_update : 회원탈퇴160 """161 queryset = User.objects.all()162 authentication_classes = [JSONWebTokenAuthentication]163 permission_classes = [permissions.IsAuthenticated]164 serializer_class = WithdrawalSerializer165 def params_validate(self, request):166 """파라미터 유효성 검사 (탈퇴이유)"""167 request_data = request.data168 is_params_checked = True169 reason = request_data.get('reason', None)170 return is_params_checked, reason171 def withdrawal(self, user, reason=''): # 탈퇴 사유 적기172 """회원탈퇴를 위한 비지니스 로직 작성"""173 response_message = {}174 status_code = status.HTTP_403_FORBIDDEN175 now = timezone.now().strftime("%Y-%m-%d %H:%M:%S")176 try:177 user.email = f'Insta-left{user.pk}@instagram.com'178 user.username = '탈퇴계정'179 user.fullname = '탈퇴회원'180 user.gender = 0181 user.photo = None182 user.web_site = ''183 user.introduction = f'탈퇴 사유 : {reason} \n 탈퇴 날짜 : {now}'184 user.is_active = False185 user.save()186 is_checked = True187 status_code = status.HTTP_200_OK188 except Exception as e:189 print(f'회원탈퇴 Error : {e}')190 is_checked = False191 response_message = {'403': '회원 탈퇴에 실패하였습니다.'}192 return response_message, status_code, is_checked193 def partial_update(self, request, *args, **kwargs):194 """195 회원탈퇴196 ---197 ## /account/withdrawal/198 """199 try:200 is_params_checked, reason = self.params_validate(request)201 if is_params_checked:202 response_message, status_code, is_checked = self.withdrawal(self.request.user, reason)203 return Response(data=response_message, status=status_code)204 except Exception as e:205 print(f'error : {e}')206 response_message = {'500': '서버 에러'}207 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR208 return Response(data=response_message, status=status_code)209class SigninViewSet(viewsets.ModelViewSet):210 """211 create: 로그인212 """213 queryset = User.objects.all()214 authentication_classes = []215 permission_classes = [permissions.AllowAny]216 serializer_class = SigninSerializer217 def params_validate(self, request):218 """파라미터 유효성 검사"""219 request_data = request.data220 loss_params = []221 is_params_checked = True222 response_message = {}223 status_code = status.HTTP_400_BAD_REQUEST224 email = request_data.get('email', None)225 password = request_data.get('password', None)226 if email is None:227 loss_params.append('email')228 if password is None:229 loss_params.append('password')230 if loss_params:231 is_params_checked = False232 response_message = {'400 - 1': f'필수파라미터({",".join(loss_params)})가 없습니다.'}233 return response_message, status_code, is_params_checked234 return response_message, status_code, is_params_checked235 def signin(self, request):236 """로그인 비지니스 로직"""237 request_data = request.data238 is_checked = False239 response_message = {}240 status_code = status.HTTP_400_BAD_REQUEST241 email = request_data.get('email')242 password = request_data.get('password')243 if 'Insta-left' in email:244 response_message = {'400 - 3': '탈퇴한 회원입니다.'}245 return response_message, status_code, is_checked246 user = authenticate(email=email, password=password) if email and password else None247 if user is None:248 response_message = {249 '400 - 2': '이메일 또는 패스워드가 일치하지 않습니다.(회원 계정 활성을 위해 이메일 인증이 필요합니다.)'250 }251 return response_message, status_code, is_checked252 else:253 JWT_PAYLOAD_HANDLER = api_settings.JWT_PAYLOAD_HANDLER254 JWT_ENCODE_HANDLER = api_settings.JWT_ENCODE_HANDLER255 is_checked = True256 payload = JWT_PAYLOAD_HANDLER(user)257 jwt_token = JWT_ENCODE_HANDLER(payload)258 update_last_login(None, user)259 response_message.update({260 'email': user.email,261 'token': jwt_token262 })263 self.token_save(jwt_token, user)264 status_code = status.HTTP_200_OK265 return response_message, status_code, is_checked266 def token_save(self, jwt, user):267 """발급 token 저장"""268 try:269 token, is_token = JWTokens.objects.get_or_create(270 token=jwt,271 user=user272 )273 # print(is_token)274 # if not is_token:275 # token.delete()276 except Exception as e:277 print(f'token 발급 실패 : {e}')278 def create(self, request, *args, **kwargs):279 """280 로그인281 ---282 ## /account/signin/283 """284 try:285 response_message, status_code, is_checked = self.signin(request)286 if is_checked:287 response_message, status_code, is_checked = self.signin(request)288 return Response(289 data=response_message if is_checked else response_message,290 status=status_code if is_checked else status_code291 )292 except Exception as e:293 print(f'error : {e}')294 response_message = {'500': '서버 에러'}295 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR296 return Response(data=response_message, status=status_code)297class SignoutViewSet(viewsets.ModelViewSet):298 """299 update: 로그아웃300 """301 queryset = User.objects.all()302 permission_classes = [permissions.IsAuthenticated]303 authentication_classes = [JSONWebTokenAuthentication]304 serializer_class = SignoutSerializer305 def signout(self, request):306 """로그아웃 비지니스 로직"""307 is_checked = False308 response_message = {}309 status_code = status.HTTP_400_BAD_REQUEST310 if request.user.is_authenticated:311 is_logout = self.token_check(request.user)312 if not is_logout:313 response_message = {'401': '유효하지 않는 토큰 정보입니다.'}314 status_code = status.HTTP_401_UNAUTHORIZED315 return response_message, status_code, is_checked316 is_checked = True317 status_code = status.HTTP_200_OK318 return response_message, status_code, is_checked319 else:320 response_message = {'400': '유효하지 않은 정보 입니다.'}321 return response_message, status_code, is_checked322 def token_check(self, user):323 """324 로그아웃을 위한 token 체크 (중복 로그아웃 방지)325 """326 is_token = False327 auth_token = self.request.META.get('HTTP_AUTHORIZATION')328 bearer, jwt = auth_token.split(' ')329 token_search = JWTokens.objects.filter(token=jwt, user=user)330 if token_search:331 token_search.delete()332 is_token = True333 return is_token334 def update(self, request, *args, **kwargs):335 """336 로그아웃337 ---338 ## /account/signout/339 """340 try:341 response_message, status_code, is_checked = self.signout(request)342 return Response(343 data=response_message if is_checked else response_message,344 status=status_code if is_checked else status_code345 )346 except Exception as e:347 print(f'error : {e}')348 response_message = {'500': '서버 에러'}349 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR350 return Response(data=response_message, status=status_code)351class ActivateViewSet(viewsets.ModelViewSet):352 """353 update: 유저를 활성화한다. (email 인증 코드를 입력한 유저만 로그인 할 수 있다.)354 """355 queryset = UserEmailAuthentication.objects.all()356 authentication_classes = []357 permission_classes = []358 serializer_class = UserEmailAuthenticationSerializer359 def params_validate(self, request):360 """파라미터 유효성 검사"""361 request_data = request.data362 is_params_checked = True363 status_code = status.HTTP_200_OK364 loss_params = []365 email = request_data.get('email', None)366 security_code = request_data.get('security_code', None)367 if email is None:368 loss_params.append('user_id')369 if security_code is None:370 loss_params.append('security_code')371 if security_code is None:372 is_params_checked = False373 response_message = {'400 - 1': '필수파라미터(security_code)가 없습니다.'}374 status_code = status.HTTP_200_OK375 return response_message, status_code, is_params_checked376 else:377 response_message = {378 'email': email,379 'security_code': security_code380 }381 return response_message, status_code, is_params_checked382 def activate(self, email, security_code):383 """email 인증 처리"""384 is_checked = False385 response_message = {'400 - 2': '이메일 인증코드가 잘못되었습니다.'}386 status_code = status.HTTP_400_BAD_REQUEST387 user = User.objects.filter(email=email).first()388 sec_code = self.queryset.filter(user=user).first()389 if user and sec_code.security_code == int(security_code):390 now = timezone.now()391 if sec_code.created_at + datetime.timedelta(minutes=3) >= now:392 is_checked = True393 sec_code.security_code = -1394 sec_code.verification = True395 sec_code.save()396 user.is_active = True397 user.save()398 response_message = {}399 status_code = status.HTTP_200_OK400 return response_message, status_code, is_checked401 def update(self, request, *args, **kwargs):402 try:403 response_message, status_code, is_checked = self.params_validate(request)404 if is_checked:405 email = response_message.get('email')406 security_code = response_message.get('security_code')407 response_message, status_code, is_checked = self.activate(email, security_code)408 return Response(409 data=response_message if is_checked else response_message,410 status=status_code if is_checked else status_code411 )412 except Exception as e:413 print(f'error : {e}')414 response_message = {'500': '서버 에러'}415 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR416 return Response(data=response_message, status=status_code)417class UserInformationViewSet(viewsets.ModelViewSet):418 """419 list: 유저정보 조회420 partial_update: 유저정보 수정421 """422 authentication_classes = [JSONWebTokenAuthentication]423 permission_classes = [permissions.IsAuthenticated]424 queryset = User.objects.all()425 serializer_class = UserSerializer426 def get_user_information(self, user):427 user_information = {}428 status_code = status.HTTP_403_FORBIDDEN429 token = self.request.META.get('HTTP_AUTHORIZATION')430 if user.is_authenticated and JWTokens.objects.filter(token=token, user=user).exists():431 email_auth = UserEmailAuthentication.objects.filter(user=user).first()432 user_information.update({433 "id": user.pk,434 "email": user.email,435 "phone": user.phone,436 "username": user.username,437 "fullname": user.fullname,438 "photo": user.photo.url if user.photo else None,439 "gender": user.gender,440 "web_site": user.web_site,441 "introduction": user.introduction,442 "is_active": user.is_active,443 "is_superuser": user.is_superuser,444 "user_email_authentication": {445 "verification": email_auth.verification if email_auth else None446 }447 })448 if user.is_superuser:449 admin = Administrator.objects.filter(user=user).first()450 user_information.update({451 "administrator": {452 "type": '전체 관리자' if admin.type == 0 else '비지니스 관리자',453 "is_active": admin.is_active454 }455 })456 status_code = status.HTTP_200_OK457 else:458 user_information = {'403': '자격 인증 정보가 없어 유저 정보를 확인할 수 없습니다.'}459 return user_information, status_code460 def params_validate(self, request):461 """유저 정보 수정 파라미터 검사"""462 request_data = request.data463 is_params_checked = True464 response_message = {}465 status_code = status.HTTP_200_OK466 fullname = request_data.get('fullname', None)467 photo = request_data.get('photo', None)468 gender = request_data.get('gender', None)469 web_site = request_data.get('web_site', None)470 introduction = request_data.get('introduction', None)471 if fullname is not None:472 response_message.update({'fullname': fullname})473 if photo is not None:474 print(f'photo : {photo}')475 response_message.update({'photo': photo})476 if gender is not None:477 response_message.update({'gender': gender})478 if web_site is not None:479 response_message.update({'web_site': web_site})480 if introduction is not None:481 response_message.update({'introduction': introduction})482 return response_message, status_code, is_params_checked483 def user_information_update(self, request, **kwargs):484 response_message = {}485 is_checked = False486 status_code = status.HTTP_400_BAD_REQUEST487 user = User.objects.filter(email=request.user.email).first()488 try:489 if user:490 for key, value in kwargs.items():491 if 'fullname' is key:492 user.fullname = value493 if 'photo' is key:494 user.photo = value495 if 'gender' is key:496 user.gender = value497 if 'web_site' is key:498 user.web_site = value499 if 'introduction' is key:500 user.introduction = value501 user.save()502 is_checked = True503 status_code = status.HTTP_200_OK504 return response_message, status_code, is_checked505 else:506 response_message = {'400': '존재하지 않는 사용자 입니다.'}507 return response_message, status_code, is_checked508 except Exception as e:509 print(f'유저 정보 수정 error : {e}')510 return response_message, status_code, is_checked511 def list(self, request, *args, **kwargs):512 """513 유저정보 조회514 ---515 ## /account/information/516 """517 try:518 user_information, status_code = self.get_user_information(self.request.user)519 return Response(data=user_information, status=status_code)520 except Exception as e:521 print(f'error : {e}')522 response_message = {'500': '서버 에러'}523 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR524 return Response(data=response_message, status=status_code)525 def partial_update(self, request, *args, **kwargs):526 """527 유저정보 수정528 ---529 ## /account/information/530 """531 try:532 response_message, status_code, is_checked = self.params_validate(request)533 if is_checked:534 response_message, status_code, is_checked = self.user_information_update(request, **response_message)535 return Response(536 data=response_message if is_checked else response_message,537 status=status_code if is_checked else status_code538 )539 except Exception as e:540 print(f'error : {e}')541 response_message = {'500': '서버 에러'}542 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR...

Full Screen

Full Screen

use.py

Source:use.py Github

copy

Full Screen

1from rest_framework import viewsets, status2from rest_framework.pagination import PageNumberPagination3from rest_framework.permissions import IsAuthenticated, AllowAny4from rest_framework.response import Response5from rest_framework_jwt.authentication import JSONWebTokenAuthentication6from apps.api.serializers.use import PostSerializer, PostFavSerializer, CommentSerializer, CommentLikeSerializer, \7 FollowingSerializer8from core.use.models import Post, PostLike, Comments, CommentsLike, Following9from core.account.models import User10class PostsViewSet(viewsets.ModelViewSet):11 """12 list: 게시물 목록 조회13 create: 게시물 생성14 """15 serializer_class = PostSerializer16 authentication_classes = [JSONWebTokenAuthentication]17 permission_classes = [IsAuthenticated]18 pagination = PageNumberPagination()19 def get_queryset(self):20 return Post.objects.all().order_by('-id')21 def post_list(self, request):22 is_checked = True23 status_code = status.HTTP_200_OK24 try:25 self.pagination.page_size = 2026 query = self.get_queryset()27 result = self.pagination.paginate_queryset(query, request)28 serializer = PostSerializer(result, many=True)29 return serializer, status_code, is_checked30 except Exception as e:31 print(f'게시물 조회 실패 : {e}')32 response_message = {'400': '게시물을 조회 할 수 없습니다.'}33 status_code = status.HTTP_400_BAD_REQUEST34 is_checked = False35 return response_message, status_code, is_checked36 def list(self, request, *args, **kwargs):37 """38 게시물 목록 조회39 ---40 ## /use/posts/41 """42 try:43 response_message, status_code, is_checked = self.post_list(request)44 if is_checked:45 return self.pagination.get_paginated_response(response_message.data)46 return Response(data=response_message, status=status_code)47 except Exception as e:48 print(f'error : {e}')49 response_message = {'500': '서버 에러'}50 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR51 return Response(data=response_message, status=status_code)52 def params_validate(self, request):53 """게시물 생성 파라미터 검사"""54 request_data = request.data55 is_params_checked = True56 response_message = {}57 status_code = status.HTTP_200_OK58 photo = request_data.get('photo', None) # 게시할 사진59 if photo is None:60 is_params_checked = False61 response_message = {'400 - 1': '필수파라미터(photo)가 없습니다.'}62 status_code = status.HTTP_400_BAD_REQUEST63 return response_message, status_code, is_params_checked64 return response_message, status_code, is_params_checked65 def post_create(self, request):66 """게시물 생성 비지니스 로직"""67 request_data = request.data68 is_checked = False69 status_code = status.HTTP_400_BAD_REQUEST70 try:71 post = Post.objects.create(72 user=request.user,73 photo=request_data.get('photo'),74 content=request_data.get('content', None),75 )76 serializer = PostSerializer(post)77 response_message = serializer.data78 is_checked = True79 status_code = status.HTTP_201_CREATED80 return response_message, status_code, is_checked81 except Exception as e:82 response_message = {'400 - 2': '게시물 생성을 실패하였습니다.(사진이 없습니다.)'}83 return response_message, status_code, is_checked84 def create(self, request, *args, **kwargs):85 """86 게시물 생성87 ---88 ## /use/posts/89 """90 try:91 response_message, status_code, is_checked = self.params_validate(request)92 if is_checked:93 response_message, status_code, is_checked = self.post_create(request)94 return Response(95 data=response_message if is_checked else response_message,96 status=status_code if is_checked else status_code97 )98 except Exception as e:99 print(f'error : {e}')100 response_message = {'500': '서버 에러'}101 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR102 return Response(data=response_message, status=status_code)103class PostViewSet(viewsets.ModelViewSet):104 """105 retrieve: 게시물 조회106 partial_update: 게시물 수정107 destroy: 게시물 삭제108 """109 queryset = Post.objects.all()110 serializer_class = PostSerializer111 authentication_classes = [JSONWebTokenAuthentication]112 def get_permissions(self):113 """http method 권한 핸들링"""114 if self.action == 'patch' or self.action == 'delete':115 permission_classes = [IsAuthenticated]116 else:117 permission_classes = [AllowAny]118 return [permission() for permission in permission_classes]119 def post_detail(self, pk):120 is_checked = False121 status_code = status.HTTP_400_BAD_REQUEST122 response_message = {}123 try:124 post = self.queryset.get(pk=pk)125 count = PostLike.objects.filter(post=post).count()126 response_message.update({127 'id': post.pk,128 'user': post.user.email,129 'photo': post.photo.url,130 'content': post.content,131 'like_count': count,132 'created_at': post.created_at.strftime('%Y-%m-%d %H:%M:%S')133 })134 status_code = status.HTTP_200_OK135 is_checked = True136 except Post.DoesNotExist:137 response_message = {'400 - 2': '게시물이 없습니다.'}138 return response_message, status_code, is_checked139 def retrieve(self, request, *args, **kwargs):140 """141 게시물 조회142 ---143 ## /use/post/<int:pk>144 """145 try:146 pk = kwargs.get('pk')147 response_message, status_code, is_checked = self.params_check(pk)148 if is_checked:149 response_message, status_code, is_checked = self.post_detail(pk)150 return Response(151 data=response_message if is_checked else response_message,152 status=status_code if is_checked else status_code153 )154 except Exception as e:155 print(f'error : {e}')156 response_message = {'500': '서버 에러'}157 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR158 return Response(data=response_message, status=status_code)159 def params_patch_validate(self, request, pk):160 """게시물 수정 파라미터 검사"""161 request_data = request.data162 is_params_checked = True163 response_message = {}164 status_code = status.HTTP_200_OK165 photo = request_data.get('photo', None)166 content = request_data.get('content', None)167 if pk is None:168 is_params_checked = False169 response_message = {'400 - 1': '필수파라미터(pk)가 없습니다.'}170 return response_message, status_code, is_params_checked171 if photo is not None:172 response_message.update({'photo': photo})173 if content is not None:174 response_message.update({'content': content})175 response_message.update({'pk': pk})176 return response_message, status_code, is_params_checked177 def post_patch(self, request, **kwargs):178 """게시물 수정 비지니스 로직"""179 is_checked = False180 response_message = {}181 status_code = status.HTTP_400_BAD_REQUEST182 try:183 post = self.queryset.get(id=kwargs.get('pk'))184 if request.user != post.user:185 response_message = {'400 - 2': '게시물에 접근할 권한이 없습니다.'}186 return response_message, status_code, is_checked187 elif post:188 for key, value in kwargs.items():189 if 'photo' is key:190 post.photo = value191 if 'content' is key:192 post.content = value193 post.save()194 is_checked = True195 status_code = status.HTTP_200_OK196 response_message = {'message': '게시물이 수정되었습니다.'}197 return response_message, status_code, is_checked198 except Post.DoesNotExist:199 response_message = {'400 - 3': '게시물이 존재하지 않습니다.'}200 return response_message, status_code, is_checked201 except Exception as e:202 print(f'게시물 수정 Error : {e}')203 return response_message, status_code, is_checked204 def partial_update(self, request, *args, **kwargs):205 """206 게시물 수정207 ---208 ## /use/post/<int:pk>209 """210 try:211 response_message, status_code, is_checked = self.params_patch_validate(request, kwargs.get('pk'))212 if is_checked:213 response_message, status_code, is_checked = self.post_patch(request, **response_message)214 return Response(215 data=response_message if is_checked else response_message,216 status=status_code if is_checked else status_code217 )218 except Exception as e:219 print(f'error : {e}')220 response_message = {"500": "서버 에러"}221 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR222 return Response(data=response_message, status=status_code)223 def params_check(self, pk):224 """게시물 삭제 파라미터 검사 (해당 게시물의 id값)"""225 is_checked = True226 response_message = {}227 status_code = status.HTTP_200_OK228 if pk is None:229 is_checked = False230 response_message = {'400 - 1': '게시물이 존재 하지 않습니다.'}231 status_code = status.HTTP_400_BAD_REQUEST232 return response_message, status_code, is_checked233 return response_message, status_code, is_checked234 def post_delete(self, request, pk):235 """게시물 삭제"""236 response_message = {}237 status_code = status.HTTP_400_BAD_REQUEST238 is_checked = False239 try:240 post = self.queryset.get(pk=pk)241 if request.user != post.user:242 response_message = {'400 - 2': '게시물에 접근할 권한이 없습니다.'}243 else:244 post.delete()245 response_message = {'message': '게시물이 삭제되었습니다.'}246 status_code = status.HTTP_200_OK247 return response_message, status_code, is_checked248 except Post.DoesNotExist:249 response_message = {'400 - 3': '게시물이 존재하지 않습니다.'}250 return response_message, status_code, is_checked251 except Exception as e:252 print(f'게시물 삭제 error : {e}')253 return response_message, status_code, is_checked254 def destroy(self, request, *args, **kwargs):255 """256 게시물 삭제257 ---258 ## /use/post/<int:pk>259 """260 try:261 pk = kwargs.get('pk')262 response_message, status_code, is_checked = self.params_check(pk)263 if is_checked:264 response_message, status_code, is_checked = self.post_delete(request, pk)265 return Response(266 data=response_message if is_checked else response_message,267 status=status_code if is_checked else status_code268 )269 except Exception as e:270 print(f'error : {e}')271 response_message = {'500': '서버 에러'}272 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR273 return Response(data=response_message, status=status_code)274class PostFavViewSet(viewsets.ModelViewSet):275 """276 create: 게시물 좋아요277 """278 permission_classes = [IsAuthenticated]279 authentication_classes = [JSONWebTokenAuthentication]280 serializer_class = PostFavSerializer281 queryset = PostLike.objects.all()282 def params_validate(self, request):283 """파라미터 검사"""284 request_data = request.data285 response_message = {}286 status_code = status.HTTP_200_OK287 is_checked = True288 post_id = request_data.get('post_id')289 if not post_id:290 response_message = {'400': '필수파라미터(post_id)가 없습니다.'}291 status_code = status.HTTP_400_BAD_REQUEST292 is_checked = False293 return response_message, status_code, is_checked294 return response_message, status_code, is_checked295 def post_like(self, request):296 request_data = request.data297 response_message = {}298 status_code = status.HTTP_400_BAD_REQUEST299 is_checked = False300 post_id = request_data.get('post_id')301 try:302 post = Post.objects.get(id=post_id)303 fav = self.queryset.filter(post=post, user=request.user).first()304 if not fav:305 """해당 사용자가 좋아요 누른적 없을때 (좋아요 +1)"""306 self.queryset.create(307 post=post,308 user=request.user309 )310 response_message = {'message': f'게시물({post_id}) 좋아요'}311 status_code = status.HTTP_201_CREATED312 is_checked = True313 return response_message, status_code, is_checked314 else:315 fav.delete()316 response_message = {'message': f'게시물({post_id}) 좋아요 취소'}317 status_code = status.HTTP_200_OK318 is_checked = True319 return response_message, status_code, is_checked320 except Post.DoesNotExist:321 response_message = {'400': '게시물이 존재하지 않습니다.'}322 return response_message, status_code, is_checked323 def create(self, request, *args, **kwargs):324 """325 게시물 좋아요326 ---327 ## use/post/favs328 """329 try:330 response_message, status_code, is_checked = self.params_validate(request)331 if is_checked:332 response_message, status_code, is_checked = self.post_like(request)333 return Response(334 data=response_message if is_checked else response_message,335 status=status_code if is_checked else status_code336 )337 except Exception as e:338 print(f'error : {e}')339 response_message = {'500': '서버 에러'}340 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR341 return Response(data=response_message, status=status_code)342class CommentViewSet(viewsets.ModelViewSet):343 """344 create: 댓글 작성345 """346 queryset = Comments.objects.all()347 authentication_classes = [JSONWebTokenAuthentication]348 permission_classes = [IsAuthenticated]349 serializer_class = CommentSerializer350 def params_validate(self, request):351 """댓글 파라미터 검사"""352 request_data = request.data353 is_checked = True354 response_message = {}355 status_code = status.HTTP_200_OK356 loss_params = []357 content = request_data.get('content', None)358 if content is None:359 loss_params.append('content')360 if loss_params:361 response_message = {'400 - 1': f'필수파라미터({",".join(loss_params)})가 없습니다.'}362 status_code = status.HTTP_400_BAD_REQUEST363 return response_message, status_code, is_checked364 def comment_create(self, request, pk):365 """댓글 생성 로직"""366 request_data = request.data367 is_checked = False368 status_code = status.HTTP_400_BAD_REQUEST369 response_message = {}370 try:371 post = Post.objects.get(pk=pk)372 Comments.objects.create(373 user=request.user,374 post=post,375 content=request_data.get('content')376 )377 status_code = status.HTTP_201_CREATED378 is_checked = True379 except Post.DoesNotExist:380 response_message = {'message': '게시물이 없습니다.'}381 except Exception as e:382 print(f'댓글 생성 실패 : {e}')383 response_message = {'400 - 2': '댓글 생성을 실패하였습니다.'}384 return response_message, status_code, is_checked385 def create(self, request, *args, **kwargs):386 """387 댓글 작성388 ---389 ## use/post/<int:pk>/comment390 """391 try:392 pk = kwargs.get('pk')393 response_message, status_code, is_checked = self.params_validate(request)394 if is_checked:395 response_message, status_code, is_checked = self.comment_create(request, pk)396 return Response(397 data=response_message if is_checked else response_message,398 status=status_code if is_checked else status_code399 )400 except Exception as e:401 print(f'error : {e}')402 response_message = {'500': '서버 에러'}403 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR404 return Response(data=response_message, status=status_code)405class CommentFavViewSet(viewsets.ModelViewSet):406 """407 create: 댓글 좋아요408 """409 permission_classes = [IsAuthenticated]410 authentication_classes = [JSONWebTokenAuthentication]411 serializer_class = CommentLikeSerializer412 queryset = CommentsLike.objects.all()413 def params_validate(self, request):414 request_data = request.data415 response_message = {}416 status_code = status.HTTP_200_OK417 is_checked = True418 comment_id = request_data.get('comment_id')419 if not comment_id:420 response_message = {'400 - 1': '필수파라미터(comment_id)가 없습니다.'}421 status_code = status.HTTP_400_BAD_REQUEST422 is_checked = False423 return response_message, status_code, is_checked424 return response_message, status_code, is_checked425 def comment_favs_create(self, request):426 request_data = request.data427 response_message = {}428 status_code = status.HTTP_400_BAD_REQUEST429 is_checked = False430 try:431 comment_id = request_data.get('comment_id')432 comment = Comments.objects.get(id=comment_id)433 comment_fav = self.queryset.filter(comment=comment, user=self.request.user).first()434 if not comment_fav:435 """좋아요 +1"""436 self.queryset.create(437 comment=comment,438 user=self.request.user439 )440 response_message = {'message': f'댓글({comment_id}) 좋아요'}441 status_code = status.HTTP_201_CREATED442 is_checked = True443 else:444 """좋아요 -1"""445 comment_fav.delete()446 response_message = {'message': f'댓글({comment_id}) 좋아요 취소'}447 status_code = status.HTTP_200_OK448 is_checked = True449 except Comments.DoesNotExist:450 response_message = {'400 - 2': '댓글이 존재하지 않습니다.'}451 return response_message, status_code, is_checked452 def create(self, request, *args, **kwargs):453 """454 댓글 좋아요455 ---456 ## use/comment/favs457 """458 try:459 response_message, status_code, is_checked = self.params_validate(request)460 if is_checked:461 response_message, status_code, is_checked = self.comment_favs_create(request)462 return Response(463 data=response_message if is_checked else response_message,464 status=status_code if is_checked else status_code465 )466 except Exception as e:467 print(f'error : {e}')468 response_message = {'500': '서버 에러'}469 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR470 return Response(data=response_message, status=status_code)471class FollowViewSet(viewsets.ModelViewSet):472 """473 create: 팔로우 추가474 """475 permission_classes = [IsAuthenticated]476 authentication_classes = [JSONWebTokenAuthentication]477 serializer_class = FollowingSerializer478 queryset = Following479 def params_validate(self, request):480 request_data = request.data481 response_message = {}482 status_code = status.HTTP_200_OK483 is_checked = True484 follow_id = request_data.get('follow_id')485 if not follow_id:486 response_message = {'400 - 1': '필수파라미터(follow_id)가 없습니다.'}487 status_code = status.HTTP_400_BAD_REQUEST488 is_checked = False489 return response_message, status_code, is_checked490 return response_message, status_code, is_checked491 def follow_create(self, request):492 status_code = status.HTTP_400_BAD_REQUEST493 is_checked = False494 follow_user = User.objects.filter(id=request.data.get('follow_id')).first()495 if not follow_user:496 response_message = {'400 - 2': 'follow 할 상대가 존재하지 않습니다.'}497 return response_message, status_code, is_checked498 follow = Following.objects.filter(following_user=follow_user, user=request.user).first()499 if follow is None:500 if follow_user == request.user:501 response_message = {'message': '자신을 follow할 순 없습니다.'}502 status_code = status.HTTP_200_OK503 is_checked = True504 elif 'Insta-left' in follow_user.email and not follow_user.is_active:505 response_message = {'message': '이미 탈퇴한 회원입니다.'}506 status_code = status.HTTP_200_OK507 is_checked = True508 else:509 Following.objects.create(510 following_user=follow_user,511 user=request.user512 )513 response_message = {'message': f'{request.user}님이 {follow_user}님을 follow 하였습니다.'}514 status_code = status.HTTP_201_CREATED515 is_checked = True516 return response_message, status_code, is_checked517 else:518 follow.delete()519 response_message = {'message': f'{request.user}님이 {follow_user}님을 follow 취소 하였습니다.'}520 return response_message, status_code, is_checked521 def create(self, request, *args, **kwargs):522 """523 팔로우 추가524 ---525 ## use/follow526 """527 try:528 response_message, status_code, is_checked = self.params_validate(request)529 if is_checked:530 response_message, status_code, is_checked = self.follow_create(request)531 return Response(532 data=response_message if is_checked else response_message,533 status=status_code if is_checked else status_code534 )535 except Exception as e:536 print(f'error : {e}')537 response_message = {'500': '서버 에러'}538 status_code = status.HTTP_500_INTERNAL_SERVER_ERROR...

Full Screen

Full Screen

test_users.py

Source:test_users.py Github

copy

Full Screen

1from apps.api.views.account import SignupViewSet, WithdrawalViewSet, SigninViewSet, ActivateViewSet2from core.account.models import User, UserEmailAuthentication3from tests.tests import Test4class UsersTest(Test):5 """유저에 관련된 테스트"""6 def setUp(self):7 super().setUp()8 self.request.data = {9 'email': self.user_email,10 'phone': self.user_phone,11 'username': self.user_username,12 'password': self.user_password13 }14 def test_signup(self):15 """회원가입 성공"""16 print('[회원가입] 성공')17 self.request.data = {18 'email': 'testSignup@test.com',19 'password': '1234qwer',20 'username': '테스트회원가입',21 'fullname': '테스트계정회원가입',22 'phone': '01033334444',23 'gender': 2,24 }25 user_signup = SignupViewSet()26 message, status, is_checked = user_signup.signup(self.request)27 self.assertEqual(True, is_checked)28 def test_signup_email_overlap(self):29 """회원가입 이메일 중복일때"""30 print('[회원가입] 이메일 중복')31 user_signup = SignupViewSet()32 self.request.data = {33 'email': 'testSignup@test.com',34 'password': '1234qwer',35 'username': '테스트회원가입1',36 'fullname': '테스트계정회원가입1',37 'phone': '01033334441',38 'gender': 2,39 }40 user_signup.signup(self.request)41 self.request.data = {42 'email': 'testSignup@test.com',43 'password': '1234qwer',44 'username': '테스트회원가입2',45 'fullname': '테스트계정회원가입2',46 'phone': '01033334442',47 'gender': 2,48 }49 message, status, is_checked = user_signup.signup(self.request)50 self.assertEqual(False, is_checked)51 self.assertEqual('400 - 3', '400 - 3' if '400 - 3' in message.keys() else '0')52 def test_signup_phone_overlap(self):53 """회원가입 휴대폰 번호 중복일때"""54 print('[회원가입] 휴대폰 번호 중복')55 user_signup = SignupViewSet()56 self.request.data = {57 'email': 'testSignup1@test.com',58 'password': '1234qwer',59 'username': '테스트회원가입1',60 'fullname': '테스트계정회원가입1',61 'phone': '01033334441',62 'gender': 2,63 }64 user_signup.signup(self.request)65 self.request.data = {66 'email': 'testSignup2@test.com',67 'password': '1234qwer',68 'username': '테스트회원가입2',69 'fullname': '테스트계정회원가입2',70 'phone': '01033334441',71 'gender': 2,72 }73 message, status, is_checked = user_signup.signup(self.request)74 self.assertEqual(False, is_checked)75 self.assertEqual('400 - 6', '400 - 6' if '400 - 6' in message.keys() else '0')76 def test_signup_left_email_id_overlap(self):77 """78 회원가입시 사용할 수 없는 이메일 ID79 -> 회원탈퇴시 사용자 정보 보호에 따라 email ID가 'Insta-left{pk}' 로 변경됨80 """81 print("[회원가입] 사용할 수 없는 email ID")82 user_signup = SignupViewSet()83 self.request.data = {84 'email': 'Insta-left1231@test.com',85 'password': '1234qwer',86 'username': '테스트회원가입',87 'fullname': '테스트계정회원가입',88 'phone': '01033334444',89 'gender': 2,90 }91 message, status, is_checked = user_signup.signup(self.request)92 self.assertEqual(False, is_checked)93 self.assertEqual('400 - 5', '400 - 5' if '400 - 5' in message.keys() else '0')94 def test_signup_username_overlap(self):95 """회원가입 계정이름이 중복일때"""96 print("[회원가입] 계정이름 중복")97 user_signup = SignupViewSet()98 self.request.data = {99 'email': 'testSignup1@test.com',100 'password': '1234qwer',101 'username': '테스트회원가입1',102 'fullname': '테스트계정회원가입1',103 'phone': '01033334441',104 'gender': 2,105 }106 user_signup.signup(self.request)107 self.request.data = {108 'email': 'testSignup2@test.com',109 'password': '1234qwer',110 'username': '테스트회원가입1',111 'fullname': '테스트계정회원가입2',112 'phone': '01033334441',113 'gender': 2,114 }115 message, status, is_checked = user_signup.signup(self.request)116 self.assertEqual(False, is_checked)117 self.assertEqual('400 - 4', '400 - 4' if '400 - 4' in message.keys() else '0')118 def test_signup_email_check_overlap(self):119 """회원가입 이메일 형식이 잘못되었을때"""120 print("[회원가입] 이메일 형식이 잘못되었을때")121 user_signup = SignupViewSet()122 self.request.data = {123 'email': 'abcdefg',124 'password': '1234qwer',125 'username': '테스트회원가입1',126 'fullname': '테스트계정회원가입2',127 'phone': '01033334441',128 'gender': 2,129 }130 message, status, is_checked = user_signup.signup(self.request)131 self.assertEqual(False, is_checked)132 self.assertEqual('400 - 2', '400 - 2' if '400 - 2' in message.keys() else '0')133 def test_signup_activate(self):134 """회원가입 후 email 인증 코드 생성"""135 print('[회원가입] 이메일 인증코드 생성 확인')136 user_signup = SignupViewSet()137 self.request.data = {138 'email': 'testSignup1@test.com',139 'password': '1234qwer',140 'username': '테스트회원가입1',141 'fullname': '테스트계정회원가입1',142 'phone': '01033334441',143 'gender': 2,144 }145 message, status, is_checked = user_signup.signup(self.request)146 if is_checked:147 user = User.objects.get(email=self.request.data.get('email'))148 user_code = UserEmailAuthentication.objects.filter(user=user).exists()149 else:150 user, user_code = None, None151 self.assertEqual(True, user_code)152 def test_withdrawal(self):153 """회원탈퇴 성공"""154 print('[회원탈퇴] 성공')155 user_signup = SignupViewSet()156 user_withdrawal = WithdrawalViewSet()157 self.request.data = {158 'email': 'testSignup1@test.com',159 'password': '1234qwer',160 'username': '테스트회원가입1',161 'fullname': '테스트계정회원가입1',162 'phone': '01033334441',163 'gender': 2,164 }165 reason = '탈퇴 테스트'166 message, status, is_checked = user_signup.signup(self.request)167 if is_checked:168 user = User.objects.get(email=self.request.data.get('email'))169 else:170 user = None171 message, status, is_checked = user_withdrawal.withdrawal(user, reason=reason)172 self.assertEqual(True, is_checked)173 self.assertEqual(f'Insta-left{user.pk}@instagram.com', user.email)174 self.assertEqual(False, user.is_active)175 def test_signin(self):176 """로그인 성공"""177 print('[로그인] 성공')178 user_signin = SigninViewSet()179 message, status, is_checked = user_signin.signin(self.request)180 self.assertEqual(True, is_checked)181 def test_signin_email_check(self):182 """탈퇴한 회원이 로그인 시도할때"""183 print('[로그인] 탈퇴한 회원')184 user_signin = SigninViewSet()185 self.request.data.update({186 'email': 'Insta-left@aaa.com',187 'password': self.user_password188 })189 message, status, is_checked = user_signin.signin(self.request)190 self.assertEqual(False, is_checked)191 self.assertEqual('400 - 3', '400 - 3' if '400 - 3' in message.keys() else '0')192 def test_user_is_email(self):193 """이메일 틀렸을때"""194 print('[로그인] 이메일 실패')195 user_signin = SigninViewSet()196 self.request.data.update({197 'email': 'testtest@test.com',198 'password': self.user_password199 })200 message, status, is_checked = user_signin.signin(self.request)201 self.assertEqual(False, is_checked)202 self.assertEqual('400 - 2', '400 - 2' if '400 - 2' in message.keys() else '0')203 def test_user_is_password(self):204 """비밀번호 틀렸을때"""205 print('[로그인] 비밀번호 실패')206 user_signin = SigninViewSet()207 self.request.data.update({208 'email': self.user_email,209 'password': '11111'210 })211 message, status, is_checked = user_signin.signin(self.request)212 self.assertEqual(False, is_checked)213 self.assertEqual('400 - 2', '400 - 2' if '400 - 2' in message.keys() else '0')214 def test_user_activate(self):215 """유저 활성화"""216 print('[이메일 인증코드 확인] 인증코드 확인 성공')217 user_signup = SignupViewSet()218 activate = ActivateViewSet()219 self.request.data = {220 'email': 'testSignup@test.com',221 'password': '1234qwer',222 'username': '테스트회원가입',223 'fullname': '테스트계정회원가입',224 'phone': '01033334444',225 'gender': 2,226 }227 user_signup.signup(self.request)228 user_code = UserEmailAuthentication.objects.get(user__email=self.request.data.get('email'))229 message, status, is_checked = activate.activate(self.request.data.get('email'), user_code.security_code)230 self.assertEqual(True, is_checked)231 def test_user_activate_error(self):232 """유저 활성화 실패"""233 print('[이메일 인증코드 확인] 인증코드 확인 실패')234 user_signup = SignupViewSet()235 activate = ActivateViewSet()236 self.request.data = {237 'email': 'testSignup@test.com',238 'password': '1234qwer',239 'username': '테스트회원가입',240 'fullname': '테스트계정회원가입',241 'phone': '01033334444',242 'gender': 2,243 }244 user_signup.signup(self.request)245 security_code = '-2'246 message, status, is_checked = activate.activate(self.request.data.get('email'), security_code)...

Full Screen

Full Screen

signalprocessing_groupbox.py

Source:signalprocessing_groupbox.py Github

copy

Full Screen

1from PyQt5 import QtWidgets as qtw2from PyQt5 import QtCore as qtc3class SignalProcessing(qtw.QWidget):4 '''5 Class for building the Signal Processing Groupbox6 Inherited from QWidget.7 --------8 Methods:9 --------10 build_sigproc_gb(self)11 change_anylsis_method(self, current_method)12 change_correction_mode(self, current_mode)13 store_sig_ana_method(self, sig_ana_method)14 store_corr_mode(self, corr_mode)15 store_mayer_source(self, mayer_source)16 store_baseline(self, state_changed, is_checked)17 store_notch(self, state_changed, is_checked)18 store_cut_off(self, cut_off)19 '''20 submit_possible_artefact_correction = qtc.pyqtSignal(list)21 submit_sig_ana_method = qtc.pyqtSignal(dict)22 submit_corr_mode = qtc.pyqtSignal(dict)23 submit_mayer_source = qtc.pyqtSignal(dict)24 submit_baseline = qtc.pyqtSignal(dict)25 submit_notch = qtc.pyqtSignal(dict)26 submit_low_pass = qtc.pyqtSignal(dict)27 submit_cut_off = qtc.pyqtSignal(dict)28 submit_mayer_on_or_off = qtc.pyqtSignal(str)29 def __init__(self, *args, **kwargs):30 super(SignalProcessing, self).__init__(*args, **kwargs)31 self.build_sigproc_gb()32 def build_sigproc_gb(self):33 '''34 Creates Signal Processing Groupbox layout and its widgets35 '''36 sig_proc_gb = qtw.QGroupBox('Signal Processing')37 outer_layout = qtw.QVBoxLayout()38 outer_layout.addWidget(sig_proc_gb)39 outer_layout.setContentsMargins(0, 0, 0, 0)40 # Labels41 sig_proc_settings = [qtw.QLabel('Signal Analysis Method'), qtw.QLabel('Correction Mode'),42 qtw.QLabel('Mayer Waves Source')]43 # Widgets44 self.sig_ana_cb = qtw.QComboBox()45 analysis_methods = ['TF (Transfer Function Models)', 'CAR (Common Average Reference)']46 self.sig_ana_cb.addItems(analysis_methods)47 self.sig_ana_cb.setStyleSheet("QComboBox::drop-down")48 self.sig_ana_cb.currentIndexChanged[str].connect(self.change_anylsis_method)49 self.sig_ana_cb.currentTextChanged.connect(self.store_sig_ana_method)50 self.corr_mode_cb = qtw.QComboBox()51 correction_modes = ['Uncorrected', 'Respiration', 'Mayer Waves', 'Mayer and Respiration']52 for mode in correction_modes:53 self.corr_mode_cb.addItem(mode)54 self.corr_mode_cb.currentIndexChanged[str].connect(self.change_correction_mode)55 self.corr_mode_cb.setStyleSheet("QComboBox::drop-down")56 self.corr_mode_cb.currentTextChanged.connect(self.store_corr_mode)57 self.mayer_waves_cb = qtw.QComboBox()58 self.mayer_waves_cb.addItem('Heart Rate')59 self.mayer_waves_cb.setEnabled(False)60 self.mayer_waves_cb.setStyleSheet("QComboBox::drop-down")61 # self.mayer_waves_cb.currentTextChanged.connect(self.store_mayer_source)62 self.baseline_removal_chb = qtw.QCheckBox('Baseline Removal')63 self.baseline_removal_chb.stateChanged.connect(64 lambda val: self.store_baseline(val, self.baseline_removal_chb.isChecked()))65 self.notch_filter_chb = qtw.QCheckBox('Notch Filter')66 self.notch_filter_chb.stateChanged.connect(lambda val: self.store_notch(val, self.notch_filter_chb.isChecked()))67 self.low_pass_chb = qtw.QCheckBox('Low-pass Filter')68 self.low_pass_chb.stateChanged.connect(lambda val: self.store_low_pass(val, self.low_pass_chb.isChecked()))69 cut_off_label = qtw.QLabel('Cut-off Frequency (Hz)')70 self.cut_off_le = qtw.QLineEdit()71 self.cut_off_le.setEnabled(False)72 self.cut_off_le.setStyleSheet('background: #F0F0F0')73 self.cut_off_le.textChanged.connect(self.store_cut_off)74 # Layout75 grid_layout = qtw.QGridLayout()76 grid_layout.setHorizontalSpacing(12)77 grid_layout.setVerticalSpacing(8)78 grid_layout.setContentsMargins(40, 12, 20, 10)79 for setting in range(len(sig_proc_settings)):80 grid_layout.addWidget(sig_proc_settings[setting], setting, 0)81 grid_layout.setAlignment(sig_proc_settings[setting], qtc.Qt.AlignRight)82 grid_layout.addWidget(self.sig_ana_cb, 0, 1)83 grid_layout.addWidget(self.corr_mode_cb, 1, 1)84 grid_layout.addWidget(self.mayer_waves_cb, 2, 1)85 grid_layout.addWidget(self.baseline_removal_chb, 3, 0)86 grid_layout.addWidget(self.notch_filter_chb, 3, 1)87 grid_layout.addWidget(self.low_pass_chb, 4, 0)88 lower_right_layout = qtw.QHBoxLayout()89 lower_right_layout.setContentsMargins(0, 0, 0, 0)90 lower_right_layout.addWidget(cut_off_label)91 lower_right_layout.addWidget(self.cut_off_le)92 grid_layout.addLayout(lower_right_layout, 4, 1)93 sig_proc_gb.setLayout(grid_layout)94 self.setLayout(outer_layout)95 @qtc.pyqtSlot(str)96 def change_anylsis_method(self, current_method):97 '''98 Controls the enabling and disabling of the corresponding settings according the current selected analysis method99 @param current_method: current method selected in sig_ana_cb100 '''101 if current_method == 'TF (Transfer Function Models)':102 self.corr_mode_cb.setEnabled(True)103 self.corr_mode_cb.setCurrentIndex(0)104 elif current_method == 'CAR (Common Average Reference)':105 self.corr_mode_cb.setEnabled(False)106 self.corr_mode_cb.setCurrentIndex(0)107 self.mayer_waves_cb.setEnabled(False)108 @qtc.pyqtSlot(str)109 def change_correction_mode(self, current_mode):110 '''111 Checks the enabling and disabling behaviour of the entering parameters for physiological artefact removal112 according the correction mode selected in corr_mode_cb and emits the checkings to gui_part.settings113 @param current_mode: currently selected correction mode in corr_mode_cb114 '''115 enable_resp_peak = False116 enable_mayer = False117 if current_mode == 'Uncorrected':118 self.mayer_waves_cb.setEnabled(False)119 self.submit_mayer_source.emit({'mayer_waves_source': ''})120 elif current_mode == 'Respiration':121 self.mayer_waves_cb.setEnabled(False)122 enable_resp_peak = True123 self.submit_mayer_source.emit({'mayer_waves_source': ''})124 elif current_mode == 'Mayer Waves':125 self.mayer_waves_cb.setEnabled(True)126 enable_mayer = True127 self.submit_mayer_source.emit({'mayer_waves_source': str(self.mayer_waves_cb.currentText())})128 elif current_mode == 'Mayer and Respiration':129 self.mayer_waves_cb.setEnabled(True)130 enable_resp_peak = True131 enable_mayer = True132 self.submit_mayer_source.emit({'mayer_waves_source': str(self.mayer_waves_cb.currentText())})133 self.submit_possible_artefact_correction.emit([enable_mayer, enable_resp_peak])134 @qtc.pyqtSlot(str)135 def store_sig_ana_method(self, sig_ana_method):136 '''137 Stores signal analysis method138 @param sig_ana_method: selected signal analysis method139 '''140 self.submit_sig_ana_method.emit(141 {'signal_analysis_method': str(sig_ana_method)})142 @qtc.pyqtSlot(str)143 def store_corr_mode(self, corr_mode):144 '''145 Stores correction method146 @param corr_mode: selected correction method147 '''148 self.submit_corr_mode.emit({'correction_mode': str(corr_mode)})149 @qtc.pyqtSlot(str)150 def store_mayer_source(self, mayer_source):151 '''152 Stores Mayer waves source. Only Heart Rate is available at the moment.153 @param mayer_source: selected Mayer waves source. At the moment is always Heart Rate154 '''155 self.submit_mayer_source.emit({'mayer_waves_source': str(mayer_source)})156 @qtc.pyqtSlot(int, bool)157 def store_baseline(self, state_changed, is_checked):158 '''159 Stores if baseline removal is checked160 @param state_changed: int, return value 0 or 2 if state of checkbox changed (2) or not (0)161 @param is_checked: bool, if baseline removal checkbox is checked162 '''163 if state_changed == 0 and is_checked:164 self.submit_baseline.emit({'baseline': is_checked})165 elif state_changed == 0 and not is_checked:166 self.submit_baseline.emit({'baseline': False})167 elif state_changed == 2 and is_checked:168 self.submit_baseline.emit({'baseline': is_checked})169 elif state_changed == 2 and not is_checked:170 self.submit_baseline.emit({'baseline': False})171 @qtc.pyqtSlot(int, bool)172 def store_notch(self, state_changed, is_checked):173 '''174 Stores if noch frequency removal is checked175 @param state_changed: int, return value 0 or 2 if state of checkbox changed (2) or not (0)176 @param is_checked: bool, if notch frequency removal checkbox is checked177 '''178 if state_changed == 0 and is_checked:179 self.submit_notch.emit({'notch': is_checked})180 elif state_changed == 0 and not is_checked:181 self.submit_notch.emit({'notch': False})182 elif state_changed == 2 and is_checked:183 self.submit_notch.emit({'notch': is_checked})184 elif state_changed == 2 and not is_checked:185 self.submit_notch.emit({'notch': False})186 @qtc.pyqtSlot(int, bool)187 def store_low_pass(self, state_changed, is_checked):188 '''189 Stores if applying a low-pass filter is checked and handles the enabling and disabling of the corresponding190 cut-off frequency line entry191 @param state_changed: int, return value 0 or 2 if state of checkbox changed (2) or not (0)192 @param is_checked: bool, if low-pass filter checkbox is checked193 '''194 if state_changed == 0 and is_checked:195 self.submit_low_pass.emit({'low_pass': is_checked})196 self.cut_off_le.setEnabled(True)197 self.cut_off_le.setStyleSheet('background: white')198 elif state_changed == 0 and not is_checked:199 self.submit_low_pass.emit({'low_pass': False})200 self.cut_off_le.setEnabled(False)201 self.cut_off_le.setStyleSheet('background: #F0F0F0')202 self.cut_off_le.setText('')203 elif state_changed == 2 and is_checked:204 self.submit_low_pass.emit({'low_pass': is_checked})205 self.cut_off_le.setEnabled(True)206 self.cut_off_le.setStyleSheet('background: white')207 elif state_changed == 2 and not is_checked:208 self.submit_low_pass.emit({'low_pass': False})209 self.cut_off_le.setEnabled(False)210 self.cut_off_le.setStyleSheet('background: #F0F0F0')211 self.cut_off_le.setText('')212 @qtc.pyqtSlot(str)213 def store_cut_off(self, cut_off):214 '''215 Stores the entered cut-off frequency and checks for correct input216 @param cut_off: str, entered cut-off frequency217 '''218 # check if double219 try:220 if cut_off == '':221 cut_off = ''222 else:223 cut_off = float(cut_off)224 self.submit_cut_off.emit({'cut_off_frequency': cut_off})225 except:226 self.msg_wrong_input = qtw.QMessageBox(qtw.QMessageBox.Information, 'Wrong input format',227 'Only int or float numbers are allowed.')228 self.msg_wrong_input.exec_()...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful