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


Python httplib.UNAUTHORIZED属性代码示例

本文整理汇总了Python中httplib.UNAUTHORIZED属性的典型用法代码示例。如果您正苦于以下问题:Python httplib.UNAUTHORIZED属性的具体用法?Python httplib.UNAUTHORIZED怎么用?Python httplib.UNAUTHORIZED使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在httplib的用法示例。


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

示例1: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def get(self, url, headers=None, can_retry=True):
        """
        Issue REST GET request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in python native data format.
        """
        headers_ = {'Authorization': 'Bearer ' + str(self.access_token)}
        if headers is not None:
            headers_.update(headers)
        resp = requests.get(url, headers=headers_)
        if resp.status_code == httplib.OK:
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.get(url, headers, can_retry=False)
        else:
            raise BrightcoveApiClientError 
开发者ID:appsembler,项目名称:xblock-video,代码行数:24,代码来源:brightcove.py

示例2: authenticate_api

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def authenticate_api(self, **kwargs):
        """
        Call a sample Wistia API url to check on authentication success.

        Reference:
            https://wistia.com/doc/data-api#authentication

        Arguments:
            kwargs (dict): Wistia master token key-value pair.

        Returns:
            auth_data (dict): Master token, provided by a user, which is to be stored in Wistia's player metadata.
            error_status_message (str): Message with authentication outcomes for the sake of verbosity.
        """
        token, media_id = kwargs.get('token'), kwargs.get('video_id')  # pylint: disable=unused-variable
        auth_data, error_message = {}, ''
        auth_data['token'] = token
        url = self.captions_api.get('auth_sample_url').format(token=str(token))
        response = requests.get('https://' + url)
        if response.status_code == httplib.UNAUTHORIZED:
            error_message = "Authentication failed. " \
                            "Please ensure you have provided a valid master token, using Video API Token field."
        return auth_data, error_message 
开发者ID:appsembler,项目名称:xblock-video,代码行数:25,代码来源:wistia.py

示例3: __call__

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def __call__(self, callback):
        def wrapper(*args, **kwargs):
            if not is_local_request():
                self._logger.info('Dropping request with bad Host header.')
                abort(httplib.UNAUTHORIZED,
                      'Unauthorized, received request from non-local Host.')
                return

            if not self.is_request_authenticated():
                self._logger.info('Dropping request with bad HMAC.')
                abort(httplib.UNAUTHORIZED, 'Unauthorized, received bad HMAC.')
                return

            body = callback(*args, **kwargs)
            self.sign_response_headers(response.headers, body)
            return body
        return wrapper 
开发者ID:vheon,项目名称:JediHTTP,代码行数:19,代码来源:hmac_plugin.py

示例4: VerifyCredentials

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def VerifyCredentials(self):
    '''Returns a twitter.User instance if the authenticating user is valid.

    Returns: 
      A twitter.User instance representing that user if the
      credentials are valid, None otherwise.
    '''
    if not self._username:
      raise TwitterError("Api instance must first be given user credentials.")
    url = 'http://twitter.com/account/verify_credentials.json'
    try:
      json = self._FetchUrl(url, no_cache=True)
    except urllib2.HTTPError, http_error:
      if http_error.code == httplib.UNAUTHORIZED:
        return None
      else:
        raise http_error 
开发者ID:kuri65536,项目名称:python-for-android,代码行数:19,代码来源:twitter.py

示例5: post

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def post(self):  # pylint:disable-msg=invalid-name
    """Handles HTTP POST requests."""
    if not users.is_current_user_admin():
      self.response.set_status(httplib.UNAUTHORIZED)
      return
    key = self.request.data['key']
    url = self.request.data['url']
    client_id = self.request.data.get('client_id')
    client_secret = self.request.data.get('client_secret')
    if client_id and client_secret:
      credential = model.SetOAuth2Credential(key, client_id, client_secret)
    else:
      credential = model.GetOAuth2Credential(key) or model.OAuth2Credential()
    r = {
        'key': key,
        'url': url,
        'client_id': credential.client_id,
        'client_secret': credential.client_secret,
    }
    return r 
开发者ID:googlearchive,项目名称:cloud-playground,代码行数:22,代码来源:playground.py

示例6: test_no_user

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def test_no_user(self):
    self.logout_user()

    response = self.testapp.get(r'/', expect_errors=True)

    self.assertEqual(response.status_int, httplib.UNAUTHORIZED) 
开发者ID:google,项目名称:loaner,代码行数:8,代码来源:frontend_test.py

示例7: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def get(self, path):
    user = users.get_current_user()
    if not user:
      self.response.status = httplib.UNAUTHORIZED
      self.response.out.write('You must be logged in to access this app.')
      return
    elif user.email().split('@')[1] not in constants.APP_DOMAINS:
      self.response.status = httplib.FORBIDDEN
      self.response.out.write('Forbidden.')
      return

    if path == '/application.js':
      self._serve_frontend_javascript()
      return

    if self.bootstrap_completed or re.match(
        r'^/(bootstrap|authorization)', path):
      self._serve_frontend()
    else:
      self._sync_roles_if_necessary()
      # Re-checks if the bootstrap status did not change since the handler was
      # first loaded.
      self.bootstrap_completed = bootstrap.is_bootstrap_completed()
      if self.bootstrap_completed:
        self.redirect(path)
      else:
        datastore_user = user_model.User.get_user(user.email())
        if (permissions.Permissions.BOOTSTRAP in
            datastore_user.get_permissions()):
          self.redirect(BOOTSTRAP_URL)
        else:
          self.redirect('/maintenance') 
开发者ID:google,项目名称:loaner,代码行数:34,代码来源:frontend.py

示例8: _handle_missing_api_key

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def _handle_missing_api_key(self, app_info, start_response):
        code = httplib.UNAUTHORIZED
        detail = self._NO_API_KEY_MSG
        _logger.warn(u'Check not performed %d, %s', code, detail)
        app_info.response_code = code
        app_info.api_key_valid = False
        return self._return_simple_http_response(start_response, code, detail) 
开发者ID:cloudendpoints,项目名称:endpoints-management-python,代码行数:9,代码来源:wsgi.py

示例9: request

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def request(self, connection, url, headers, data=None, timeout=0):
		result = response = None
		try:
			if data: connection.request('POST', url, data, headers)
			else: connection.request('GET', url, headers=headers)
			response = self.timeout_response(connection, timeout)
			if not response:
				return None
			if response.status == httplib.UNAUTHORIZED:
				say_line('Wrong username or password for %s', self.server().name)
				self.authorization_failed = True
				raise NotAuthorized()
			r = self.max_redirects
			while response.status == httplib.TEMPORARY_REDIRECT:
				response.read()
				url = response.getheader('Location', '')
				if r == 0 or url == '': raise HTTPException('Too much or bad redirects')
				connection.request('GET', url, headers=headers)
				response = self.timeout_response(connection, timeout)
				r -= 1
			self.long_poll_url = response.getheader('X-Long-Polling', '')
			self.switch.update_time = bool(response.getheader('X-Roll-NTime', ''))
			hostList = response.getheader('X-Host-List', '')
			self.stratum_header = response.getheader('x-stratum', '')
			if (not self.options.nsf) and hostList: self.switch.add_servers(loads(hostList))
			result = loads(response.read())
			if result['error']:
				say_line('server error: %s', result['error']['message'])
				raise RPCError(result['error']['message'])
			return (connection, result)
		finally:
			if not result or not response or (response.version == 10 and response.getheader('connection', '') != 'keep-alive') or response.getheader('connection', '') == 'close':
				connection.close()
				connection = None 
开发者ID:theRealTacoTime,项目名称:poclbm,代码行数:36,代码来源:GetworkSource.py

示例10: post

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def post(self, url, payload, headers=None, can_retry=True):
        """
        Issue REST POST request to a given URL. Can throw ApiClientError or its subclass.

        Arguments:
            url (str): API url to fetch a resource from.
            payload (dict): POST data.
            headers (dict): Headers necessary as per API, e.g. authorization bearer to perform authorised requests.
            can_retry (bool): True if in a case of authentication error it can refresh access token and retry a call.
        Returns:
            Response in Python native data format.
        """
        headers_ = {
            'Authorization': 'Bearer ' + self.access_token,
            'Content-type': 'application/json'
        }
        if headers is not None:
            headers_.update(headers)

        resp = requests.post(url, data=payload, headers=headers_)
        log.debug("BC response status: {}".format(resp.status_code))
        if resp.status_code in (httplib.OK, httplib.CREATED):
            return resp.json()
        elif resp.status_code == httplib.UNAUTHORIZED and can_retry:
            self.access_token = self._refresh_access_token()
            return self.post(url, payload, headers, can_retry=False)

        try:
            resp_dict = resp.json()[0]
            log.warn("API error code: %s - %s", resp_dict.get(u'error_code'), resp_dict.get(u'message'))
        except (ValueError, IndexError):
            message = _("Can't parse unexpected response during POST request to Brightcove API!")
            log.exception(message)
            resp_dict = {"message": message}
        return resp_dict 
开发者ID:appsembler,项目名称:xblock-video,代码行数:37,代码来源:brightcove.py

示例11: _PerformCsrfRequestValidation

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def _PerformCsrfRequestValidation(session, environ):
  session_xsrf = session['xsrf']
  client_xsrf = environ.get(_XSRF_TOKEN_HEADER)
  if not client_xsrf:
    Abort(httplib.UNAUTHORIZED, 'Missing client XSRF token.')
  if client_xsrf != session_xsrf:
    # do not log tokens in production
    if common.IsDevMode():
      logging.error('Client XSRF token={0!r}, session XSRF token={1!r}'
                    .format(client_xsrf, session_xsrf))
    Abort(httplib.UNAUTHORIZED,
          'Client XSRF token does not match session XSRF token.') 
开发者ID:googlearchive,项目名称:cloud-playground,代码行数:14,代码来源:middleware.py

示例12: __call__

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def __call__(self, environ, start_response):
    if appids.TWO_COLLABORATING_APP_IDS:
      self._AssertCollaboratingAppIdAccessCheck(environ)

    if environ['PATH_INFO'] in common.CONTROL_PATHS_REQUIRING_TREE:
      if shared.IsHttpReadMethod(environ):
        if not shared.HasProjectReadAccess(environ):
          Abort(httplib.UNAUTHORIZED, 'no project read access to mimic control')
      else:
        if not shared.HasProjectWriteAccess(environ):
          Abort(httplib.UNAUTHORIZED,
                'no project write access to mimic control')
    return self.app(environ, start_response) 
开发者ID:googlearchive,项目名称:cloud-playground,代码行数:15,代码来源:middleware.py

示例13: PerformAccessCheck

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def PerformAccessCheck(self):
    if not shared.HasProjectReadAccess(self.request.environ):
      Abort(httplib.UNAUTHORIZED, 'no project read access') 
开发者ID:googlearchive,项目名称:cloud-playground,代码行数:5,代码来源:playground.py

示例14: download_pdf

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def download_pdf(self, qbbo, item_id):
        if self.session is None:
            raise exceptions.QuickbooksException('No session')

        url = "{0}/company/{1}/{2}/{3}/pdf".format(
            self.api_url, self.company_id, qbbo.lower(), item_id)

        headers = {
            'Content-Type': 'application/pdf',
            'Accept': 'application/pdf, application/json',
            'User-Agent': 'python-quickbooks V3 library'
        }

        response = self.process_request("GET", url, headers=headers)

        if response.status_code != httplib.OK:

            if response.status_code == httplib.UNAUTHORIZED:
                # Note that auth errors have different result structure which can't be parsed by handle_exceptions()
                raise exceptions.AuthorizationException("Application authentication failed", detail=response.text)

            try:
                result = response.json()
            except:
                raise exceptions.QuickbooksException("Error reading json response: {0}".format(response.text), 10000)

            self.handle_exceptions(result["Fault"])
        else:
            return response.content 
开发者ID:ej2,项目名称:python-quickbooks,代码行数:31,代码来源:client.py

示例15: test_missing_credentials

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import UNAUTHORIZED [as 别名]
def test_missing_credentials(self):
        self._enable_basic_auth(self.default_username, self.default_password)
        resp = self.client.get('/')
        self.assertEqual(resp.status_code, httplib.UNAUTHORIZED) 
开发者ID:Jahaja,项目名称:psdash,代码行数:6,代码来源:test_web.py


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