Best Python code snippet using SeleniumBase
account.py
Source:account.py
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...
use.py
Source:use.py
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...
test_users.py
Source:test_users.py
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)...
signalprocessing_groupbox.py
Source:signalprocessing_groupbox.py
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_()...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!