当前位置: 首页>>代码示例>>Python>>正文


Python http.TASClient类代码示例

本文整理汇总了Python中pytas.http.TASClient的典型用法代码示例。如果您正苦于以下问题:Python TASClient类的具体用法?Python TASClient怎么用?Python TASClient使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了TASClient类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: register

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)
开发者ID:,项目名称:,代码行数:60,代码来源:

示例2: profile_edit

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)
开发者ID:,项目名称:,代码行数:28,代码来源:

示例3: _process_password_reset_confirm

def _process_password_reset_confirm(request, form):
    if form.is_valid():
        data = form.cleaned_data
        try:
            tas = TASClient()
            return tas.confirm_password_reset(data['username'], data['code'],
                                              data['password'], source='DesignSafe')
        except Exception as e:
            if len(e.args) > 1:
                if re.search('account does not match', e.args[1]):
                    form.add_error('username', e.args[1])
                elif re.search('No password reset request matches', e.args[1]):
                    form.add_error('code', e.args[1])
                elif re.search('complexity requirements', e.args[1]):
                    form.add_error('password', e.args[1])
                elif re.search('expired', e.args[1]):
                    form.add_error('code', e.args[1])
                else:
                    logger.exception('Password reset failed')
                    form.add_error('__all__', 'An unexpected error occurred. '
                                              'Please try again')
            else:
                form.add_error('__all__', 'An unexpected error occurred. '
                                          'Please try again')

    return False
开发者ID:DesignSafe-CI,项目名称:portal,代码行数:26,代码来源:views.py

示例4: make_user_pi

    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)
开发者ID:,项目名称:,代码行数:33,代码来源:

示例5: user_projects

def user_projects( request, username ):
    logger.info( 'User projects requested by admin: %s for user %s', request.user, username )
    resp = {
        'status': 'error',
        'msg': '',
        'result': []
    }
    if username:
        tas = TASClient()
        try:
            userData = tas.get_user(username=username)
            try:
                userProjects = tas.projects_for_user( username=username )
                chameleonProjects = tas.projects_for_group('Chameleon');
                if (chameleonProjects and userProjects):
                    for project in userProjects:
                        if project in chameleonProjects:
                            resp['status'] = 'success'
                            resp['result'].append(project)
                            logger.info( 'Total chameleon projects for user %s: %s', username, len( resp ) )
            except Exception as e:
                logger.debug('Error loading projects for user: %s', username)
                resp['msg'] = 'Error loading projects for user: %s' %username
        except Exception as e:
            logger.debug('User not found with username: %s', username)
            resp['msg'] = 'User not found.'
    return HttpResponse(json.dumps(resp), content_type="application/json")
开发者ID:,项目名称:,代码行数:27,代码来源:

示例6: reset_user_password

    def reset_user_password(self, request, selected_users, form_url=''):

        # The user has already confirmed the action.
        # Trigger password reset notifications
        if request.POST.get('post'):
            tas = TASClient()
            for user in selected_users:
                try:
                    resp = tas.request_password_reset(user.username, source='Chameleon')
                    self.message_user(request, _('Password Reset notification sent to: %s') % user.username)
                except:
                    logger.exception( 'Failed password reset request' )
                    self.message_user(request, _('Unable to reset password for: %s') % user.username, level=messages.ERROR)

            return None

        context = {
            'title': _('Send Password Reset Notification'),
            '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/reset_user_password.html',
            context, current_app=self.admin_site.name)
开发者ID:,项目名称:,代码行数:28,代码来源:

示例7: email_confirmation

def email_confirmation(request):
    context = {}
    if request.method == 'POST':
        form = EmailConfirmationForm(request.POST)
        if form.is_valid():
            code = request.POST['code']
            username = request.POST['username']
            try:
                tas = TASClient()
                user = tas.get_user(username=username)
                tas.verify_user(user['id'], code)
                activate_local_user(username)
                messages.success(request, 'Congratulations, your email has been verified! Please log in now.')
                return HttpResponseRedirect(reverse('tas:profile'))
            except Exception as e:
                logger.exception('Email verification failed')
                if e[0] == 'User not found':
                    form.add_error('username', e[1])
                else:
                    form.add_error('code', 'Email verification failed. Please check your verification code and username and try again.')

    else:
        form = EmailConfirmationForm(initial={'code': request.GET.get('code', '')})

    context['form'] = form

    return render(request, 'tas/email_confirmation.html', context)
开发者ID:,项目名称:,代码行数:27,代码来源:

示例8: get_departments_json

def get_departments_json(request):
    institutionId = request.GET.get('institutionId')
    if institutionId:
        tas = TASClient()
        departments = tas.get_departments(institutionId)
    else:
        departments = {}
    return HttpResponse(json.dumps(departments), content_type='application/json')
开发者ID:,项目名称:,代码行数:8,代码来源:

示例9: TASBackend

class TASBackend(ModelBackend):

    logger = logging.getLogger(__name__)

    def __init__(self):
        self.tas = TASClient()

    # Create an authentication method
    # This is called by the standard Django login procedure
    def authenticate(self, username=None, password=None, request=None, **kwargs):
        user = None
        if username is not None and password is not None:
            tas_user = None
            if request is not None:
                self.logger.info('Attempting login via TAS for user "%s" from IP "%s"' % (username, request.META.get('REMOTE_ADDR')))
            else:
                self.logger.info('Attempting login via TAS for user "%s" from IP "%s"' % (username, 'unknown'))
            try:
                # Check if this user is valid on the mail server
                if self.tas.authenticate(username, password):
                    tas_user = self.tas.get_user(username=username)
                    self.logger.info('Login successful for user "%s"' % username)
                else:
                    raise ValidationError('Authentication Error', 'Your username or password is incorrect.')
            except Exception as e:
                self.logger.warning(e.args)
                if re.search(r'PendingEmailConfirmation', e.args[1]):
                    raise ValidationError('Please confirm your email address before logging in.')
                else:
                    raise ValidationError(e.args[1])

            if tas_user is not None:
                UserModel = get_user_model()
                try:
                    # Check if the user exists in Django's local database
                    user = UserModel.objects.get(username=username)
                    user.first_name = tas_user['firstName']
                    user.last_name = tas_user['lastName']
                    user.email = tas_user['email']
                    user.save()

                except UserModel.DoesNotExist:
                    # Create a user in Django's local database
                    self.logger.info('Creating local user record for "%s" from TAS Profile' % username)
                    user = UserModel.objects.create_user(
                        username=username,
                        first_name=tas_user['firstName'],
                        last_name=tas_user['lastName'],
                        email=tas_user['email']
                        )

                try:
                    profile = DesignSafeProfile.objects.get(user=user)
                except DesignSafeProfile.DoesNotExist:
                    profile = DesignSafeProfile(user=user)
                    profile.save()

        return user
开发者ID:DesignSafe-CI,项目名称:portal,代码行数:58,代码来源:backends.py

示例10: view

def view( request ):
    resp = ''
    try:
        tas = TASClient()
        resp = tas.projects_for_group('Chameleon')
        logger.debug( 'Total projects: %s', len(resp) )
    except Exception as e:
        logger.exception('Error loading chameleon projects')
        messages.error( request, e[0] )
        raise Exception('Error loading chameleon projects')
    return HttpResponse(json.dumps(resp), content_type="application/json")
开发者ID:,项目名称:,代码行数:11,代码来源:

示例11: profile

def profile(request):
    context = {}

    try:
        tas = TASClient()
        resp = tas.get_user(username=request.user)
        context['profile'] = resp
    except:
        context['profile'] = False
        # raise Exception('error loading profile')

    return render(request, 'tas/profile.html', context)
开发者ID:ChameleonCloud,项目名称:portal,代码行数:12,代码来源:views.py

示例12: get_fields_choices

def get_fields_choices():
    choices = (('', 'Choose One'),)
    tas = TASClient()
    fields = tas.fields()
    for f in fields:
        choices = choices + ((f['id'], f['name']),)
        if f['children']:
            for c in f['children']:
                choices = choices + ((c['id'], '--- ' + c['name']),)
                if c['children']:
                    for g in c['children']:
                        choices = choices + ((g['id'], '--- --- ' + g['name']),)
    return choices
开发者ID:,项目名称:,代码行数:13,代码来源:

示例13: get_project_users_json

def get_project_users_json( request, project_id=None ):
    logger.info( 'Projects users requested.')
    resp = []
    try:
        tas = TASClient()
        if project_id is not None:
            resp = tas.get_project_users( project_id=project_id )
            logger.info( 'Total users for project %s: %s', project_id, len( resp ) )
        else:
            raise Exception('Project id is required.')

    except Exception as e:
        traceback.print_exc()
        raise Exception('Error loading projects users.')
    return HttpResponse(json.dumps(resp), content_type="application/json")
开发者ID:,项目名称:,代码行数:15,代码来源:

示例14: profile_edit

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)
开发者ID:DesignSafe-CI,项目名称:portal,代码行数:48,代码来源:views.py

示例15: _process_password_reset_request

def _process_password_reset_request(request, form):
    if form.is_valid():
        # always show success to prevent data leaks
        messages.success(request, 'Your request has been received. If an account matching the username you provided is found, you will receive an email with further instructions to complete the password reset process.')

        username = form.cleaned_data['username']
        logger.info('Password reset request for username: "%s"', username)
        try:
            tas = TASClient()
            user = tas.get_user(username=username)
            resp = tas.request_password_reset(user['username'], source='Chameleon')
            logger.debug(resp)
        except:
            logger.exception('Failed password reset request')

        return True
    else:
        return False
开发者ID:,项目名称:,代码行数:18,代码来源:


注:本文中的pytas.http.TASClient类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。