本文整理汇总了Python中pytas.http.TASClient.save_user方法的典型用法代码示例。如果您正苦于以下问题:Python TASClient.save_user方法的具体用法?Python TASClient.save_user怎么用?Python TASClient.save_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pytas.http.TASClient
的用法示例。
在下文中一共展示了TASClient.save_user方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: profile_edit
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def profile_edit(request):
tas = TASClient()
tas_user = tas.get_user(username=request.user)
if tas_user['source'] != 'Chameleon':
return HttpResponseRedirect(reverse('tas:profile'))
if request.method == 'POST':
form = UserProfileForm(request.POST, initial=tas_user)
if form.is_valid():
data = form.cleaned_data
if request.POST.get('request_pi_eligibility'):
data['piEligibility'] = 'Requested'
_create_ticket_for_pi_request(tas_user)
else:
data['piEligibility'] = tas_user['piEligibility']
data['source'] = 'Chameleon'
tas.save_user(tas_user['id'], data)
messages.success(request, 'Your profile has been updated!')
return HttpResponseRedirect(reverse('tas:profile'))
else:
form = UserProfileForm(initial=tas_user)
context = {
'form': form,
'user': tas_user,
}
return render(request, 'tas/profile_edit.html', context)
示例2: make_user_pi
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def make_user_pi(self, request, selected_users, form_url=''):
# The user has already confirmed the action.
# Make the users PI Eligible
if request.POST.get('post'):
tas = TASClient()
for user in selected_users:
try:
tas_user = tas.get_user(username=user.username)
if tas_user['piEligibility'] == 'Eligible':
self.message_user(request, _('User %s already PI Eligible') % user.username, level=messages.WARNING)
else:
tas_user['piEligibility'] = 'Eligible'
tas.save_user(tas_user['id'], tas_user)
self.message_user(request, _('Granted PI Eligible to %s') % user.username)
except:
logger.exception('Unable to Grant PI Eligible to %s' % user.username)
self.message_user(request, _('Unable to Grant PI Eligible to %s') % user.username, level=messages.ERROR)
return None
context = {
'title': _('Grant PI eligibility'),
'opts': self.model._meta,
'selected_users': selected_users,
'form_url': form_url,
'action_checkbox_name':helpers.ACTION_CHECKBOX_NAME
}
context.update(admin.site.each_context())
return TemplateResponse(request,
'admin/tas/make_user_pi.html',
context, current_app=self.admin_site.name)
示例3: profile_edit
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def profile_edit(request):
tas = TASClient()
user = request.user
tas_user = tas.get_user(username=user.username)
if request.method == 'POST':
form = forms.UserProfileForm(request.POST, initial=tas_user)
if form.is_valid():
data = form.cleaned_data
# punt on PI Eligibility for now
data['piEligibility'] = tas_user['piEligibility']
# retain original account source
data['source'] = tas_user['source']
tas.save_user(tas_user['id'], data)
messages.success(request, 'Your profile has been updated!')
try:
ds_profile = user.profile
ds_profile.ethnicity = data['ethnicity']
ds_profile.gender = data['gender']
ds_profile.save()
except ObjectDoesNotExist as e:
logger.info('exception e: {} {}'.format(type(e), e ))
ds_profile = DesignSafeProfile(
user=user,
ethnicity=data['ethnicity'],
gender=data['gender']
)
ds_profile.save()
return HttpResponseRedirect(reverse('designsafe_accounts:manage_profile'))
else:
try:
tas_user['ethnicity'] = user.profile.ethnicity
tas_user['gender'] = user.profile.gender
except ObjectDoesNotExist:
pass
form = forms.UserProfileForm(initial=tas_user)
context = {
'title': 'Manage Profile',
'form': form,
}
return render(request, 'designsafe/apps/accounts/profile_edit.html', context)
示例4: register
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def register(request):
if request.user is not None and request.user.is_authenticated():
return HttpResponseRedirect(reverse('tas:profile'))
if request.method == 'POST':
register_form = UserRegistrationForm(request.POST)
if register_form.is_valid():
data = register_form.cleaned_data
if request.POST.get('request_pi_eligibility'):
data['piEligibility'] = 'Requested'
else:
data['piEligibility'] = 'Ineligible'
data['source'] = 'Chameleon'
logger.info('Attempting new user registration: %s' % _clean_registration_data(data))
try:
tas = TASClient()
created_user = tas.save_user(None, data)
if data['piEligibility'] == 'Requested':
_create_ticket_for_pi_request(created_user)
messages.success(request, 'Congratulations! Your account request has been received. Please check your email for account verification.')
return HttpResponseRedirect('/')
except Exception as e:
logger.exception('Error saving user')
if len(e.args) > 1:
if re.search('DuplicateLoginException', e.args[1]):
message = 'The username you chose has already been taken. Please choose another. If you already have an account with TACC, please log in using those credentials.'
errors = register_form._errors.setdefault('username', ErrorList())
errors.append(message)
messages.error(request, message)
elif re.search('DuplicateEmailException', e.args[1]):
message = 'This email is already registered. If you already have an account with TACC, please log in using those credentials.'
messages.error(request, message + ' <a href="{0}">Did you forget your password?</a>'.format(reverse('tas:password_reset')))
errors = register_form._errors.setdefault('email', ErrorList())
errors.append(message)
elif re.search('PasswordInvalidException', e.args[1]):
message = 'The password you provided did not meet the complexity requirements.'
messages.error(request, message)
errors = register_form._errors.setdefault('password', ErrorList())
errors.append(message)
else:
messages.error(request, 'An unexpected error occurred. If this problem persists please create a help ticket.')
else:
messages.error(request, 'An unexpected error occurred. If this problem persists please create a help ticket.')
# return HttpResponseRedirect(reverse('tas:profile'))
else:
register_form = UserRegistrationForm()
context = {
'register_form': register_form,
}
if request.method == 'POST':
context['request_pi_eligibility'] = request.POST.get('request_pi_eligibility')
return render(request, 'tas/register.html', context)
示例5: openid_register
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def openid_register(request):
openid = request.session["openid"]
if request.method == "POST":
reg_form = UserRegistrationForm(request.POST)
if reg_form.is_valid():
data = reg_form.cleaned_data
if request.POST.get("request_pi_eligibility"):
data["piEligibility"] = "Requested"
else:
data["piEligibility"] = "Ineligible"
data["source"] = "Chameleon"
logger.info("Attempting OpenID user registration: %s" % _clean_registration_data(data))
try:
tas = TASClient()
created_user = tas.save_user(None, data)
# eager create local user and save OpenIDUserIdentity
local_user = get_user_model().objects.create_user(
username=created_user["username"],
email=created_user["email"],
first_name=created_user["firstName"],
last_name=created_user["lastName"],
)
# set not active until email confirmation
local_user.is_active = False
local_user.save()
oid = OpenIDUserIdentity(uid=openid["url"], user=local_user)
oid.save()
messages.success(
request,
"Congratulations! Your account request has been "
"received. Please check your email for account "
"verification.",
)
return HttpResponseRedirect("/")
except Exception as e:
logger.exception("Error saving user")
if len(e.args) > 1:
if re.search("DuplicateLoginException", e.args[1]):
message = (
"The username you chose has already been taken. "
"Please choose another. If you already have an "
"account with TACC, please log in using those "
"credentials."
)
errors = reg_form._errors.setdefault("username", ErrorList())
errors.append(message)
messages.error(request, message)
elif re.search("DuplicateEmailException", e.args[1]):
forgot_password_url = reverse("tas:password_reset")
message = (
"This email is already registered. If you already "
"have an account with TACC, please log in using those "
'credentials. <a href="%s">Did you forget your password?</a>' % forgot_password_url
)
messages.error(request, message)
errors = reg_form._errors.setdefault("email", ErrorList())
errors.append(message)
elif re.search("PasswordInvalidException", e.args[1]):
message = "The password you provided did not meet the complexity requirements."
messages.error(request, message)
errors = reg_form._errors.setdefault("password", ErrorList())
errors.append(message)
else:
messages.error(
request,
"An unexpected error occurred. If this problem " "persists please create a help ticket.",
)
else:
messages.error(
request,
"An unexpected error occurred. If this problem " "persists please create a help ticket.",
)
else:
full_name = openid["ax"]["full_name"][0].split(" ")
reg_form = UserRegistrationForm(
initial={
"email": openid["sreg"]["email"],
"firstName": full_name[0],
"lastName": full_name[-1],
"username": openid["sreg"]["nickname"],
}
)
try:
username_taken = get_user_model().objects.get(username=openid["sreg"]["nickname"])
if username_taken:
messages.warning(
request,
"Your GENI nickname (<b>%s</b>) is not available on "
"Chameleon. Please choose a different username." % openid["sreg"]["nickname"],
)
except:
pass
context = {"register_form": reg_form}
#.........这里部分代码省略.........
示例6: tas_manage
# 需要导入模块: from pytas.http import TASClient [as 别名]
# 或者: from pytas.http.TASClient import save_user [as 别名]
def tas_manage(self, request, id, form_url=''):
if not self.has_change_permission(request):
raise PermissionDenied
user = self.get_object(request, unquote(id))
if user is None:
raise Http404(_('%(name)s object with primary key %(key)r does not exist.') % {
'name': force_text(self.model._meta.verbose_name),
'key': escape(id),
})
tas = TASClient()
tas_user = tas.get_user(username=user.username)
if request.method == 'POST':
logger.debug(request.POST)
form = TasUserProfileAdminForm(request.POST)
if form.is_valid():
redirect = False
user.first_name = tas_user['firstName'] = form.cleaned_data['firstName']
user.last_name = tas_user['lastName'] = form.cleaned_data['lastName']
user.email = tas_user['email'] = form.cleaned_data['email']
tas_user['piEligibility'] = form.cleaned_data['piEligibility']
try:
tas.save_user(tas_user['id'], tas_user) # Update remote TAS record
user.save() # Update local Django record
self.message_user(request, _('Successfully updated profile for user: %s') % user.username)
redirect = True
except:
logger.exception('Error saving user %s' % user.username)
self.message_user(request, _('Error saving profile for user: %s') % user.username, level=messages.ERROR)
redirect = False
if form.cleaned_data['reset_password']:
# trigger password reset
try:
resp = tas.request_password_reset( user.username, source='Chameleon' )
logger.debug( 'Administrator triggered password reset for user %s. Reset token: %s' % (user.username, resp) )
self.message_user(request, _('Sent password reset to user: %s') % user.username)
redirect = True
except:
logger.exception( 'Failed password reset request' )
self.message_user(request, _('Password reset failed for user: %s') % user.username, level=messages.ERROR)
redirect = False
if redirect:
return HttpResponseRedirect(
reverse(
'%s:auth_%s_change' % (
self.admin_site.name,
user._meta.model_name,
),
args=(user.pk,),
)
)
else:
form = TasUserProfileAdminForm(initial=tas_user)
fieldsets = [(None, {'fields': list(form.base_fields)})]
adminForm = admin.helpers.AdminForm(form, fieldsets, {})
context = {
'title': _('Manage TAS User: %s') % user.username,
'adminform': adminForm,
'form_url': form_url,
'form': form,
'opts': self.model._meta,
'original': user,
}
context.update(admin.site.each_context())
return TemplateResponse(request,
'admin/tas/tas_manage.html',
context, current_app=self.admin_site.name)