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


Python utils.setting函数代码示例

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


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

示例1: auth_complete

 def auth_complete(self, *args, **kwargs):
     """Returns user, might be logged in"""
     if 'code' in self.data:
         url = GITHUB_ACCESS_TOKEN_URL + '?' + urllib.urlencode({
               'client_id': setting('GITHUB_APP_ID'),
               'redirect_uri': self.redirect_uri,
               'client_secret': setting('GITHUB_API_SECRET'),
               'code': self.data['code']
         })
         response = cgi.parse_qs(urllib.urlopen(url).read())
         if response.get('error'):
             error = self.data.get('error') or 'unknown error'
             raise ValueError('Authentication error: %s' % error)
         access_token = response['access_token'][0]
         data = self.user_data(access_token)
         if data is not None:
             if 'error' in data:
                 error = self.data.get('error') or 'unknown error'
                 raise ValueError('Authentication error: %s' % error)
             data['access_token'] = access_token
         kwargs.update({'response': data, GithubBackend.name: True})
         return authenticate(*args, **kwargs)
     else:
         error = self.data.get('error') or 'unknown error'
         raise ValueError('Authentication error: %s' % error)
开发者ID:FrankBie,项目名称:django-social-auth,代码行数:25,代码来源:github.py

示例2: setUp

 def setUp(self, *args, **kwargs):
     super(FacebookTestCase, self).setUp(*args, **kwargs)
     self.user = setting('TEST_FACEBOOK_USER')
     self.passwd = setting('TEST_FACEBOOK_PASSWORD')
     # check that user and password are setup properly
     self.assertTrue(self.user)
     self.assertTrue(self.passwd)
开发者ID:FrankBie,项目名称:django-social-auth,代码行数:7,代码来源:facebook.py

示例3: get_username

def get_username(
                 user_exists=UserSocialAuth.simple_user_exists,
                 ):
    """Return an username for new user. Return current user username
    if user was given.
    """

    uuid_length = setting('SOCIAL_AUTH_UUID_LENGTH', 16)
    do_slugify = setting('SOCIAL_AUTH_SLUGIFY_USERNAMES', False)

    username = uuid4().get_hex()

    max_length = UserSocialAuth.username_max_length()
    short_username = username[:max_length - uuid_length]
    final_username = UserSocialAuth.clean_username(username[:max_length])
    if do_slugify:
        final_username = slugify(final_username)

    # Generate a unique username for current user using username
    # as base but adding a unique hash at the end. Original
    # username is cut to avoid any field max_length.
    while user_exists(username=final_username):
        username = short_username + uuid4().get_hex()[:uuid_length]
        username = username[:max_length]
        final_username = UserSocialAuth.clean_username(username)
        if do_slugify:
            final_username = slugify(final_username)
    print final_username
    return final_username
开发者ID:wikilife-org,项目名称:datadonor,代码行数:29,代码来源:services.py

示例4: __init__

 def __init__(self, request, redirect):
     """Init method"""
     super(BaseOAuth, self).__init__(request, redirect)
     if setting('VAGRANT_ENABLED'):
         self.redirect_uri = "http://localhost:" + str(setting('VAGRANT_PORT_FORWARD')) + self.redirect
     else:
         self.redirect_uri = self.build_absolute_uri(self.redirect)
开发者ID:bilalaslam,项目名称:django-social-auth,代码行数:7,代码来源:__init__.py

示例5: get_username

def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs):
    """Return an username for new user. Return current user username
    if user was given.
    """
    if user:
        return {"username": user.username}

    if details.get(USERNAME):
        username = unicode(details[USERNAME])
    else:
        username = uuid4().get_hex()

    uuid_length = setting("SOCIAL_AUTH_UUID_LENGTH", 16)
    max_length = UserSocialAuth.username_max_length()
    do_slugify = setting("SOCIAL_AUTH_SLUGIFY_USERNAMES", False)
    short_username = username[: max_length - uuid_length]
    final_username = UserSocialAuth.clean_username(username[:max_length])
    if do_slugify:
        final_username = slugify(final_username)

    # Generate a unique username for current user using username
    # as base but adding a unique hash at the end. Original
    # username is cut to avoid any field max_length.
    while user_exists(username=final_username):
        username = short_username + uuid4().get_hex()[:uuid_length]
        final_username = UserSocialAuth.clean_username(username[:max_length])
        if do_slugify:
            final_username = slugify(final_username)

    return {"username": final_username}
开发者ID:gonsamuel,项目名称:djnro,代码行数:30,代码来源:user.py

示例6: vk_api

def vk_api(method, data, is_app=False):
    """Calls VK OpenAPI method
        https://vk.com/apiclub,
        https://vk.com/pages.php?o=-1&p=%C2%FB%EF%EE%EB%ED%E5%ED%E8%E5%20%E7'
                                        %E0%EF%F0%EE%F1%EE%E2%20%EA%20API
    """

    # We need to perform server-side call if no access_token
    if not 'access_token' in data:
        if not 'v' in data:
            data['v'] = VK_API_VERSION

        if not 'api_id' in data:
            data['api_id'] = setting('VKAPP_APP_ID' if is_app else 'VK_APP_ID')

        data['method'] = method
        data['format'] = 'json'

        url = VK_SERVER_API_URL
        secret = setting('VKAPP_API_SECRET' if is_app else 'VK_API_SECRET')

        param_list = sorted(list(item + '=' + data[item] for item in data))
        data['sig'] = md5(''.join(param_list) + secret).hexdigest()
    else:
        url = VK_API_URL + method

    params = urlencode(data)
    url += '?' + params
    try:
        return simplejson.load(dsa_urlopen(url))
    except (TypeError, KeyError, IOError, ValueError, IndexError):
        log('error', 'Could not load data from vk.com',
            exc_info=True, extra=dict(data=data))
        return None
开发者ID:Elec,项目名称:django-social-auth,代码行数:34,代码来源:vk.py

示例7: wrapper

        def wrapper(request, backend, *args, **kwargs):
            if redirect_name:
                redirect = reverse(redirect_name, args=(backend,))
            else:
                redirect = request.path
            backend = get_backend(backend, request, redirect)

            if not backend:
                return HttpResponseServerError('Incorrect authentication ' + \
                                               'service')

            try:
                return func(request, backend, *args, **kwargs)
            except Exception, e:  # some error ocurred
                if setting('DEBUG'):
                    raise
                backend_name = backend.AUTH_BACKEND.name

                log('error', unicode(e), exc_info=True,
                    extra=dict(request=request))

                if 'django.contrib.messages' in setting('INSTALLED_APPS'):
                    from django.contrib.messages.api import error
                    error(request, unicode(e), extra_tags=backend_name)
                else:
                    log('warn', 'Messages framework not in place, some '+
                                'errors have not been shown to the user.')

                url = setting('SOCIAL_AUTH_BACKEND_ERROR_URL', LOGIN_ERROR_URL)
                return HttpResponseRedirect(url)
开发者ID:FrankBie,项目名称:django-social-auth,代码行数:30,代码来源:views.py

示例8: auth_complete

    def auth_complete(self, *args, **kwargs):
        """Returns user, might be logged in"""
        if 'code' not in self.data:
            error = self.data.get('error') or 'unknown error'
            raise AuthFailed(self, error)

        url = GITHUB_ACCESS_TOKEN_URL + urlencode({
              'client_id': setting('GITHUB_APP_ID'),
              'redirect_uri': self.redirect_uri,
              'client_secret': setting('GITHUB_API_SECRET'),
              'code': self.data['code']
        })
        response = cgi.parse_qs(urlopen(url).read())
        if response.get('error'):
            error = self.data.get('error') or 'unknown error'
            raise AuthFailed(self, error)

        access_token = response['access_token'][0]
        data = self.user_data(access_token)
        if data is not None:
            if 'error' in data:
                error = self.data.get('error') or 'unknown error'
                raise AuthFailed(self, error)
            data['access_token'] = access_token

        kwargs.update({
            'auth': self,
            'response': data,
            self.AUTH_BACKEND.name: True
        })
        return authenticate(*args, **kwargs)
开发者ID:1010,项目名称:django-social-auth,代码行数:31,代码来源:github.py

示例9: complete_process

def complete_process(request, backend, *args, **kwargs):
    """Authentication complete process"""
    # pop redirect value before the session is trashed on login()
    redirect_value = request.session.get(REDIRECT_FIELD_NAME, '')
    user = auth_complete(request, backend, *args, **kwargs)

    if isinstance(user, HttpResponse):
        return user

    if not user and request.user.is_authenticated():
        return HttpResponseRedirect(redirect_value)

    if user:
        if getattr(user, 'is_active', True):
            # catch is_new flag before login() might reset the instance
            is_new = getattr(user, 'is_new', False)
            login(request, user)
            # user.social_user is the used UserSocialAuth instance defined
            # in authenticate process
            social_user = user.social_user
            if redirect_value:
                request.session[REDIRECT_FIELD_NAME] = redirect_value or \
                                                       DEFAULT_REDIRECT

            if setting('SOCIAL_AUTH_SESSION_EXPIRATION', True):
                # Set session expiration date if present and not disabled by
                # setting. Use last social-auth instance for current provider,
                # users can associate several accounts with a same provider.
                if social_user.expiration_delta():
                    try:
                        request.session.set_expiry(social_user.expiration_delta())
                    except OverflowError:
                        # Handle django time zone overflow, set default expiry.
                        request.session.set_expiry(None)

            # store last login backend name in session
            key = setting('SOCIAL_AUTH_LAST_LOGIN',
                          'social_auth_last_login_backend')
            request.session[key] = social_user.provider

            # Remove possible redirect URL from session, if this is a new
            # account, send him to the new-users-page if defined.
            new_user_redirect = backend_setting(backend,
                                           'SOCIAL_AUTH_NEW_USER_REDIRECT_URL')
            if new_user_redirect and is_new:
                url = new_user_redirect
            else:
                url = redirect_value or \
                      backend_setting(backend,
                                      'SOCIAL_AUTH_LOGIN_REDIRECT_URL') or \
                      DEFAULT_REDIRECT
        else:
            url = backend_setting(backend, 'SOCIAL_AUTH_INACTIVE_USER_URL',
                                  LOGIN_ERROR_URL)
    else:
        msg = setting('LOGIN_ERROR_MESSAGE', None)
        if msg:
            messages.error(request, msg)
        url = backend_setting(backend, 'LOGIN_ERROR_URL', LOGIN_ERROR_URL)
    return HttpResponseRedirect(url)
开发者ID:dongshilong,项目名称:Book-Sharing-Portal,代码行数:60,代码来源:views.py

示例10: setup_request

    def setup_request(self, extra_params=None):
        """Setup request"""
        openid_request = self.openid_request(extra_params)
        # Request some user details. Use attribute exchange if provider
        # advertises support.
        if openid_request.endpoint.supportsType(ax.AXMessage.ns_uri):
            fetch_request = ax.FetchRequest()
            # Mark all attributes as required, Google ignores optional ones
            for attr, alias in AX_SCHEMA_ATTRS + OLD_AX_ATTRS:
                fetch_request.add(ax.AttrInfo(attr, alias=alias, required=True))
        else:
            fetch_request = sreg.SRegRequest(optional=dict(SREG_ATTR).keys())
        openid_request.addExtension(fetch_request)

        # Add PAPE Extension for if configured
        preferred_policies = setting("SOCIAL_AUTH_OPENID_PAPE_PREFERRED_AUTH_POLICIES")
        preferred_level_types = setting("SOCIAL_AUTH_OPENID_PAPE_PREFERRED_AUTH_LEVEL_TYPES")
        max_age = setting("SOCIAL_AUTH_OPENID_PAPE_MAX_AUTH_AGE")
        if max_age is not None:
            try:
                max_age = int(max_age)
            except (ValueError, TypeError):
                max_age = None

        if max_age is not None or preferred_policies is not None or preferred_level_types is not None:
            pape_request = pape.Request(
                preferred_auth_policies=preferred_policies,
                max_auth_age=max_age,
                preferred_auth_level_types=preferred_level_types,
            )
            openid_request.addExtension(pape_request)

        return openid_request
开发者ID:numan,项目名称:django-social-auth,代码行数:33,代码来源:__init__.py

示例11: auth_process

def auth_process(request, backend):
    """Authenticate using social backend"""
    print(backend)
    data = request.POST if request.method == 'POST' else request.GET

    # Save extra data into session.
    for field_name in setting('SOCIAL_AUTH_FIELDS_STORED_IN_SESSION', []):
        if field_name in data:
            request.session[field_name] = data[field_name]

    # Save any defined next value into session
    if REDIRECT_FIELD_NAME in data:
        # Check and sanitize a user-defined GET/POST next field value
        redirect = data[REDIRECT_FIELD_NAME]
        if setting('SOCIAL_AUTH_SANITIZE_REDIRECTS', True):
            redirect = sanitize_redirect(request.get_host(), redirect)
        request.session[REDIRECT_FIELD_NAME] = redirect or DEFAULT_REDIRECT

    # Clean any partial pipeline info before starting the process
    clean_partial_pipeline(request)
    if backend.uses_redirect:
        return HttpResponseRedirect(backend.auth_url())
    else:
        return HttpResponse(backend.auth_html(),
                            content_type='text/html;charset=UTF-8')
开发者ID:jbau,项目名称:django-social-auth,代码行数:25,代码来源:views.py

示例12: auth_complete

    def auth_complete(self, *args, **kwargs):
        """Completes loging process, must return user instance"""
        if 'code' in self.data:
            url = 'https://graph.facebook.com/oauth/access_token?' + \
                  urlencode({'client_id': setting(self.SETTINGS_KEY_NAME),
                             'redirect_uri': self.redirect_uri,
                             'client_secret': setting(self.SETTINGS_SECRET_NAME),
                             'code': self.data['code']})
            response = cgi.parse_qs(urlopen(url).read())
            access_token = response['access_token'][0]
            data = self.user_data(access_token)
            if data is not None:
                if 'error' in data:
                    error = self.data.get('error') or 'unknown error'
                    raise ValueError('Authentication error: %s' % error)
                data['access_token'] = access_token
                # expires will not be part of response if offline access
                # premission was requested
                if 'expires' in response:
                    data['expires'] = response['expires'][0]
            kwargs.update({
                'auth': self,
                'response': data,
                self.AUTH_BACKEND.name: True
            })
#            logger.info('%s %s' % (args, kwargs))
            return authenticate(*args, **kwargs)
        else:
            error = self.data.get('error') or 'unknown error'
            raise ValueError('Authentication error: %s' % error)
开发者ID:AdvisorDeck,项目名称:django-social-auth,代码行数:30,代码来源:facebook.py

示例13: auth_complete

    def auth_complete(self, *args, **kwargs):
        if 'code' not in self.data:
            if self.data.get('error') == 'access_denied':
                raise AuthCanceled(self)
            else:
                raise AuthException(self)

        post_data = urlencode({
            'client_id': setting(self.SETTINGS_KEY_NAME),
            'redirect_uri': self.redirect_uri,
            'client_secret': setting(self.SETTINGS_SECRET_NAME),
            'code': self.data['code'],
            'grant_type': 'authorization_code'
        })
        try:
            response = simplejson.loads(urlopen(self.ACCESS_TOKEN_URL, post_data).read())
        except HTTPError:
            raise AuthFailed(self, 'There was an error authenticating the app')

        access_token = response['access_token']
        data = self.user_data(response)

        if data is not None:
            data['access_token'] = access_token
            # expires will not be part of response if offline access
            # premission was requested
            if 'expires_in' in response:
                data['expires_in'] = response['expires_in']

        kwargs.update({'auth': self,
                       'response': data,
                       self.AUTH_BACKEND.name: True})
        return authenticate(*args, **kwargs)
开发者ID:thoslin,项目名称:django-social-auth,代码行数:33,代码来源:renren.py

示例14: auth_complete

    def auth_complete(self, *args, **kwargs):
        """Completes login process, must return user instance"""
        access_token = None
        if self.data.get('error'):
            error = self.data.get('error_description') or self.data['error']
            raise AuthFailed(self, error)

        client_id, client_secret = self.get_key_and_secret()
        try:
            shop_url = self.request.GET.get('shop')
            self.shopifyAPI.Session.setup(
                api_key=setting('SHOPIFY_APP_API_KEY'),
                secret=setting('SHOPIFY_SHARED_SECRET')
            )
            shopify_session = self.shopifyAPI.Session(shop_url,
                                                      self.request.REQUEST)
            access_token = shopify_session.token
        except self.shopifyAPI.ValidationException as e:
            raise AuthCanceled(self)
        except HTTPError as e:
            if e.code == 400:
                raise AuthCanceled(self)
            else:
                raise

        if not access_token:
            raise AuthFailed(self, 'Authentication Failed')
        return self.do_auth(access_token, shop_url, shopify_session.url,
                            *args, **kwargs)
开发者ID:Memrise,项目名称:django-social-auth,代码行数:29,代码来源:shopify.py

示例15: get_backends

def get_backends(force_load=False):
    """
    Entry point to the BACKENDS cache. If BACKENDSCACHE hasn't been
    populated, each of the modules referenced in
    AUTHENTICATION_BACKENDS is imported and checked for a BACKENDS
    definition and if enabled, added to the cache.

    Previously all backends were attempted to be loaded at
    import time of this module, which meant that backends that subclass
    bases found in this module would not have the chance to be loaded
    by the time they were added to this module's BACKENDS dict. See:
    https://github.com/omab/django-social-auth/issues/204

    This new approach ensures that backends are allowed to subclass from
    bases in this module and still be picked up.

    A force_load boolean arg is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    if not BACKENDSCACHE or force_load:
        for auth_backend in setting('AUTHENTICATION_BACKENDS'):
            module = import_module(auth_backend.rsplit(".", 1)[0])
            backends = getattr(module, "BACKENDS", {})
            for name, backend in backends.items():
                if backend.enabled() and name in setting('SOCIAL_AUTH_ENABLED_BACKENDS'):
                    BACKENDSCACHE[name] = backend
    return BACKENDSCACHE
开发者ID:chrisgilmerproj,项目名称:django-social-auth,代码行数:27,代码来源:__init__.py


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