本文整理匯總了Python中ipware.ip.get_ip方法的典型用法代碼示例。如果您正苦於以下問題:Python ip.get_ip方法的具體用法?Python ip.get_ip怎麽用?Python ip.get_ip使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類ipware.ip
的用法示例。
在下文中一共展示了ip.get_ip方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: generate_key
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def generate_key(self, request):
"""
Generate new link expiration key
"""
new_key = DataFileKey(datafile_id=self.id)
if request:
# Log the entity that is requesting the key be generated
new_key.ip_address = get_ip(request)
try:
new_key.access_token = request.query_params.get("access_token", None)
except (AttributeError, KeyError):
new_key.access_token = None
try:
new_key.project_id = request.auth.id
except AttributeError:
# We do not have an accessing project
new_key.project_id = None
new_key.save()
return new_key.key
示例2: fake_login
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def fake_login(request, next_page=None):
"""
Fake login view for devel without access to the fake CAS server
"""
import socket
from django.contrib.auth import login
from django.contrib.auth.models import User
if not next_page and 'next' in request.GET:
next_page = request.GET['next']
if not next_page:
next_page = '/'
hostname = socket.gethostname()
if settings.DEPLOY_MODE == 'production' or hostname.startswith('courses'):
# make damn sure we're not in production
raise NotImplementedError
if 'userid' in request.GET:
username = request.GET['userid']
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
user = User.objects.create_user(username, '')
user.save()
user.backend = 'django.contrib.auth.backends.ModelBackend'
login(request, user)
#LOG EVENT#
l = LogEntry(userid=user.username,
description=("fake login as %s from %s") % (user.username, ip.get_ip(request)),
related_object=user)
l.save()
return HttpResponseRedirect(next_page)
response = HttpResponse('<h1>Fake Authenticator</h1><p>Who would you like to be today?</p><form action="">Userid: <input type="text" name="userid" /><br/><input type="submit" value=""Authenticate"" /><input type="hidden" name="next" value="%s" /></form>' % (next_page))
return response
示例3: successful_login
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def successful_login(self, request, next_page):
# create a LogEntry when users log in
user = request.user
l = LogEntry(userid=user.username,
description=("logged in as %s from %s") % (user.username, ip.get_ip(request)),
related_object=user)
l.save()
return super().successful_login(request, next_page)
示例4: photo_agreement
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def photo_agreement(request):
user = get_object_or_404(Person, userid=request.user.username)
configs = UserConfig.objects.filter(user=user, key='photo-agreement')
if configs:
config = configs[0]
else:
config = UserConfig(user=user, key='photo-agreement', value={'agree': False})
if request.method == 'POST':
form = PhotoAgreementForm(request.POST)
if form.is_valid():
config.value['agree'] = form.cleaned_data['agree']
if config.value['agree']:
config.value['version'] = 1
config.value['at'] = datetime.datetime.now().isoformat()
config.value['from'] = ip.get_ip(request)
config.save()
messages.add_message(request, messages.SUCCESS, 'Updated your photo agreement status.')
if 'return' in request.GET:
url = request.GET['return']
else:
url = reverse('config:config')
return HttpResponseRedirect(url)
else:
form = PhotoAgreementForm({'agree': config.value['agree']})
if 'at' in config.value:
agree_date = datetime.datetime.strptime(config.value['at'], '%Y-%m-%dT%H:%M:%S.%f')
else:
agree_date = None
context = {"form": form, 'agree': config.value['agree'], 'agree_date': agree_date}
return render(request, "dashboard/photo_agreement.html", context)
示例5: login_2fa
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def login_2fa(request, next_page=None):
next_page, okay_auth, okay_2fa = _setup_view(request, next_page)
if not okay_auth:
# Stale standard-Django authentication: redirect to password login page.
return HttpResponseRedirect(settings.PASSWORD_LOGIN_URL + '?' + urlencode({'next': next_page}))
if not okay_2fa:
# Need to do 2FA for this user.
devices = list(all_otp_devices(request.maybe_stale_user))
if not devices:
messages.add_message(request, messages.WARNING, 'You are required to do two-factor authentication but have no device enabled. You must add one.')
return HttpResponseRedirect(reverse('otp:add_topt') + '?' + urlencode({'next': next_page}))
if request.method == 'POST':
form = TokenForm(data=request.POST, devices=devices)
if form.is_valid():
# OTP is valid: record last 2FA time in SessionInfo; have django_otp record what it needs in the session
SessionInfo.just_2fa(request)
request.user = request.maybe_stale_user # otp_login looks at request.user
otp_login(request, form.device)
l = LogEntry(userid=request.user.username,
description=("2FA as %s from %s") % (request.user.username, ip.get_ip(request)),
related_object=request.user)
l.save()
return HttpResponseRedirect(next_page)
else:
form = TokenForm()
context = {
'form': form,
}
return render(request, 'otp/login_2fa.html', context)
return HttpResponseRedirect(next_page)
示例6: add_topt
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def add_topt(request, next_page=None):
next_page, okay_auth, okay_2fa = _setup_view(request, next_page)
if not okay_auth:
return ForbiddenResponse(request)
# This enforces that users have exactly one TOTP. That *seems* like the best practice.
devices = TOTPDevice.objects.devices_for_user(request.maybe_stale_user, confirmed=True)
if devices:
return ForbiddenResponse(request, "You have already configured an authenticator with this account, and cannot add another. Contact %s if you are unable to authenticate with CourSys", (help_email(request),))
device = TOTPDevice(user=request.maybe_stale_user, name='Authenticator, enabled %s' % (datetime.date.today()))
device.save()
l = LogEntry(userid=request.user.username,
description=("Added TOPT from %s") % (ip.get_ip(request),),
related_object=device)
l.save()
# build QR code
uri = totpauth_url(device)
qr = qrcode.make(uri, image_factory=qrcode.image.svg.SvgPathImage)
qrdata = BytesIO()
qr.save(qrdata)
# This is the OTP secret (bits) encoded as base32, wrapped in an otpauth URL, encoded as a QR code, encoded as an
# SVG, encoded as base64, wrapped in a data URL. I'm strangely proud.
dataurl = (b'data:image/svg+xml;base64,' + base64.b64encode(qrdata.getvalue())).decode("utf-8")
context = {
'device': device,
'dataurl': dataurl,
'next_page': next_page,
}
return render(request, 'otp/add_topt.html', context)
示例7: has_permission
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def has_permission(self, request, view):
remote_ip = get_ip(request)
if remote_ip:
allowed_ips = [ip.lower() for ip in settings.HEALTH_CHECK_REMOTE_IPS]
for allowed_ip in allowed_ips:
if remote_ip.startswith(allowed_ip):
return True
return False
示例8: __init__
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def __init__(self, poll, request=None, data=None, **kwargs):
super(VoteForm, self).__init__(data, **kwargs)
self.poll = poll
self.request = request
self.fields['question'].queryset = poll.questions.all()
if request:
self.ip = get_real_ip(self.request) or get_ip(self.request)
示例9: search
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def search(request):
ip = get_ip(request)
if request.method == 'POST':
usr = User.objects.filter(username=request.user)
ip = get_ip(request)
rst = essearch(request.POST['keyword'])
intent=None
gnr = ""
for i, (k, v) in enumerate(rst['gnr']):
if i is 3:
break
else:
gnr += (k + "|")
if len(usr) is 1:
try:
intent=str(usr[0].last_name).split('|')[1]
except:
pass
obj = Searchedkey(usr=usr[0],
ipaddr=str(ip),
content=request.POST['keyword'],
star=rst['avg'],
gnrs=gnr,
isapi=False,
update=datetime.datetime.now(tz=pytz.UTC),
intent=intent
)
obj.save()
else:
obj = Searchedkey(usr=None,
ipaddr=str(ip),
content=request.POST['keyword'],
star=rst['avg'],
gnrs=gnr,
isapi=False,
update=datetime.datetime.now(tz=pytz.UTC),
intent=intent
)
obj.save()
return render(request, 'search.html', rst)
示例10: jsonapi
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def jsonapi(request,userid,keyword):
usr=User.objects.filter(username=userid)
ip = get_ip(request)
intent=None
if len(usr) is 1:
rst=essearch(keyword)
gnr=""
try:
intent = str(usr[0].last_name).split('|')[1]
except:
pass
for i,(k,v) in enumerate(rst['gnr']):
if i is 3:
break
else:
gnr+=(k+"|")
js = json.dumps(rst, ensure_ascii=False)
obj = Searchedkey(usr=usr[0],
ipaddr=str(ip),
content=keyword,
star=rst['avg'],
gnrs=gnr,
isapi=True,
update=datetime.datetime.now(),
intent=intent
)
obj.save()
return HttpResponse(js, content_type=u"application/json; charset=utf-8", status=200)
else:
rst={"err":"오픈한글감성사전에 등록된 유저가 아닙니다"}
js = json.dumps(rst, ensure_ascii=False)
return HttpResponse(js, content_type=u"application/json; charset=utf-8", status=500)
示例11: login_user
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def login_user(request):
state = ''
username = ''
password = ''
redirect_to = request.GET.get('next')
ip = get_ip(request)
if request.POST:
username = request.POST.get('username')
password = request.POST.get('password')
redirect_to = request.POST.get('redirect_to')
user = authenticate(username=username, password=password)
if user is not None:
auth_logger.info('User:%s logged in from %s' % (username, ip))
if user.is_active:
login(request, user)
check_and_create_perms(user)
if user.perms.access_level == 5:
return redirect(redirect_to or '/reports/')
else:
return redirect(redirect_to or '/incidents/')
else:
state = "Your account is inactive, please contact the administrator."
else:
auth_logger.info('Failed login attempt from user:%s from %s' % (username, ip))
state = "Username/Password incorrect"
return render(request, 'login.html', {'state': state, 'username': username, 'redirect_to': redirect_to})
示例12: logout_user
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def logout_user(request):
logout(request)
ip = get_ip(request)
auth_logger.info('User:%s logged out from %s' % (request.user.username, ip))
return render(request, 'logout.html')
示例13: get_and_log
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def get_and_log(self, request, key_object=None):
"""
Redirect to S3 URL for file. Log access if this feature is active.
Feature activity for specific users is based on whether the datafile
belongs to that user, not based on the user doing the download.
"""
aws_url = self.data_file.file_url_as_attachment
url = "{0}&x-oh-key={1}".format(aws_url, key_object.key)
# Check feature flag based on file user (subject), not request user.
flag = FlagModel.get("datafile-access-logging")
if not flag.is_active(request=request, subject=self.data_file.user):
return HttpResponseRedirect(url)
user = request.user if request.user.is_authenticated else None
access_log = NewDataFileAccessLog(
user=user, ip_address=get_ip(request), data_file=self.data_file
)
access_log.data_file_key = {
"id": key_object.id,
"created": key_object.created.isoformat(),
"key": key_object.key,
"datafile_id": key_object.datafile_id,
"key_creation_ip_address": key_object.ip_address,
"access_token": key_object.access_token,
"project_id": key_object.project_id,
}
access_log.aws_url = url
access_log.serialized_data_file = serialize_datafile_to_dict(self.data_file)
access_log.save()
return HttpResponseRedirect(url)
# pylint: disable=attribute-defined-outside-init
示例14: post
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def post(self, request, pk):
try:
lang = request.POST.get('lang', '')
if lang not in dict(LANG_CHOICE).keys():
raise ValueError("語言無效。")
submission = create_submission(self.problem, self.user, request.POST.get('code', ''), lang, ip=get_ip(request))
running_complete = bool(is_problem_manager(self.user, self.problem) and request.POST.get('complete'))
async_task(judge_submission_on_problem, submission, run_until_complete=running_complete)
return JsonResponse({"url": reverse('problem:submission_api',
kwargs={'pk': self.problem.id, 'sid': submission.id})})
except Exception as e:
return HttpResponseBadRequest(str(e).encode())
示例15: save_to_db
# 需要導入模塊: from ipware import ip [as 別名]
# 或者: from ipware.ip import get_ip [as 別名]
def save_to_db(self, form_data, request, referrer):
user = request.user if request.user.is_authenticated() else None
FormSubmission.objects.create(
plugin=self.form_definition.plugin_reference,
ip=get_ip(request),
referrer=referrer,
form_data=form_data,
created_by=user)