def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = None if user and user.profile.email_confirmed: raise authnz_exceptions.CustomException( detail=_('This email is registered before.')) elif user: permissions.check_send_email_permission(email) user.set_password(serialized_data.data['password']) user.save() utilities.send_email_confirm(user, request) return responses.SuccessResponse().send() else: password = serialized_data.data['password'] user = transactions.register_user_with_email_and_password( email, password) utilities.send_email_confirm(user, request) return responses.SuccessResponse( message=_('Check your email box.')).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): nick_name = serialized_data.data['nick_name'] if request.user.profile.nick_name == nick_name: return responses.SuccessResponse().send() if Profile.objects.filter(nick_name__iexact=nick_name): raise authnz_exceptions.CustomException(detail=_('This nick name exists')) else: return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): if request.user.check_password( serialized_data.data['old_password']): if request.user.is_active: transactions.change_user_password( request.user, serialized_data.data['password']) payload = jwt_payload_handler( request.user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler( jwt_encode_handler(payload), user=request.user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException( detail=_('This user is deactivated, contact us.')) else: raise authnz_exceptions.CustomException( detail=_('Old Password is invalid.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, question_slug, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') question = self.model.objects.get(question_slug=question_slug, is_deleted=False) if not isinstance(request.user, AnonymousUser): question.view.add(request.user) question.total_view += 1 question.save() result = question.answer_set result = result.filter(is_deleted=False) if sort: result = result.order_by(sort) result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def get(self, request, id, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission(request.user, size, index) size = index + size instance = self.model.objects.get(id=id, is_deleted=False) if not instance.has_legal_issue: if not instance.approved: if request.user == instance.creator or (not request.user.is_anonymous and request.user.is_staff): pass else: raise self.model.DoesNotExist serialize_data = self.get_serializer(instance.interviewcomment_set.filter( is_deleted=False, approved=True ).all(), many=True) data = serialize_data.data data = sorted(data, key=lambda x: x['vote_count'], reverse=True) else: data = [] return responses.SuccessResponse(data[index:size], index=index, total=len(data)).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') result = self.model.objects.filter(**arguments) if sort: result = result.order_by(sort) result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def get(self, request, *args, **kwargs): try: arguments = parser.parse(request.GET.urlencode()) size = int(arguments.pop('size', 20)) index = int(arguments.pop('index', 0)) size, index = permissions.pagination_permission( request.user, size, index) size = index + size sort = None if arguments.get('order_by'): sort = arguments.pop('order_by') result = self.model.objects.filter(**arguments) if self.model in MODELS_HAVE_IS_DELETED: result = result.filter(is_deleted=False) if self.model == CompanyReview or self.model == Interview: result = result.filter(approved=True) if sort: result = result.order_by(sort) if self.model in [City, Pros, Cons]: result = result.order_by('-priority') result = result.all() total = len(result) result = result[index:size] data = self.get_serializer(result, many=True) return responses.SuccessResponse(data.data, index=index, total=total).send() except FieldError as e: return responses.ErrorResponse(message=str(e)).send()
def add_report(request): user_id = extract_user_from_header(request) latitude = request.POST.get('latitude', None) longitude = request.POST.get('longitude', None) images = request.POST.get('images', None) if not user_id: return responses.StandardResponse(error_code=(errors.NOT_AUTHORIZED[0], 'The JWT authorization is missing, please provide JWT in the headers as per the docs')).json() if not latitude or not longitude: return responses.StandardResponse(error_code=(errors.INVALID_PARAMS[0], 'The latitude or longitude are missing')).json() try: print('The images are', images) images = loads(str(images)) except Exception as e: print(e) return responses.StandardResponse(error_code=(errors.INVALID_PARAMS[0], 'The images are missing or not formatted properly. Please send a JSON-encoded string of array of URLs')).json() try: report = CitizenReport( citizen=CustomUser.objects.get(pk=int(user_id)), latitude=float(latitude), longitude=float(latitude), images=dumps(images), status='unread' ) report.save() except Exception as e: print(e) return responses.StandardResponse(error_code=errors.SOMETHING_WENT_WRONG).json() return responses.SuccessResponse(action_name='ADD_REPORT').json()
def post(self, request, backend, *args, **kwargs): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): token = serialized_data.data['token'] if backend.lower() == 'google': try: resp_user = id_token.verify_oauth2_token(token, google_requests.Request(), settings.GOOGLE_OAUTH_ID) except Exception as e: return responses.ErrorResponse(message='Error in google open auth', dev_error=str(e), status=400).send() if resp_user['iss'] not in ['accounts.google.com', 'https://accounts.google.com']: raise authnz_exceptions.CustomException(detail=_('Google Wrong issuer.')) if not resp_user.get('email') or not resp_user.get('given_name') or \ not resp_user.get('family_name') or not resp_user.get('picture'): raise authnz_exceptions.CustomException( detail=_('Scope need to have email, given name, family, picture')) email = resp_user['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = transactions.open_auth_user_creator(email, resp_user['given_name'], resp_user['family_name'], resp_user['picture']) else: raise authnz_exceptions.CustomException(detail=_('Wrong backend')) if user.is_active: payload = jwt_payload_handler(user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=user) else: raise authnz_exceptions.CustomException( detail=_('Your user account is deactivated, contact us for more information.')) return responses.SuccessResponse(jwt_token).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, *args, **kwargs): try: interview_list = self.model.objects.filter(creator=request.user) data = self.get_serializer(interview_list, many=True) return responses.SuccessResponse(data.data).send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialize_data = self.serializer_class(data=request.data) if serialize_data.is_valid(raise_exception=True): email = serialize_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist: raise authnz_exceptions.CustomException(detail=_('Email does not exist.')) if user.is_active: forgot_password_token = cache.get('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) if forgot_password_token == serialize_data.data['token']: transactions.change_user_password(user, serialize_data.data['password']) cache.delete('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) payload = jwt_payload_handler(user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=user) return responses.SuccessResponse(jwt_token).send() elif not forgot_password_token: raise authnz_exceptions.CustomException(detail=_('Token timeout.')) else: raise authnz_exceptions.CustomException(detail=_('We sent a new token recently please try it.')) else: raise authnz_exceptions.CustomException(detail=_('Your account is inactive.')) except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialize_data = self.serializer_class(data=request.data) if serialize_data.is_valid(raise_exception=True): email = serialize_data.data['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist: raise authnz_exceptions.CustomException(detail=_('Email does not exist.')) if user.is_active and user.email: forgot_password_token = cache.get('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN)) if not forgot_password_token: permissions.check_send_email_permission(email) forgot_password_token = utilities.forgot_password_delete_account_token_generator() utilities.send_password_forget_token_email(user, request, forgot_password_token) cache.set('{}{}'.format(user.username, settings.CACHE_FORGOT_PASSWORD_TOKEN), forgot_password_token, timeout=settings.TIMEOUT_FORGOT_PASSWORD_TOKEN) return responses.SuccessResponse(message=_('Check Your email for token.')).send() else: raise authnz_exceptions.CustomException(detail=_('We sent an token recently please try later')) elif not user.is_active: raise authnz_exceptions.CustomException(detail=_('This account is inactive.')) else: raise authnz_exceptions.CustomException(detail=_('This account has no email.')) except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except Exception as e: return responses.ErrorResponse(message=str(e)).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(profile__email=email, profile__email_confirmed=True) except User.DoesNotExist: raise authnz_exceptions.CustomException( detail=_('Email is invalid or not confirmed')) if user.check_password(serialized_data.data['password']): if user.is_active: payload = jwt_payload_handler( user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler( jwt_encode_handler(payload), user=user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException( detail=_('This user is inactive, contact us.')) else: raise authnz_exceptions.CustomException( detail=_('Email or Password is invalid.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id) instance.down_vote.remove(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=400).send()
def get(self, request, *args, **kwargs): try: main_url = '{}/'.format(request.build_absolute_uri('/')[:-1].strip("/")) create_data(main_url) # for debug data = {} return responses.SuccessResponse(data).send() except Exception as e: return responses.ErrorResponse(message=str(e), status=400).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, is_deleted=False) if instance.approved or request.user == instance.company.user: instance.view.add(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() else: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def post(self, request, *args, **kwargs): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): self.perform_create(serialize_data) return responses.SuccessResponse(serialize_data.data).send() except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request): try: if request.user.is_active: payload = jwt_payload_handler(request.user) # todo: Is deprecated jwt_token = utilities.jwt_response_payload_handler(jwt_encode_handler(payload), user=request.user) return responses.SuccessResponse(jwt_token).send() else: raise authnz_exceptions.CustomException(detail=_('This user is inactive, contact us.')) except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, approved=True) if self.model in [CompanyReview, Question, Interview]: if not isinstance( request.user, AnonymousUser): # view of company review, question instance.view.add(request.user) serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def post(self, request, *args, **kwargs): serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(): file = file_check_name(request.user.username, serialize_data.validated_data['file'], serialize_data.validated_data['slug']) data = {'file_path': file} return responses.SuccessResponse(data, status=200).send() else: dev_error = serialize_data.errors message = 'Failed to upload {}'.format(serialize_data.data['file'].name) show_type = settings.MESSAGE_SHOW_TYPE['TOAST'] return responses.ErrorResponse(message=message, dev_error=dev_error, show_type=show_type, status=400).send()
def put(self, request): try: serialize_data = self.get_serializer(request.user, data=request.data) if serialize_data.is_valid(raise_exception=True): try: self.perform_update(serialize_data) except Exception as e: raise e serialize_data = self.get_serializer(request.user) return responses.SuccessResponse(serialize_data.data).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except Exception as e: return responses.ErrorResponse(message=str(e)).send()
def get(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id, is_deleted=False) if instance.approved or request.user == instance.creator or (not request.user.is_anonymous and request.user.is_staff): if self.model in [CompanyReview, Question, Interview]: if not isinstance(request.user, AnonymousUser): # view of company review, question instance.view.add(request.user) instance.total_view += 1 instance.save() serialize_data = self.get_serializer(instance) return responses.SuccessResponse(serialize_data.data).send() else: return responses.ErrorResponse(message='Instance does not Found.', status=404).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def put(self, request, id, *args, **kwargs): try: instance = self.model.objects.get(id=id) permissions.check_perm_company_owner_update(request, instance) serialize_data = self.get_serializer(instance, data=request.data) if serialize_data.is_valid(raise_exception=True): self.perform_update(serialize_data) data = self.get_serializer(instance) return responses.SuccessResponse(data.data).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=400).send() except CustomException as c: return responses.ErrorResponse(message=c.detail, status=c.status_code).send() except ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): if serialize_data.data['key'] == settings.BOT_APPROVE_KEY: if serialize_data.data['type'] == 'review': review = CompanyReview.objects.get( id=serialize_data.data['id']) elif serialize_data.data['type'] == 'interview': review = Interview.objects.get( id=serialize_data.data['id']) else: raise CustomException( detail='Instance does not Found.', code=404) review.approved = True review.save() cache.delete(settings.LAST_REVIEWS) cache.delete(settings.LAST_INTERVIEWS) if serialize_data.data['type'] == 'review': review_link = '{}/review/{}'.format( settings.WEB_BASE_PATH, review.id) utilities.telegram_notify_channel( 'تجربه کاری {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}' .format(review.title, review.company.name, review_link, '#' + review.company.city.city_slug, '#review')) review.company.handle_company_review_statics() elif serialize_data.data['type'] == 'interview': review_link = '{}/interview/{}'.format( settings.WEB_BASE_PATH, review.id) utilities.telegram_notify_channel( 'تجربه مصاحبه {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}' .format(review.title, review.company.name, review_link, '#' + review.company.city.city_slug, '#interview')) review.company.handle_company_interview_statics() return responses.SuccessResponse().send() else: raise CustomException(detail='Instance does not Found.', code=404) except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except self.model.DoesNotExist as e: return responses.ErrorResponse(message='Instance does not Found.', status=404).send()
def post(self, request, backend, *args, **kwargs): try: if request.user.profile.email and request.user.profile.email_confirmed: return responses.ErrorResponse( message=_('This email used before.')).send() serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): token = serialized_data.data['token'] if backend.lower() == 'google': try: resp_user = id_token.verify_oauth2_token( token, google_requests.Request(), settings.GOOGLE_OAUTH_ID) except Exception as e: return responses.ErrorResponse( message='Error in google open auth', dev_error=str(e), status=400).send() if resp_user['iss'] not in [ 'accounts.google.com', 'https://accounts.google.com' ]: raise authnz_exceptions.CustomException( detail=_('Google Wrong issuer.')) if not resp_user.get('email') or not resp_user.get('given_name') or \ not resp_user.get('family_name') or not resp_user.get('picture'): raise authnz_exceptions.CustomException(detail=_( 'Scope need to have email, given name, family, picture' )) email = resp_user['email'].lower() try: user = User.objects.get(profile__email=email) except User.DoesNotExist as e: user = None if user: raise authnz_exceptions.CustomException( detail=_('This email was used before.')) else: request.user.profile.email = email request.user.profile.email_confirmed = True request.user.save() else: raise authnz_exceptions.CustomException( detail=_('Wrong backend')) return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request): try: serialized_data = self.serializer_class(data=request.data) if serialized_data.is_valid(raise_exception=True): email = serialized_data.data['email'].lower() try: user = User.objects.get(email=email) except User.DoesNotExist as e: user = None if user: raise authnz_exceptions.CustomException(detail=_('This email is registered before.')) else: password = serialized_data.data['password'] user = transactions.register_user_with_email_and_password(email, password) return responses.SuccessResponse().send() except authnz_exceptions.CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send() except exceptions.ValidationError as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def post(self, request, *args, **kwargs): serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(): try: src = Company.objects.get(id=serialize_data.validated_data["src"], is_deleted=False) except Company.DoesNotExist as e: return responses.ErrorResponse(message="Src company does not exist", status=400).send() try: des = Company.objects.get(id=serialize_data.validated_data["des"], is_deleted=False) except Company.DoesNotExist as e: return responses.ErrorResponse(message="Des company does not exist", status=400).send() with transaction.atomic(): # review for review in src.companyreview_set.all(): review.company = des review.save() # interview for interview in src.interview_set.all(): interview.company = des interview.save() # question for question in src.question_set.all(): question.company = des question.save() src.is_deleted = True src.save() des.handle_company_review_statics() des.handle_company_interview_statics() return responses.SuccessResponse({}, status=200).send() return responses.ErrorResponse(message="not valid data", status=400).send()
def post(self, request): try: serialize_data = self.get_serializer(data=request.data) if serialize_data.is_valid(raise_exception=True): if serialize_data.data["key"] == settings.BOT_APPROVE_KEY: instance_map = { "review": CompanyReview, "interview": Interview, "question": Question, "answer": Answer, "review_comment": ReviewComment, "interview_comment": InterviewComment, } if serialize_data.data["type"] in instance_map.keys(): try: instance = instance_map[serialize_data.data["type"]].objects.get( id=serialize_data.data["id"] ) except ( CompanyReview.DoesNotExist, Interview.DoesNotExist, Question.DoesNotExist, Answer.DoesNotExist, ReviewComment.DoesNotExist, InterviewComment.DoesNotExist ) as e: raise CustomException(detail="Instance does not Found.", code=404) else: raise CustomException(detail="Instance type does not exist.") instance.approved = serialize_data.data["approved"] instance.save() if serialize_data.data["type"] in ["review", "interview"]: cache.delete(settings.LAST_REVIEWS) cache.delete(settings.LAST_INTERVIEWS) if check_notify_to_telegram_channel(serialize_data.data): if serialize_data.data["type"] == "review": review_link = "{}/review/{}".format(settings.WEB_BASE_PATH, instance.id) utilities.telegram_notify_channel( "تجربه کاری {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}".format( instance.title, instance.company.name, review_link, "#" + instance.company.city.city_slug, "#review")) instance.company.handle_company_review_statics() elif serialize_data.data["type"] == "interview": review_link = "{}/interview/{}".format(settings.WEB_BASE_PATH, instance.id) utilities.telegram_notify_channel( "تجربه مصاحبه {} در {}, را در جابگای بخوانید. \n {} \n {} \n {}".format( instance.title, instance.company.name, review_link, "#"+instance.company.city.city_slug, "#interview")) instance.company.handle_company_interview_statics() if not instance.approved: instance_type = serialize_data.data["type"] fa_map = { "review": "تجربه کاری", "interview": "تجربه مصاحبه", "question": "سوال", "answer": "پاسخ", "review_comment": "نظر", "interview_comment": "نظر", } company = get_compnay(instance, instance_type) send_notice_instance_rejected( instance.creator, fa_map[instance_type], company ) return responses.SuccessResponse().send() else: raise CustomException(detail="Instance does not Found.", code=404) except CustomException as e: return responses.ErrorResponse(message=e.detail, status=e.status_code).send()
def create_data(main_url): print('Cleaning previous database') call_command('migrate') print('Set initial configs') IntegerConfig(name='SUGGESTION_TIMEOUT', value=60 * 5, description='Redis timeout for suggestion').save() IntegerConfig(name='MAX_SMS_PER_TIME_OUT', value=3, description='Max send sms in a timeout').save() IntegerConfig(name='SMS_TIMEOUT', value=30 * 60, description='Sms timeout ').save() IntegerConfig(name='MAX_FILE_SIZE', value=2*1024*1024, description='Max file size to upload').save() IntegerConfig(name='VERIFICATION_TIME_OUT', value=10 * 60, description='Timeout to verify mobile').save() url_map = { 'MAIN_URL': main_url, 'REGISTER_EMAIL': 'authnz/register_email/', 'LOGIN_EMAIL': 'authnz/login_email/', 'BENEFIT_CREATE': 'benefit/create/', 'INDUSTRY_CREATE': 'industry/create/', 'PROVINCE_CREATE': 'province/create/', 'CITY_CREATE': 'city/create/', 'COMPANY_CREATE': 'company/create/', 'JOB_CREATE': 'job/create/', 'PROS_CREATE': 'pros/create/', 'CONS_CREATE': 'cons/create/', 'COMPANY_REVIEW_CREATE': 'company_review/create/', 'QUESTION_CREATE': 'question/create/', 'ANSWER_CREATE': 'answer/create/', } ADMIN_DATA = {'email': '*****@*****.**', 'password': '******'} resp = requests.post(url_map['MAIN_URL'] + url_map['REGISTER_EMAIL'], json=ADMIN_DATA) resp = requests.post(url_map['MAIN_URL'] + url_map['LOGIN_EMAIL'], json=ADMIN_DATA) user = User.objects.last() user.is_staff = True user.is_superuser = True user.save() ADMIN_HEADER = { 'Content-Type': 'application/json', 'Authorization': 'JWT ' + resp.json()['data']['token'] } excel_file = 'data_test.xlsx' script_dir = os.path.dirname(__file__) file_path = os.path.join(script_dir, excel_file) xl = pd.ExcelFile(file_path) df = xl.parse('provinces') PROVINCE_DATA = {} for index, row in df.iterrows(): # Province PROVINCE_DATA_TEMP = {'name': row['name']} resp = requests.post(url_map['MAIN_URL'] + url_map['PROVINCE_CREATE'], json=PROVINCE_DATA_TEMP, headers=ADMIN_HEADER) PROVINCE_DATA[row['province_id']] = resp.json()['data'] # City df = xl.parse('cities') CITY_DATA = {} for index, row in df.iterrows(): CITY_DATA_TEMP = {'name': row['name'], 'province': PROVINCE_DATA[row['province_id']]} resp = requests.post(url_map['MAIN_URL'] + url_map['CITY_CREATE'], json=CITY_DATA_TEMP, headers=ADMIN_HEADER) CITY_DATA[row['city_id']] = resp.json()['data'] # Job df = xl.parse('job') JOB_DATA = {} for index, row in df.iterrows(): JOB_DATA_TEMP = {'name': row['name'], 'description': row['description'], 'cover': row['cover'], 'icon': row['icon']} resp = requests.post(url_map['MAIN_URL'] + url_map['JOB_CREATE'], json=JOB_DATA_TEMP, headers=ADMIN_HEADER) # JOB_DATA[row['job_id']] = resp.json()['data'] # Industry df = xl.parse('industries') INDUSTRY_DATA = {} for index, row in df.iterrows(): INDUSTRY_DATA_TEMP = {'name': row['name'], 'logo': row['logo'], 'icon': row['icon'], 'description': row['description']} resp = requests.post(url_map['MAIN_URL'] + url_map['INDUSTRY_CREATE'], json=INDUSTRY_DATA_TEMP, headers=ADMIN_HEADER) INDUSTRY_DATA[row['industry_id']] = resp.json()['data'] # Pros df = xl.parse('pros') PROS_DATA = {} for index, row in df.iterrows(): PROS_DATA_TEMP = {'name': row['name'], 'icon': row['icon'], 'logo': row['logo']} resp = requests.post(url_map['MAIN_URL'] + url_map['PROS_CREATE'], json=PROS_DATA_TEMP, headers=ADMIN_HEADER) # PROS_DATA[row['pros_id']] = resp.json()['data'] # Cons df = xl.parse('cons') CONS_DATA = {} for index, row in df.iterrows(): CONS_DATA_TEMP = {'name': row['name'], 'icon': row['icon'], 'logo': row['logo']} resp = requests.post(url_map['MAIN_URL'] + url_map['CONS_CREATE'], json=CONS_DATA_TEMP, headers=ADMIN_HEADER) # CONS_DATA[row['cons_id']] = resp.json()['data'] # Company df = xl.parse('companies') COMPANY_DATA = {} for index, row in df.iterrows(): gallery_list = [] if isinstance(row['gallery'], str): for gallery_path in row['gallery'].split(',')[:-1]: gallery_list.append({ 'path': gallery_path, }) COMPANY_DATA_TEMP = {'name': row['name'], 'name_en': row['name_en'], 'company_slug': row['slug'], 'founded': '{}-01-01'.format(row['founded']), 'industry': INDUSTRY_DATA[row['industry']], 'size': row['size'], 'city': CITY_DATA[row['city_id']], 'cover': row['header'], 'logo': row['logo'], 'site': row['website'] if isinstance(row['website'], str) else '', 'description': row['description'] if isinstance(row['description'], str) else '', 'gallery': gallery_list} if not isinstance(row['website'], str): COMPANY_DATA_TEMP.pop('site') if not isinstance(row['description'], str): COMPANY_DATA_TEMP.pop('description') if not isinstance(row['founded'], str): COMPANY_DATA_TEMP.pop('founded') resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_CREATE'], json=COMPANY_DATA_TEMP, headers=ADMIN_HEADER) try: COMPANY_DATA[row['company_id']] = resp.json()['data'] except Exception as e: print(e) # user_data_map = dict() # for index, row in df.iterrows(): # # Benefit # BENEFIT_DATA = {'name': 'Test Benefit', 'logo': UPLOAD_IMAGE_PATH, 'icon': ICON} # resp = requests.post(url_map['MAIN_URL'] + url_map['BENEFIT_CREATE'], json=BENEFIT_DATA, headers=ADMIN_HEADER) # BENEFIT_DATA = resp.json()['data'] # # # Industry # INDUSTRY_DATA = {'name': 'Test Industry', 'logo': UPLOAD_IMAGE_PATH, 'icon': ICON, # 'description': 'Test industry description'} # resp = requests.post(url_map['MAIN_URL'] + url_map['INDUSTRY_CREATE'], json=INDUSTRY_DATA, headers=ADMIN_HEADER) # INDUSTRY_DATA = resp.json()['data'] # # # Company # COMPANY_DATA1 = {'name': 'Snapp', 'logo': UPLOAD_IMAGE_PATH, 'industry': INDUSTRY_DATA, 'founded': '2012-02-01', # 'benefit': [BENEFIT_DATA], 'gallery': [{'path': UPLOAD_IMAGE_PATH, 'description': 'Snapp gallery'}], # 'description': 'Online taxi company in iran', 'size': 'L', 'tell': '02123564879', # 'site': 'http://google.com', 'explanation': 'An Internet taxi app for iranian', # 'latitude': 65.254, 'longitude': 64.25, 'working_hours_start': '07:00:00', # 'working_hours_stop': '19:00:00', 'city': CITY_DATA, 'cover': UPLOAD_IMAGE_COVER_PATH, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_CREATE'], json=COMPANY_DATA1, headers=ADMIN_HEADER) # COMPANY_DATA1 = resp.json()['data'] # # COMPANY_DATA2 = {'name': 'Tap30', 'logo': UPLOAD_IMAGE_PATH, 'industry': INDUSTRY_DATA, 'founded': '2012-02-01', # 'benefit': [BENEFIT_DATA], 'gallery': [{'path': UPLOAD_IMAGE_PATH, 'description': 'Snapp gallery'}], # 'description': 'Online taxi company in iran', 'size': 'L', 'tell': '02123564879', # 'site': 'http://google.com', 'explanation': 'An Internet taxi app for iranian', # 'latitude': 65.254, 'longitude': 64.25, 'working_hours_start': '07:00:00', # 'working_hours_stop': '19:00:00', 'city': CITY_DATA, 'cover': UPLOAD_IMAGE_COVER_PATH, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_CREATE'], json=COMPANY_DATA2, headers=ADMIN_HEADER) # COMPANY_DATA2 = resp.json()['data'] # # COMPANY_DATA3 = {'name': 'Jobguy', 'logo': UPLOAD_IMAGE_PATH, 'industry': INDUSTRY_DATA, 'founded': '2012-02-01', # 'benefit': [BENEFIT_DATA], 'gallery': [{'path': UPLOAD_IMAGE_PATH, 'description': 'Snapp gallery'}], # 'description': 'Online taxi company in iran', 'size': 'L', 'tell': '02123564879', # 'site': 'http://google.com', 'explanation': 'An Internet taxi app for iranian', # 'latitude': 65.254, 'longitude': 64.25, 'working_hours_start': '07:00:00', # 'working_hours_stop': '19:00:00', 'city': CITY_DATA, 'cover': UPLOAD_IMAGE_COVER_PATH, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_CREATE'], json=COMPANY_DATA3, headers=ADMIN_HEADER) # COMPANY_DATA3 = resp.json()['data'] # # Job # JOB_DATA = {'name': 'Developer Python', 'description': 'This is a good job :).', 'cover': UPLOAD_IMAGE_PATH, 'icon': ICON} # resp = requests.post(url_map['MAIN_URL'] + url_map['JOB_CREATE'], json=JOB_DATA, headers=ADMIN_HEADER) # JOB_DATA = resp.json()['data'] # # JOB_DATA = {'name': 'Developer Java Script', 'description': 'This is a good job :).', 'cover': UPLOAD_IMAGE_PATH, 'icon': ICON} # resp = requests.post(url_map['MAIN_URL'] + url_map['JOB_CREATE'], json=JOB_DATA, headers=ADMIN_HEADER) # JOB_DATA = resp.json()['data'] # # JOB_DATA = {'name': 'Developer IOS', 'description': 'This is a good job :).', 'cover': UPLOAD_IMAGE_PATH, 'icon': ICON} # resp = requests.post(url_map['MAIN_URL'] + url_map['JOB_CREATE'], json=JOB_DATA, headers=ADMIN_HEADER) # JOB_DATA = resp.json()['data'] # # JOB_DATA = {'name': 'Developer Android', 'description': 'This is a good job :).', 'cover': UPLOAD_IMAGE_PATH, 'icon': ICON} # resp = requests.post(url_map['MAIN_URL'] + url_map['JOB_CREATE'], json=JOB_DATA, headers=ADMIN_HEADER) # JOB_DATA = resp.json()['data'] # # # Pros # PROS_DATA = {'name': 'Pros 1', 'icon': ICON, 'logo': UPLOAD_IMAGE_PATH} # resp = requests.post(url_map['MAIN_URL'] + url_map['PROS_CREATE'], json=PROS_DATA, headers=ADMIN_HEADER) # PROS_DATA = resp.json()['data'] # # # Cons # CONS_DATA = {'name': 'Cons 1', 'icon': ICON, 'logo': UPLOAD_IMAGE_PATH} # resp = requests.post(url_map['MAIN_URL'] + url_map['CONS_CREATE'], json=CONS_DATA, headers=ADMIN_HEADER) # CONS_DATA = resp.json()['data'] # # # Company Review # COMPANY_REVIEW_DATA = {'company': COMPANY_DATA1, 'job': JOB_DATA, # 'recommend_to_friend': True, # 'pros': [ # PROS_DATA # ], # 'cons': [ # CONS_DATA # ], # 'state': 'FULL', 'work_life_balance': 3, 'salary_benefit': 4, 'security': 2, # 'management': 3, 'culture': 5, 'title': 'Good second home', 'salary_type': 'MONTH', # 'description': 'This company is very good company', 'salary': 3500000, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_REVIEW_CREATE'], # json=COMPANY_REVIEW_DATA, headers=ADMIN_HEADER) # COMPANY_REVIEW_DATA = resp.json()['data'] # # # Company Review # COMPANY_REVIEW_DATA = {'company': COMPANY_DATA1, 'job': JOB_DATA, # 'recommend_to_friend': True, # 'pros': [ # PROS_DATA # ], # 'cons': [ # CONS_DATA # ], # 'state': 'FULL', 'work_life_balance': 3, 'salary_benefit': 4, 'security': 2, # 'management': 3, 'culture': 5, 'title': 'Good second home', 'salary_type': 'MONTH', # 'description': 'This company is very good company', 'salary': 3500000, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_REVIEW_CREATE'], # json=COMPANY_REVIEW_DATA, headers=ADMIN_HEADER) # COMPANY_REVIEW_DATA = resp.json()['data'] # # # Company Review # COMPANY_REVIEW_DATA = {'company': COMPANY_DATA1, 'job': JOB_DATA, # 'recommend_to_friend': True, # 'pros': [ # PROS_DATA # ], # 'cons': [ # CONS_DATA # ], # 'state': 'FULL', 'work_life_balance': 3, 'salary_benefit': 4, 'security': 2, # 'management': 3, 'culture': 5, 'title': 'Good second home', 'salary_type': 'MONTH', # 'description': 'This company is very good company', 'salary': 3500000, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_REVIEW_CREATE'], # json=COMPANY_REVIEW_DATA, headers=ADMIN_HEADER) # COMPANY_REVIEW_DATA = resp.json()['data'] # COMPANY_REVIEW_DATA = {'company': COMPANY_DATA3, 'job': JOB_DATA, # 'recommend_to_friend': True, # 'pros': [ # PROS_DATA # ], # 'cons': [ # CONS_DATA # ], 'anonymous_job': True, # 'state': 'FULL', 'work_life_balance': 5, 'salary_benefit': 4, 'security': 5, # 'management': 5, 'culture': 5, 'title': 'Good second home', 'salary_type': 'MONTH', # 'description': 'This company is very good company', 'salary': 3500000, # } # resp = requests.post(url_map['MAIN_URL'] + url_map['COMPANY_REVIEW_CREATE'], # json=COMPANY_REVIEW_DATA, headers=ADMIN_HEADER) # COMPANY_REVIEW_DATA = resp.json()['data'] # # # Question # QUESTION_DATA = {'title': 'What about a question?', 'body': 'Do you know anything about this company?', # 'company': COMPANY_DATA2} # resp = requests.post(url_map['MAIN_URL'] + url_map['QUESTION_CREATE'], # json=QUESTION_DATA, headers=ADMIN_HEADER) # QUESTION_DATA = resp.json()['data'] # # # Answer # ANSWER_DATA = {'body': 'Yes I know everything about it.', 'question': QUESTION_DATA} # resp = requests.post(url_map['MAIN_URL'] + url_map['ANSWER_CREATE'], # json=ANSWER_DATA, headers=ADMIN_HEADER) # ANSWER_DATA = resp.json()['data'] return responses.SuccessResponse({}).send()