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


Python httplib.FORBIDDEN属性代码示例

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


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

示例1: HandleRequest

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def HandleRequest(self, request):
    """Hook that allows the DevProcess a chance to respond to requests.

    This hook is invoked just before normal request dispatch occurs in
    dev_appserver.py.

    Args:
      request: The request to be handled.

    Returns:
      bool: Indicates whether the request was handled here.  If False, normal
        request handling should proceed.
    """
    if self.IsBackendInstance() and not self.started:
      if request.path != '/_ah/start':
        request.send_response(httplib.FORBIDDEN,
                              'Waiting for start request to finish.')
        return True


    return False 
开发者ID:elsigh,项目名称:browserscope,代码行数:23,代码来源:dev_appserver_multiprocess.py

示例2: create_user

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def create_user():
    if not settings.load()['config'].get('allow_account_creation', False):
        return JSONResponse(status=httplib.FORBIDDEN)

    """ This API route is used by the create new account template to add a new user into Mongo """
    if isinstance(request.json, dict):
        args = request.json
        if args.get('username') and args.get('password'):
            try:
                user = users.create_user(args['username'], args['password'], args.get('email'), args.get('full_name'))
            except users.PasswordPolicyError as error:
                regex, rules = error.args
                return JSONResponse({'violation': {'regex': regex, 'rules': rules}}, httplib.BAD_REQUEST)

            if user is not None:
                response = Response(status=httplib.CREATED)
                response.set_cookie('user-token', user.generate_token(), max_age=datetime.timedelta(days=7))
                return response
            else:
                return JSONResponse({'message': 'Username already exists!'}, status=httplib.BAD_REQUEST)

    return JSONResponse({'message': 'Username, email and password are required'}, status=httplib.BAD_REQUEST) 
开发者ID:mitre,项目名称:cascade-server,代码行数:24,代码来源:api.py

示例3: __init__

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def __init__(self, namespace, access_key):
    if not namespace:
      Abort(httplib.FORBIDDEN, 'Missing namespace')
    if not access_key:
      Abort(httplib.FORBIDDEN, 'Missing access key')
    super(ZipUrlFetchTree, self).__init__(namespace, access_key)
    self.namespace = namespace
    self.access_key = access_key

    path_info = '{}/zip'.format(common.CONTROL_PREFIX)
    query_params = '{}={}&use_basepath=false'.format(
      common.config.PROJECT_ID_QUERY_PARAM, namespace)
    playground_hostname = (settings.PLAYGROUND_USER_CONTENT_HOST or
                           settings.PLAYGROUND_HOSTS[0])
    url = 'https://{}{}?{}'.format(playground_hostname, path_info, query_params)

    result = shared.Fetch(access_key, url, method='GET', deadline=30, retries=3)
    buf = cStringIO.StringIO(result.content)
    self._zipfile = zipfile.ZipFile(buf) 
开发者ID:googlearchive,项目名称:cloud-playground,代码行数:21,代码来源:zip_urlfetch_tree.py

示例4: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def get(self, host_id):

    logging.info('Retrieving Exemption for host %s', host_id)

    # This request should only be available to admins or users who have (at
    # least at one time) had control of the host.
    if not (self.user.is_admin or
            model_utils.IsHostAssociatedWithUser(self.host, self.user)):
      logging.warning(
          'User %s is not authorized to access Exemption for host %s',
          self.user.nickname, host_id)
      self.abort(
          httplib.FORBIDDEN,
          explanation='Host not associated with user %s' % self.user.nickname)

    if self.exm is None:
      self.abort(httplib.NOT_FOUND, explanation='Exemption not found')

    self.respond_json(self.exm) 
开发者ID:google,项目名称:upvote,代码行数:21,代码来源:exemptions.py

示例5: insert_role

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def insert_role(self, name=_ROLE_NAME, customer_id='my_customer'):
    """Creates and inserts a new GSuite Admin Role.

    Args:
      name: str, the name of the new GSuite Admin Role.
      customer_id: str, the G Suite customer ID to insert the role into.

    Returns:
      A dictionary object representing the new GSuite Admin Role.
          https://developers.google.com/admin-sdk/directory/v1/reference/roles

    Raises:
      AlreadyExistsError: when the role with the provided name already exists.
      ForbiddenError: when authorization fails.
      InsertionError: when creation fails (e.g. failed to authenticate, improper
          scopes, etc).
    """
    try:
      return self._client.roles().insert(
          customer=customer_id,
          body={
              'roleName': name,
              'rolePrivileges': _ROLE_PRIVILEGES,
              'roleDescription': _ROLE_DESCRIPTION,
              'isSystemRole': False,
              'isSuperAdminRole': False,
          },
      ).execute()
    except errors.HttpError as err:
      status = err.resp.status

      if (status == http_status.CONFLICT or
          status == http_status.INTERNAL_SERVER_ERROR):
        raise AlreadyExistsError(
            'role with name {!r} already exists'.format(name))

      if status == http_status.FORBIDDEN:
        raise ForbiddenError(_FORBIDDEN_ERROR_MSG)

      logging.error(_INSERT_ROLE_ERROR_MSG, name, err)
      raise InsertionError(_INSERT_ROLE_ERROR_MSG % (name, err)) 
开发者ID:google,项目名称:loaner,代码行数:43,代码来源:directory.py

示例6: test_wrong_domain

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_wrong_domain(self):
    current_domains = constants.APP_DOMAINS
    def _reset_app_domain():
      constants.APP_DOMAINS = current_domains
    self.addCleanup(_reset_app_domain)
    constants.APP_DOMAINS = ['not-example.com']
    self.testbed.setup_env(
        user_email='user@example.com',
        user_id='1',
        user_is_admin='0',
        overwrite=True)

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

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

示例7: get

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [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: test_should_include_project_id_in_error_text_when_needed

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_should_include_project_id_in_error_text_when_needed(self):
        resp = sc_messages.AllocateQuotaResponse(
            allocateErrors = [
                sc_messages.QuotaError(
                    code=sc_messages.QuotaError.CodeValueValuesEnum.PROJECT_DELETED)
            ]
        )
        code, got = quota_request.convert_response(resp, self.PROJECT_ID)
        want = u'Project %s has been deleted' % (self.PROJECT_ID,)
        expect(code).to(equal(httplib.FORBIDDEN))
        expect(got).to(equal(want)) 
开发者ID:cloudendpoints,项目名称:endpoints-management-python,代码行数:13,代码来源:test_quota_request.py

示例9: test_should_include_project_id_in_error_text_when_needed

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_should_include_project_id_in_error_text_when_needed(self):
        resp = sc_messages.CheckResponse(
            checkErrors = [
                sc_messages.CheckError(
                    code=sc_messages.CheckError.CodeValueValuesEnum.PROJECT_DELETED)
            ]
        )
        code, got, _ = check_request.convert_response(resp, self.PROJECT_ID)
        want = u'Project %s has been deleted' % (self.PROJECT_ID,)
        expect(code).to(equal(httplib.FORBIDDEN))
        expect(got).to(equal(want)) 
开发者ID:cloudendpoints,项目名称:endpoints-management-python,代码行数:13,代码来源:test_check_request.py

示例10: test_should_include_detail_in_error_text_when_needed

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_should_include_detail_in_error_text_when_needed(self):
        detail = u'details, details, details'
        resp = sc_messages.CheckResponse(
            checkErrors = [
                sc_messages.CheckError(
                    code=sc_messages.CheckError.CodeValueValuesEnum.IP_ADDRESS_BLOCKED,
                    detail=detail)
            ]
        )
        code, got, _ = check_request.convert_response(resp, self.PROJECT_ID)
        expect(code).to(equal(httplib.FORBIDDEN))
        expect(got).to(equal(detail)) 
开发者ID:cloudendpoints,项目名称:endpoints-management-python,代码行数:14,代码来源:test_check_request.py

示例11: test_auth_failure

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_auth_failure(self):
    self.response.status_code = httplib.FORBIDDEN
    with self.assertRaises(net.AuthError):
      gerrit.fetch_json('localhost', 'a') 
开发者ID:luci,项目名称:luci-py,代码行数:6,代码来源:gerrit_test.py

示例12: test_get_config_one_forbidden

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def test_get_config_one_forbidden(self):
    self.mock(acl, 'can_read_config_sets', mock.Mock(return_value={
      'services/x': False,
    }))
    with self.call_should_fail(httplib.FORBIDDEN):
      req = {
        'config_set': 'services/x',
      }
      self.call_api('get_config_sets', req) 
开发者ID:luci,项目名称:luci-py,代码行数:11,代码来源:api_test.py

示例13: remove_config

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def remove_config(self, data_id, group, timeout=None):
        data_id, group = process_common_config_params(data_id, group)
        logger.info(
            "[remove] data_id:%s, group:%s, namespace:%s, timeout:%s" % (data_id, group, self.namespace, timeout))

        params = {
            "dataId": data_id,
            "group": group,
        }
        if self.namespace:
            params["tenant"] = self.namespace

        try:
            resp = self._do_sync_req("/nacos/v1/cs/configs", None, None, params,
                                     timeout or self.default_timeout, "DELETE")
            c = resp.read()
            logger.info("[remove] remove group:%s, data_id:%s, server response:%s" % (
                group, data_id, c))
            return c == b"true"
        except HTTPError as e:
            if e.code == HTTPStatus.FORBIDDEN:
                logger.error(
                    "[remove] no right for namespace:%s, group:%s, data_id:%s" % (self.namespace, group, data_id))
                raise NacosException("Insufficient privilege.")
            else:
                logger.error("[remove] error code [:%s] for namespace:%s, group:%s, data_id:%s" % (
                    e.code, self.namespace, group, data_id))
                raise NacosException("Request Error, code is %s" % e.code)
        except Exception as e:
            logger.exception("[remove] exception %s occur" % str(e))
            raise 
开发者ID:nacos-group,项目名称:nacos-sdk-python,代码行数:33,代码来源:client.py

示例14: publish_config

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def publish_config(self, data_id, group, content, timeout=None):
        if content is None:
            raise NacosException("Can not publish none content, use remove instead.")

        data_id, group = process_common_config_params(data_id, group)
        if type(content) == bytes:
            content = content.decode("UTF-8")

        logger.info("[publish] data_id:%s, group:%s, namespace:%s, content:%s, timeout:%s" % (
            data_id, group, self.namespace, truncate(content), timeout))

        params = {
            "dataId": data_id,
            "group": group,
            "content": content.encode("UTF-8"),
        }

        if self.namespace:
            params["tenant"] = self.namespace

        try:
            resp = self._do_sync_req("/nacos/v1/cs/configs", None, None, params,
                                     timeout or self.default_timeout, "POST")
            c = resp.read()
            logger.info("[publish] publish content, group:%s, data_id:%s, server response:%s" % (
                group, data_id, c))
            return c == b"true"
        except HTTPError as e:
            if e.code == HTTPStatus.FORBIDDEN:
                raise NacosException("Insufficient privilege.")
            else:
                raise NacosException("Request Error, code is %s" % e.code)
        except Exception as e:
            logger.exception("[publish] exception %s occur" % str(e))
            raise 
开发者ID:nacos-group,项目名称:nacos-sdk-python,代码行数:37,代码来源:client.py

示例15: add_naming_instance

# 需要导入模块: import httplib [as 别名]
# 或者: from httplib import FORBIDDEN [as 别名]
def add_naming_instance(self, service_name, ip, port, cluster_name=None, weight=1.0, metadata=None,
                            enable=True, healthy=True):
        logger.info("[add-naming-instance] ip:%s, port:%s, service_name:%s, namespace:%s" % (
            ip, port, service_name, self.namespace))

        params = {
            "ip": ip,
            "port": port,
            "serviceName": service_name,
            "weight": weight,
            "enable": enable,
            "healthy": healthy,
            "metadata": metadata,
            "clusterName": cluster_name
        }

        if self.namespace:
            params["namespaceId"] = self.namespace

        try:
            resp = self._do_sync_req("/nacos/v1/ns/instance", None, None, params, self.default_timeout, "POST")
            c = resp.read()
            logger.info("[add-naming-instance] ip:%s, port:%s, service_name:%s, namespace:%s, server response:%s" % (
                ip, port, service_name, self.namespace, c))
            return c == b"ok"
        except HTTPError as e:
            if e.code == HTTPStatus.FORBIDDEN:
                raise NacosException("Insufficient privilege.")
            else:
                raise NacosException("Request Error, code is %s" % e.code)
        except Exception as e:
            logger.exception("[add-naming-instance] exception %s occur" % str(e))
            raise 
开发者ID:nacos-group,项目名称:nacos-sdk-python,代码行数:35,代码来源:client.py


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