def get_initial(self): initial = super(Feedback, self).get_initial() initial.update({ 'user': self.request.user if self.request.user.is_authenticated() else None, 'ip_address': get_client_ip(self.request) }) return initial
def check_attemp(self, request): phone = self.data['phone'] ip = utils.get_client_ip(request) ip_phone_key = f'attemps::{phone}::{ip}' ip_key = f'attemps::{ip}' if ip_phone_key in cache: if cache.get(ip_phone_key) > VERIFY_CNT_LIMIT: raise RegistryByPhoneError( f'limit sms attemps: {VERIFY_CNT_LIMIT}') cache.incr(ip_phone_key, 1) else: cache.set(ip_phone_key, 1) # if ip_key in cache: # if cache.get(ip_key) > FROM_ONE_IP_LIMIT: # raise RegistryByPhoneError( # f'Число НОМЕРОВ для регистрации с Вашего IP: {FROM_ONE_IP_LIMIT} (превышено)') # cache.incr(ip_key, 1) # else: # cache.set(ip_key, 1) self.ip = ip return
def index(request): """Docstring.""" print colored("***" * 27, "green") print colored("*** INSIDE `%s`" % inspect.stack()[0][3], "green") g = GeoIP() ip = get_client_ip(request) # ip = "108.162.209.69" country = g.country(ip) city = g.city(ip) print colored("[--- DUMP ---] COUNTRY : %s" % country, "yellow") print colored("[--- DUMP ---] CITY : %s" % city, "yellow") timeline_qs = [] timeline_qs = sorted(chain( Post.objects.all(), Challenge.objects.get_upcoming(), Organization.objects.filter( is_hidden=False, is_deleted=False, )), key=attrgetter("created"))[:10] return render(request, "home/index.html", { "timeline_qs": timeline_qs, })
def get(self, request, blog_id): try: blog = BlogModel.objects.get(id=blog_id, is_deleted=False, is_active=True) except BlogModel.DoesNotExist: raise Http404 # 浏览计数 try: blog.click(request.session.session_key, get_client_ip(request)) except RedisConnectionError: pass # 为当前用户生成标识符,用于评论表单提交校验 key_name = 'blog-session-{0}'.format(blog.id) request.session[key_name] = md5('-'.join(['blog', str(blog.id) ]).encode()).hexdigest() ctx = { 'blog': blog, 'relates': blog.topic.blog_set.filter(is_deleted=False, is_active=True).exclude( id=blog.id) if blog.topic else [], 'comments': blog.blogcomment_set.filter(is_deleted=False, is_active=True).order_by('-created') } return self.render_to_response(context=ctx)
def new(request, lang): if request.method == 'POST': participant_form = ParticipantForm(request.POST) if participant_form.is_valid(): participant = participant_form.save(commit=False) participant.ip = get_client_ip(request), participant.ua = get_client_ua(request), participant.save() sequences = Sequence.objects.all() pairs = Pair.objects.all() if len(sequences) > len(pairs): generate_pairs(len(sequences) - len(pairs) + 1) pairs = Pair.objects.all() send_email(template='email/pairs_empty.html') pairs = pairs[:len(sequences)] for sequence, pair in zip(sequences, pairs): question = Question(participant=participant, left=pair.left, right=pair.right, sequence=sequence, answered=False) question.save() pair.delete() request.session['participant_id'] = participant.id #messages.add_message(request, messages.SUCCESS, u'Новый участник создан') return redirect(reverse('core.views.index', kwargs={'lang': lang})) #messages.add_message(request, messages.ERROR, u'Не удалось создать участника') return redirect(reverse('core.views.index', kwargs={'lang': lang}))
def subscribe_view(request): if request.method == 'POST': form = SubscriberForm(request.POST) # Check if the email address already exists. if Subscriber.objects.filter(email=request.POST['email']).exists(): return render_to_response('home.html', {'exists': True}, context_instance=RequestContext(request)) if form.is_valid(): subscriber = form.save(commit=False) # Set the subscriber's source IP. subscriber.source_ip = get_client_ip(request) subscriber.save() # Send the email confirmation. if settings.SEND_SUBSCRIBERS_EMAIL_CONFIRMATION: subscriber.send_confirmation() return render_to_response('home.html', {'success': True}, context_instance=RequestContext(request)) return render_to_response('home.html', {'error': True}, context_instance=RequestContext(request))
def get_initial(self): initial = super(Comment, self).get_initial() initial.update({ 'ip_address': get_client_ip(self.request), 'user': self.request.user if self.request.user.is_authenticated() else None, 'blog': self.blog }) return initial
def process_request(self, request): try: AccessLog.objects.create(user=request.user if request.user.is_authenticated() else None, referer=request.META.get('HTTP_REFERER', ''), path=request.get_full_path(), agent=request.META.get('HTTP_USER_AGENT', ''), ip_address=get_client_ip(request)) except: pass
def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) instance = self.queryset.create(ip_address=get_client_ip(request), **serializer.validated_data) headers = self.get_success_headers(serializer.data) serializer = self.get_serializer(instance) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
def process_request(self, request): try: AccessLog.objects.create( user=request.user if request.user.is_authenticated() else None, referer=request.META.get('HTTP_REFERER', ''), path=request.get_full_path(), agent=request.META.get('HTTP_USER_AGENT', ''), ip_address=get_client_ip(request)) except: pass
def test_forwarded(self): meta = MagicMock() def mocked_get_forwarded(key): if key == 'HTTP_X_FORWARDED_FOR': return '127.0.0.1,127.0.0.2,127.0.0.3' return '127.0.0.4' meta.get = mocked_get_forwarded request = MagicMock(META=meta) self.assertEqual('127.0.0.1', get_client_ip(request))
def test_remote(self): meta = MagicMock() def mocked_get_remote(key): if key == 'HTTP_X_FORWARDED_FOR': return None return '127.0.0.4' meta.get = mocked_get_remote request = MagicMock(META=meta) self.assertEqual('127.0.0.4', get_client_ip(request))
def get_initial(self): initial = super(Comment, self).get_initial() initial.update({ 'ip_address': get_client_ip(self.request), 'user': self.request.user if self.request.user.is_authenticated() else None, 'blog': self.blog }) return initial
def detect(self, request): """ Определение страны пользователя по IP (GeoIP). """ ip = get_client_ip(request) g = GeoIP2() match = g.country(ip) if not match: return Response(status=status.HTTP_404_NOT_FOUND) serializer = DetectCountryByIPSerializer( data={ 'country': match['country_name'], 'iso_code': match['country_code'], 'ip': ip }) serializer.is_valid(raise_exception=True) return Response(serializer.data, status=status.HTTP_200_OK)
def insert(self, request, user=None, provider="Desktop", **extra_fields): """Docstring.""" try: g = GeoIP() ip = get_client_ip(request) if not user: user = request.user login = self.model( user=user, ip=ip, provider=provider, country=g.country(ip), city=g.city(ip), **extra_fields ) login.save(using=self._db) return login except Exception as e: print colored("###" * 27, "white", "on_red") print colored("### EXCEPTION @ `{module}`: {msg}".format( module=inspect.stack()[0][3], msg=str(e), ), "white", "on_red") # ----------------------------------------------------------------- # --- Save the Log. papertrail.log( event_type="exception-insert-user-login", message="Exception: Insert User Login Entry", data={ "user": user if user else request.user.email, "message": str(e), }, # timestamp=timezone.now(), targets={ "user": user if user else request.user, }, )
def dispatch(self, request, *args, **kwargs): remote_ip = get_client_ip(request) if settings.DEBUG is False and remote_ip not in settings.RATELIMIT_WHITELIST: # create a dummy function and dynamically set its name. This way, # the ratelimit decorator is specific to the method in each class. def func(request): pass func.__name__ = str('%s_dispatch' % self.__class__.__name__) func = ratelimit(method='POST', rate='10/m')(func) ratelimit(method='GET', rate='30/m')(func)(request) if getattr(request, 'limited', False): raise RateException() # We sometimes get requests *without* a user agent. We assume these are automated requests. if not request.META.get('HTTP_USER_AGENT'): raise SpamException("No user agent passed.") return super(AntiSpamFormView, self).dispatch(request, *args, **kwargs)
def dispatch(self, request, *args, **kwargs): remote_ip = get_client_ip(request) if settings.DEBUG is False and remote_ip not in settings.RATELIMIT_WHITELIST: # create a dummy function and dynamically set its name. This way, # the ratelimit decorator is specific to the method in each class. def func(request): pass func.__name__ = str('%s_dispatch' % self.__class__.__name__) func = ratelimit(method='POST', rate='10/m')(func) ratelimit(method='GET', rate='30/m')(func)(request) if getattr(request, 'limited', False): raise RateException() # We sometimes get requests *without* a user agent. We assume these are automated requests. if not request.META.get('HTTP_USER_AGENT'): raise SpamException("No user agent passed.") return super(AntiSpamFormView, self).dispatch(request, *args, **kwargs)
def form_valid(self, form): countries = form.cleaned_data['country_indexes'] quote_request = form.save(commit=False) tour_operator = get_object_or_404(TourOperator, slug=self.kwargs.get('slug')) quote_request.tour_operator = tour_operator quote_request.ip_address = get_client_ip(self.request) quote_request.user = self.request.user quote_request.save() quote_request.country_indexes.set(countries) quote_request.save() self.send_more_information_email(quote_request) self.send_user_information_summary_email([quote_request]) context = { 'base_url': settings.BASE_URL, 'back_to': self.request.GET.get('back_to', '') } t = SimpleTemplateResponse('operators/quote_request_thanks.html', context) return t
def get(self, request, blog_id): try: blog = BlogModel.objects.get(id=blog_id, is_deleted=False, is_active=True) except BlogModel.DoesNotExist: raise Http404 # 浏览计数 try: blog.click(request.session.session_key, get_client_ip(request)) except RedisConnectionError: pass # 为当前用户生成标识符,用于评论表单提交校验 key_name = 'blog-session-{0}'.format(blog.id) request.session[key_name] = md5('-'.join(['blog', str(blog.id)]).encode()).hexdigest() ctx = { 'blog': blog, 'relates': blog.topic.blog_set.filter(is_deleted=False, is_active=True).exclude(id=blog.id) if blog.topic else [], 'comments': blog.blogcomment_set.filter(is_deleted=False, is_active=True).order_by('-created') } return self.render_to_response(context=ctx)
def new(request, lang): if request.method == 'POST': participant_form = ParticipantForm(request.POST) if participant_form.is_valid(): participant = participant_form.save(commit=False) participant.ip = get_client_ip(request), participant.ua = get_client_ua(request), participant.save() sequences = Sequence.objects.all() pairs = Pair.objects.all() if len(sequences) > len(pairs): generate_pairs(len(sequences) - len(pairs) + 1) pairs = Pair.objects.all() send_email(template='email/pairs_empty.html') pairs = pairs[:len(sequences)] for sequence, pair in zip(sequences, pairs): question = Question( participant=participant, left=pair.left, right=pair.right, sequence=sequence, answered=False ) question.save() pair.delete() request.session['participant_id'] = participant.id #messages.add_message(request, messages.SUCCESS, u'Новый участник создан') return redirect(reverse('core.views.index', kwargs={'lang': lang})) #messages.add_message(request, messages.ERROR, u'Не удалось создать участника') return redirect(reverse('core.views.index', kwargs={'lang': lang}))