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


Python util.get_context函数代码示例

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


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

示例1: add

def add(request, template_name='im/auth/ldap_add.html'):

    provider = auth.get_provider('ldap', request.user)

    # Check that provider's policy allows to add provider to account
    if not provider.get_add_policy:
        messages.error(request, provider.get_add_disabled_msg)
        return HttpResponseRedirect(reverse('edit_profile'))

    if request.method == "GET":
        return render_response(
            template_name,
            login_form=LDAPLoginForm(request=request),
            context_instance=get_context(request, provider=LDAP_PROVIDER)
        )

    form = LDAPLoginForm(data=request.POST,
                         request=request)

    if form.is_valid():
        provider = auth.get_provider('ldap', request.user)

        user = form.ldap_user_cache

        provider_info = dict(user.ldap_user.attrs)
        try:
            user_info = populate_user_attributes(provider, provider_info)
            user_id = user_info.pop('identifier')
        except (ValueError, KeyError):
            logger.exception("Failed to map attributes from LDAP provider."
                             " Provider attributes: %s", provider_info)
            msg = 'Invalid LDAP response. Please contact support.'
            messages.error(request, msg)
            return HttpResponseRedirect(reverse('login'))
        affiliation = 'LDAP'  # TODO: Add LDAP server name?
        user_info['affiliation'] = affiliation
        provider_info = dict([(k, smart_unicode(v, errors="ignore"))
                              for k, v in provider_info.items()
                              if k in provider.get_provider_info_attributes()])

    if hasattr(user, 'group_names') and provider.get_policy('mirror_groups'):
        groups = [Group.objects.get_or_create(name=group_name)[0]
                  for group_name in user.group_names]
        user_info['groups'] = groups

        return handle_third_party_login(request, provider_module="ldap",
                                        identifier=user_id,
                                        provider_info=provider_info,
                                        affiliation=affiliation,
                                        user_info=user_info)
    else:
        return render_response(
            template_name,
            form=LDAPLoginForm(request=request),
            context_instance=get_context(request, provider=LDAP_PROVIDER)
        )
开发者ID:AthinaB,项目名称:synnefo,代码行数:56,代码来源:ldap.py

示例2: handle_get_to_login_view

def handle_get_to_login_view(request, primary_provider, login_form,
                             template_name="im/login.html",
                             extra_context=None):
    """Common handling of a GET request to a login view.

    Handle a GET request to a login view either by redirecting the user
    to landing page in case the user is authenticated, or by rendering
    the login template with the 'primary_provider' correctly set.

    """
    extra_context = extra_context or {}

    third_party_token = request.GET.get('key', False)
    if third_party_token:
        messages.info(request, astakos_messages.AUTH_PROVIDER_LOGIN_TO_ADD)

    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('landing'))

    extra_context['primary_provider'] = primary_provider

    return render_response(
        template_name,
        login_form=login_form,
        context_instance=get_context(request, extra_context)
    )
开发者ID:grnet,项目名称:synnefo,代码行数:26,代码来源:im.py

示例3: resource_usage

def resource_usage(request):

    resources_meta = presentation.RESOURCES

    current_usage = quotas.get_user_quotas(request.user)
    current_usage = json.dumps(current_usage['system'])
    resource_catalog, resource_groups = _resources_catalog()
    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))

    return render_response('im/resource_usage.html',
                           context_instance=get_context(request),
                           resource_catalog=resource_catalog,
                           resource_groups=resource_groups,
                           resources_order=resources_order,
                           current_usage=current_usage,
                           token_cookie_name=settings.COOKIE_NAME,
                           usage_update_interval=
                           settings.USAGE_UPDATE_INTERVAL)
开发者ID:antonis-m,项目名称:synnefo,代码行数:26,代码来源:im.py

示例4: login

def login(request, template_name='im/login.html', extra_context=None):
    """
    Renders login page.

    **Arguments**

    ``template_name``
        A custom login template to use. This is optional; if not specified,
        this will default to ``im/login.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.
    """

    extra_context = extra_context or {}

    third_party_token = request.GET.get('key', False)
    if third_party_token:
        messages.info(request, astakos_messages.AUTH_PROVIDER_LOGIN_TO_ADD)

    if request.user.is_authenticated():
        return HttpResponseRedirect(reverse('landing'))

    return render_response(
        template_name,
        login_form=LoginForm(request=request),
        context_instance=get_context(request, extra_context)
    )
开发者ID:antonis-m,项目名称:synnefo,代码行数:28,代码来源:im.py

示例5: resource_usage

def resource_usage(request):

    resources_meta = presentation.RESOURCES

    # resolve uuids of projects the user consumes quota from
    user = request.user
    quota_filters = Q(usage_min__gt=0, limit__gt=0)
    quota_uuids = map(lambda k: k[1],
                      quotas.get_users_quotas_counters([user],
                                                       flt=quota_filters)[0].keys(),)
    # resolve uuids of projects the user is member to
    user_memberships = request.user.projectmembership_set.actually_accepted()
    membership_uuids = [m.project.uuid for m in user_memberships]

    # merge uuids
    uuids = set(quota_uuids + membership_uuids)
    uuid_refs = map(quotas.project_ref, uuids)

    user_quotas = quotas.get_user_quotas(request.user, sources=uuid_refs)
    projects = Project.objects.filter(uuid__in=uuids)
    user_projects = projects_api.get_projects_details(projects)
    resource_catalog, resource_groups = _resources_catalog()

    if resource_catalog is False:
        # on fail resource_groups contains the result object
        result = resource_groups
        messages.error(request, 'Unable to retrieve system resources: %s' %
                       result.reason)

    # Exclude projects that are terminated *and* the user has no active
    # resources (usage>0)
    non_terminated_projects = [p["id"] for p in user_projects
                               if p["state"] != "terminated"]
    user_quotas = dict([(p_id,  p_quotas)
                        for (p_id, p_quotas) in user_quotas.items()
                        if p_id in non_terminated_projects
                        or
                        filter(lambda x: x["usage"] > 0, p_quotas.values())])

    resource_catalog = json.dumps(resource_catalog)
    resource_groups = json.dumps(resource_groups)
    resources_order = json.dumps(resources_meta.get('resources_order'))
    projects_details = json.dumps(user_projects, default=_dthandler)
    user_quotas = json.dumps(user_quotas)

    interval = settings.USAGE_UPDATE_INTERVAL
    return render_response('im/resource_usage.html',
                           context_instance=get_context(request),
                           resource_catalog=resource_catalog,
                           resource_groups=resource_groups,
                           resources_order=resources_order,
                           projects_details=projects_details,
                           user_quotas=user_quotas,
                           token_cookie_name=settings.COOKIE_NAME,
                           usage_update_interval=interval)
开发者ID:grnet,项目名称:synnefo,代码行数:55,代码来源:im.py

示例6: feedback

def feedback(request, template_name='im/feedback.html',
             email_template_name='im/feedback_mail.txt', extra_context=None):
    """
    Allows a user to send feedback.

    In case of GET request renders a form for providing the feedback
    information.
    In case of POST sends an email to support team.

    If the user isn't logged in, redirects to settings.LOGIN_URL.

    **Arguments**

    ``template_name``
        A custom template to use. This is optional; if not specified,
        this will default to ``im/feedback.html``.

    ``extra_context``
        An dictionary of variables to add to the template context.

    **Template:**

    im/signup.html or ``template_name`` keyword argument.

    **Settings:**

    * LOGIN_URL: login uri
    """
    extra_context = extra_context or {}
    if request.method == 'GET':
        form = FeedbackForm()
    if request.method == 'POST':
        if not request.user:
            return HttpResponse('Unauthorized', status=401)

        form = FeedbackForm(request.POST)
        if form.is_valid():
            msg = form.cleaned_data['feedback_msg']
            data = form.cleaned_data['feedback_data']
            send_feedback(msg, data, request.user, email_template_name)
            message = _(astakos_messages.FEEDBACK_SENT)
            messages.success(request, message)
            return HttpResponseRedirect(reverse('feedback'))

    return render_response(template_name,
                           feedback_form=form,
                           context_instance=get_context(request,
                                                        extra_context))
开发者ID:grnet,项目名称:synnefo,代码行数:48,代码来源:im.py

示例7: _approval_terms_post

def _approval_terms_post(request, template_name, terms, extra_context):
    next = restrict_next(
        request.POST.get('next'),
        domain=settings.COOKIE_DOMAIN
    )
    if not next:
        next = reverse('index')
    form = SignApprovalTermsForm(request.POST, instance=request.user)
    if not form.is_valid():
        return render_response(template_name,
                               terms=terms,
                               approval_terms_form=form,
                               context_instance=get_context(request,
                                                            extra_context))
    user = form.save()
    return HttpResponseRedirect(next)
开发者ID:grnet,项目名称:synnefo,代码行数:16,代码来源:im.py

示例8: request_change_email

def request_change_email(request,
                 email_to_new_template_name='registration/email_change_email_new_email.txt',
                 form_template_name='registration/email_change_form.html',
                 extra_context=None):

    extra_context = extra_context or {}

    if not settings.EMAILCHANGE_ENABLED:
        raise PermissionDenied

    if not request.user.is_authenticated():
        path = quote(request.get_full_path())
        url = request.build_absolute_uri(reverse('index'))
        return HttpResponseRedirect(url + '?next=' + path)

    # clean up expired email changes
    if request.user.email_change_is_pending():
        change = request.user.emailchanges.get()
        if change.activation_key_expired():
            change.delete()
            return HttpResponseRedirect(reverse('email_change'))

    form = EmailChangeForm(request.POST or None)
    if request.method == 'POST' and form.is_valid():
        new_email = request.POST['new_email_address']
        try:
            change_user_email(
                user=request.user,
                new_email=new_email,
                email_to_new_template_name=email_to_new_template_name,
            )
            msg = _(astakos_messages.EMAIL_CHANGE_REGISTERED)
            messages.success(request, msg)
            return HttpResponseRedirect(reverse('edit_profile'))
        except ValidationError:
            pass


    if request.user.email_change_is_pending():
        messages.warning(request,
                         astakos_messages.PENDING_EMAIL_CHANGE_REQUEST)

    return render_response(
        form_template_name,
        form=form,
        context_instance=get_context(request, extra_context)
    )
开发者ID:grnet,项目名称:synnefo,代码行数:47,代码来源:im.py

示例9: api_access

def api_access(request, template_name='im/api_access.html',
               extra_context=None):
    """
    API access view.
    """
    context = {}

    url = get_public_endpoint(settings.astakos_services, 'identity')
    context['services'] = Component.catalog()
    context['token_url'] = url
    context['user'] = request.user
    context['client_url'] = settings.API_CLIENT_URL

    if extra_context:
        context.update(extra_context)
    context_instance = get_context(request, context)
    return render_response(template_name,
                           context_instance=context_instance)
开发者ID:grnet,项目名称:synnefo,代码行数:18,代码来源:im.py

示例10: change_email

def change_email(request, activation_key=None,
                 email_template_name='registration/email_change_email.txt',
                 form_template_name='registration/email_change_form.html',
                 confirm_template_name='registration/email_change_done.html',
                 extra_context=None):
    extra_context = extra_context or {}

    if not settings.EMAILCHANGE_ENABLED:
        raise PermissionDenied

    if activation_key:
        try:
            try:
                email_change = EmailChange.objects.get(
                    activation_key=activation_key)
            except EmailChange.DoesNotExist:
                logger.error("[change-email] Invalid or used activation "
                             "code, %s", activation_key)
                raise Http404

            if (
                request.user.is_authenticated() and
                request.user == email_change.user or not
                request.user.is_authenticated()
            ):
                user = EmailChange.objects.change_email(activation_key)
                msg = _(astakos_messages.EMAIL_CHANGED)
                messages.success(request, msg)
                transaction.commit()
                return HttpResponseRedirect(reverse('edit_profile'))
            else:
                logger.error("[change-email] Access from invalid user, %s %s",
                             email_change.user, request.user.log_display)
                raise PermissionDenied
        except ValueError, e:
            messages.error(request, e)
            transaction.rollback()
            return HttpResponseRedirect(reverse('index'))

        return render_response(confirm_template_name,
                               modified_user=user if 'user' in locals()
                               else None,
                               context_instance=get_context(request,
                                                            extra_context))
开发者ID:AthinaB,项目名称:synnefo,代码行数:44,代码来源:im.py

示例11: login

def login(request, template_name="im/login.html", on_failure='im/login.html',
          signup_template="/im/third_party_check_local.html",
          extra_context=None):
    """
    on_failure: the template name to render on login failure
    """
    if request.method == 'GET':
        return handle_get_to_login_view(request,
                                        primary_provider=LDAP_PROVIDER,
                                        login_form=LDAPLoginForm(request),
                                        template_name=template_name,
                                        extra_context=extra_context)

    # 'limited' attribute is used by recapatcha
    was_limited = getattr(request, 'limited', False)
    next = get_query(request).get('next', '')
    third_party_token = get_query(request).get('key', False)

    form = LDAPLoginForm(data=request.POST,
                         was_limited=was_limited,
                         request=request)
    provider = LDAP_PROVIDER

    if not form.is_valid():
        if third_party_token:
            messages.info(request, provider.get_login_to_add_msg)

        return render_to_response(
            on_failure,
            {'login_form': form,
             'next': next,
             'key': third_party_token},
            context_instance=get_context(request,
                                         primary_provider=LDAP_PROVIDER))

    # get the user from the cache
    user = form.ldap_user_cache
    provider = auth.get_provider('ldap', user)

    affiliation = 'LDAP'
    provider_info = dict(user.ldap_user.attrs)
    try:
        user_info = populate_user_attributes(provider, provider_info)
        user_id = user_info.pop('identifier')
    except (ValueError, KeyError):
        logger.exception("Failed to map attributes from LDAP provider."
                         " Provider attributes: %s", provider_info)
        msg = 'Invalid LDAP response. Please contact support.'
        messages.error(request, msg)
        return HttpResponseRedirect(reverse('login'))

    provider_info = dict([(k, smart_unicode(v, errors="ignore"))
                          for k, v in provider_info.items()
                          if k in provider.get_provider_info_attributes()])

    user_info['affiliation'] = affiliation

    if hasattr(user, 'group_names') and provider.get_policy('mirror_groups'):
        groups = [Group.objects.get_or_create(name=group_name)[0]
                  for group_name in user.group_names]
        user_info['groups'] = groups

    try:
        return handle_third_party_login(request, provider_module="ldap",
                                        identifier=user_id,
                                        provider_info=provider_info,
                                        affiliation=affiliation,
                                        user_info=user_info)
    except AstakosUser.DoesNotExist:
        third_party_key = get_pending_key(request)
        return handle_third_party_signup(request, user_id, 'ldap',
                                         third_party_key,
                                         provider_info,
                                         user_info,
                                         signup_template,
                                         extra_context)
开发者ID:AthinaB,项目名称:synnefo,代码行数:76,代码来源:ldap.py

示例12: render_response

        request.user.save()

    # existing providers
    user_providers = request.user.get_enabled_auth_providers()
    user_disabled_providers = request.user.get_disabled_auth_providers()

    # providers that user can add
    user_available_providers = request.user.get_available_auth_providers()

    extra_context['services'] = Component.catalog().values()
    return render_response(template_name,
                           profile_form=form,
                           user_providers=user_providers,
                           user_disabled_providers=user_disabled_providers,
                           user_available_providers=user_available_providers,
                           context_instance=get_context(request,
                                                        extra_context))


@transaction.atomic
@require_http_methods(["GET", "POST"])
@cookie_fix
def signup(request, template_name='im/signup.html', on_success='index',
           extra_context=None, activation_backend=None):
    """
    Allows a user to create a local account.

    In case of GET request renders a form for entering the user information.
    In case of POST handles the signup.

    The user activation will be delegated to the backend specified by the
    ``activation_backend`` keyword argument if present, otherwise to the
开发者ID:grnet,项目名称:synnefo,代码行数:32,代码来源:im.py

示例13: how_it_works

def how_it_works(request):
    return render_response('im/how_it_works.html',
                           context_instance=get_context(request))
开发者ID:skalkoto,项目名称:synnefo,代码行数:3,代码来源:projects.py

示例14: signup


#.........这里部分代码省略.........

    **Template:**

    im/signup.html or ``template_name`` keyword argument.
    """
    extra_context = extra_context or {}
    if request.user.is_authenticated():
        logger.info("%s already signed in, redirect to index",
                    request.user.log_display)
        return HttpResponseRedirect(reverse('index'))

    provider = get_query(request).get('provider', 'local')
    if not auth.get_provider(provider).get_create_policy:
        logger.error("%s provider not available for signup", provider)
        raise PermissionDenied

    instance = None

    # user registered using third party provider
    third_party_token = request.REQUEST.get('third_party_token', None)
    unverified = None
    if third_party_token:
        # retreive third party entry. This was created right after the initial
        # third party provider handshake.
        pending = get_object_or_404(PendingThirdPartyUser,
                                    token=third_party_token)

        provider = pending.provider

        # clone third party instance into the corresponding AstakosUser
        instance = pending.get_user_instance()
        get_unverified = AstakosUserAuthProvider.objects.unverified

        # check existing unverified entries
        unverified = get_unverified(pending.provider,
                                    identifier=pending.third_party_identifier)

        if unverified and request.method == 'GET':
            messages.warning(request, unverified.get_pending_registration_msg)
            if unverified.user.moderated:
                messages.warning(request,
                                 unverified.get_pending_resend_activation_msg)
            else:
                messages.warning(request,
                                 unverified.get_pending_moderation_msg)

    # prepare activation backend based on current request
    if not activation_backend:
        activation_backend = activation_backends.get_backend()

    form_kwargs = {'instance': instance, 'request': request}
    if third_party_token:
        form_kwargs['third_party_token'] = third_party_token

    form = activation_backend.get_signup_form(
        provider, None, **form_kwargs)

    if request.method == 'POST':
        form = activation_backend.get_signup_form(
            provider,
            request.POST,
            **form_kwargs)

        if form.is_valid():
            user = form.save(commit=False)

            # delete previously unverified accounts
            if AstakosUser.objects.user_exists(user.email):
                AstakosUser.objects.get_by_identifier(user.email).delete()

            # store_user so that user auth providers get initialized
            form.store_user(user, request)
            result = activation_backend.handle_registration(user)
            if result.status == \
                    activation_backend.Result.PENDING_MODERATION:
                # user should be warned that his account is not active yet
                status = messages.WARNING
            else:
                status = messages.SUCCESS
            message = result.message
            activation_backend.send_result_notifications(result, user)

            # commit user entry
            transaction.commit()

            if user and user.is_active:
                # activation backend directly activated the user
                # log him in
                next = request.POST.get('next', '')
                response = prepare_response(request, user, next=next)
                return response

            messages.add_message(request, status, message)
            return HttpResponseRedirect(reverse(on_success))

    return render_response(template_name,
                           signup_form=form,
                           third_party_token=third_party_token,
                           provider=provider,
                           context_instance=get_context(request, extra_context))
开发者ID:cstavr,项目名称:synnefo,代码行数:101,代码来源:im.py

示例15: landing

def landing(request):
    context = {'services': Component.catalog(orderfor='dashboard')}
    return render_response(
        'im/landing.html',
        context_instance=get_context(request), **context)
开发者ID:grnet,项目名称:synnefo,代码行数:5,代码来源:im.py


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