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


Python Response.status方法代码示例

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


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

示例1: best_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
 def best_response(self, req, statuses, reasons, bodies, server_type,
                   etag=None,jsondata=None):
     """
     :param req: webob.Request object
     :param statuses: list of statuses returned
     :param reasons: list of reasons for each status
     :param bodies: bodies of each response
     :param server_type: type of server the responses came from
     :param etag: etag
     :returns: webob.Response object with the correct status, body, etc. set
     """
     
     resp = Response(request=req)
     
     if len(statuses):
         for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
             hstatuses = \
                 [s for s in statuses if hundred <= s < hundred + 100]
             if len(hstatuses) > len(statuses) / 2:
                 status = max(hstatuses)
                 status_index = statuses.index(status)
                 resp.status = '%s %s' % (status, reasons[status_index]) 
                 resp.body = bodies[status_index]
                 
                 return resp
     
     resp.status = '503 Internal Server Error'
     return jresponse('-1', 'internal server error', req,503)
开发者ID:sun3shines,项目名称:swift-1.7.4,代码行数:30,代码来源:base.py

示例2: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
	def __call__(self, env, start_response):
		res = Response (content_type = 'text/plain', status = 200)
		req = Request (env)
		url = req.path_info
		
		additional_params = dict(req.params)
		additional_params['request'] = req
		additional_params['response'] = res
		additional_params['method'] = req.method
		additional_params['headers'] = req.headers
		
		found = False
		for handler in UrlCallableFunction.request_handlers:
			result = handler.call_if_matches (url, additional_params)
			if result: 
				found = True
				if isinstance (result, str):
					res.text = result
				elif isinstance (result, dict):
					if 'body' in result: res.text = result['body']
					if 'charset' in result: res.charset = result['charset']
					if 'content_type' in result: res.content_type = result['content_type']
					if 'additional_headers' in result: res.headers.update(result['additional_headers'])
					if 'status' in result: res.status = result['status']
				break
		
		if not found:
			res.status = 400
			
		return res (env, start_response)
开发者ID:co-stig,项目名称:trivial-python-web-services,代码行数:32,代码来源:vsws.py

示例3: buildSvInst

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
	def buildSvInst(self,req,id,body=None):
		#启动一个服务后,这个服务才能被调用
		#url Post http://ip:port/v1/sv_id/start
		#body:user_id,sv_inst_id,type
# 		if body['svtype']==utils.SYN:
		res =Response(None,200)
# 		sv_inst_id = body['sv_inst_id']
		sv_inst_id = str(body.get('sv_inst_id'))
		if not sv_inst_id:
			Logger.debug("The args 'sv_inst_id' can not be null!")
			res.status=505
		sv_id = id
		
		user_id = body.get('user_id')
		if not user_id:
			Logger.debug("The args 'user_id' can not be null!")
			res.status=505
		svtype = body.get('svtype')
		if svtype is None:
			svtype = ServiceCtrlBlock.UNDAEM
		if svtype not in ServiceCtrlBlock.TYPES:
			res.status=412
		try:
			self.svinstanc_mgr.build_svinstance(sv_inst_id, user_id, sv_id, svtype)
			self.svinstanc_mgr.start(sv_inst_id)
		except Exception,e:
			Logger.error(e.msg)
			res.status=505
			res.body=e.msg
开发者ID:kinglongchen,项目名称:alligatorproxy,代码行数:31,代码来源:controllers.py

示例4: best_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def best_response(self, req, statuses, reasons, bodies, server_type,
                      etag=None):
        """
        Given a list of responses from several servers, choose the best to
        return to the API.

        :param req: webob.Request object
        :param statuses: list of statuses returned
        :param reasons: list of reasons for each status
        :param bodies: bodies of each response
        :param server_type: type of server the responses came from
        :param etag: etag
        :returns: webob.Response object with the correct status, body, etc. set
        """
        resp = Response(request=req)
        if len(statuses):
            for hundred in (HTTP_OK, HTTP_MULTIPLE_CHOICES, HTTP_BAD_REQUEST):
                hstatuses = \
                    [s for s in statuses if hundred <= s < hundred + 100]
                if len(hstatuses) > len(statuses) / 2:
                    status = max(hstatuses)
                    status_index = statuses.index(status)
                    resp.status = '%s %s' % (status, reasons[status_index])
                    resp.body = bodies[status_index]
                    resp.content_type = 'text/html'
                    if etag:
                        resp.headers['etag'] = etag.strip('"')
                    return resp
        self.app.logger.error(_('%(type)s returning 503 for %(statuses)s'),
                              {'type': server_type, 'statuses': statuses})
        resp.status = '503 Internal Server Error'
        return resp
开发者ID:missall,项目名称:swift,代码行数:34,代码来源:base.py

示例5: GET

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def GET(self, req, *parts):
        """
        Handle GET Container (List Objects) request
        """

        env = self._fresh_env(req)
        env['SERVER_PORT'] = self.conf.get('volume_endpoint_port')
        env['SCRIPT_NAME'] = '/v1'
        env['HTTP_HOST'] = '%s:%s' % \
            (self.conf.get('volume_endpoint_host'),
             self.conf.get('volume_endpoint_port'))
        env['CONTENT_LENGTH'] = 0

        status, headers, body, status_code = access_resource(env, 'GET',
            '/v1' + self.os_path, True, None, None)

        if status:
            data = json.loads(body).get('volume')

            body = {}
            body['id'] = '/'.join([self.tenant_id, 'Volume', parts[0]])
            match_up(body, data, 'name', 'display_name')
            match_up(body, data, 'description', 'display_description')
            match_up(body, data, 'created', 'created_at')
            match_up(body, data, 'capacity', 'size')
            body['capacity'] = int(body['capacity']) * 1000000
            body['state'] = map_volume_state(data['status'])
            body['bootable'] = 'false'
            body['type'] = 'http://schemas.dmtf.org/cimi/1/mapped'

            operations = []
            operations.append(self._create_op('delete',
                '/'.join([self.tenant_id, 'volume',
                          parts[0]])))
            body['operations'] = operations


            if self.res_content_type == 'application/xml':
                response_data = {'Volume': body}
            else:
                body['resourceURI'] = '/'.join([self.uri_prefix,
                                                self.entity_uri])
                response_data = body

            new_content = make_response_data(response_data,
                                             self.res_content_type,
                                             self.metadata,
                                             self.uri_prefix)
            resp = Response()
            self._fixup_cimi_header(resp)
            resp.headers['Content-Type'] = self.res_content_type
            resp.status = status_code
            resp.body = new_content
            return resp
        else:
            resp = Response()
            resp.status = status_code
            resp.body = 'Volume could not be found'
            return resp
开发者ID:chrrrles,项目名称:cimi,代码行数:61,代码来源:volume.py

示例6: get_err_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
def get_err_response(code):
    """
    Given an HTTP response code, create a properly formatted error response

    :param code: error code
    :returns: webob.response object
    """

    error_table = {
        'AccessDenied':
            (403, 'Access denied'),
        'ContainerAlreadyExists':
            (409, 'The requested Container alredy exists'),
        'ContainerNotEmpty':
            (409, 'The container you tried to delete is not empty'),
        'InvalidArgument':
            (400, 'Invalid Argument'),
        'InvalidContainerName':
            (400, 'The specified container is not valid'),
        'InvalidURI':
            (400, 'Required header or the URI formation is not correct.'),
        'InvalidHeader':
            (400, 'CDMI required headers are not present in the request'),
        'InvalidContent':
            (400, 'CDMI request body is not in a correct format'),
        'BadRequest':
            (400, 'Bad request'),
        'NotContainer':
            (400, 'Requested resource is not a CDMI container'),
        'BadRequestPath':
            (400, 'Request url does not confirm with CDMI specification'),
        'InconsistantState':
            (400, 'The storage state is inconsistant.'),
        'VersionNotSupported':
            (400, 'Requested cdmi version is not supported.'),
        'InvalidRange':
            (400, 'Requested Range is not valid.'),
        'InvalidBody':
            (400, 'MIME message or the request body can not be parsed.'),
        'NoSuchContainer':
            (404, 'The specified container does not exist'),
        'ResourceIsNotObject':
            (404, 'The specified resource is not data object'),
        'NoParentContainer':
            (404, 'The parent container does not exist'),
        'NoSuchKey':
            (404, 'The resource you requested does not exist'),
        'Conflict':
            (409, 'The requested name already exists as a different type')}

    resp = Response()
    if error_table.get(code):
        resp.status = error_table[code][0]
        resp.body = error_table[code][1]
    else:
        resp.status = 400
        resp.body = 'Unknown Error'
    return resp
开发者ID:IntelLabsEurope,项目名称:CDMI-OS,代码行数:60,代码来源:cdmiutils.py

示例7: GET

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def GET(self, req, *parts):
        """
        Handle GET machine request
        """

        env = self._fresh_env(req)
        env['SERVER_PORT'] = self.conf.get('volume_endpoint_port')
        env['SCRIPT_NAME'] = '/v1'
        env['HTTP_HOST'] = '%s:%s'%(self.conf.get('volume_endpoint_host'),
                                    self.conf.get('volume_endpoint_port'))

        status, headers, body = access_resource(env, 'GET',
                                               '/v1/' + self.os_path,
                                               True, None)
        if status:
            content = json.loads(body)
            body = {}
            body['resourceURI'] = '/'.join([self.uri_prefix.rstrip('/'),
                                            self.entity_uri])
            body['id'] = '/'.join([self.tenant_id, self.entity_uri])
            body['volumes'] = []
            volumes = content.get('volumes', [])
            for volume in volumes:
                entry = {}
                entry['resourceURI'] = '/'.join([self.uri_prefix.rstrip('/'),
                                                 'Volume'])
                entry['id'] = '/'.join([self.tenant_id, 'Volume',
                                        volume['id']])

                body['volumes'].append(entry)

            body['count'] = len(body['volumes'])
            if self.res_content_type == 'application/xml':
                response_data = {'Collection': body}
            else:
                response_data = body

            new_content = make_response_data(response_data,
                                             self.res_content_type,
                                             self.metadata,
                                             self.uri_prefix)
            resp = Response()
            self._fixup_cimi_header(resp)
            resp.headers['Content-Type'] = self.res_content_type
            resp.status = 200
            resp.body = new_content

            return resp
        else:
            resp = Response()
            resp.status = 404
            return resp
开发者ID:zhexuan,项目名称:cimi,代码行数:54,代码来源:volume.py

示例8: fake_response2

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
def fake_response2():
    global _CPT
    if _CPT == 0:
        r = Response()
        r.status = '400 Bad Request'
        r.body = str(ERROR_NO_EMAIL_ADDRESS)
    elif _CPT == 1:
        r = Response()
        r.status = '400 Bad Request'
        r.body = str(ERROR_INVALID_RESET_CODE)

    _CPT += 1
    return r
开发者ID:irslambouf,项目名称:SyncServer,代码行数:15,代码来源:test_mozilla_sreg.py

示例9: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
 def __call__(self, env, start_response):
     print "enter call of app Hello, s_r=%s" % start_response
     req = Request(env)    
     res = Response()
     res.status = "200 OK"
     res.content_type = "text/json"
     if not check_user(self.conf, req.GET):
         res.status = "413 auth failed!"
         res.body = json.dumps({'user': req.GET.get('user', None),                  
                                'passwd': req.GET.get('passwd', None)})
         return res(env, start_response)
     res.body = json.dumps({"hello": "world"})
     return res(env, start_response)
开发者ID:Bougou,项目名称:study,代码行数:15,代码来源:test_pd.py

示例10: handle_sub_verification

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def handle_sub_verification(self, req):
        res = Response()
        mode = req.GET.get('hub.mode', None)
        topic = req.GET.get('hub.topic', None)

        if self._validate_sub_request(req):
            log.info("Got valid '%s' req for '%s'" % (mode, topic))
            res.status = 200
            res.body = req.GET['hub.challenge']
            return res
        else:
            log.warn("Got invalid '%s' req for '%s'" % (mode, topic))
            res.status = 404
        return res
开发者ID:jab,项目名称:melkman,代码行数:16,代码来源:pubsubhubbub.py

示例11: identify

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def identify(self, environ):
        user = {}
        request = Request(environ)

        log.debug("Request path: %s" % request.path)
        log.debug(request)
        log.debug(environ)

        # Logout user
        if request.path == self.logout_url:
            response = Response()

            for a, v in self.forget(environ, {}):
                response.headers.add(a, v)

            response.status = 302
            response.location = url_for(controller="user", action="logged_out")
            environ["repoze.who.application"] = response

            return {}

        # Login user, if there's shibboleth headers and path is shiblogin
        if self.is_shib_session(environ) and request.path == self.login_url:
            log.debug("Trying to authenticate with shibboleth")
            log.debug("environ AUTH TYPE: %s", environ.get("AUTH_TYPE", "None"))
            log.debug("environ Shib-Session-ID: %s", environ.get(self.session, "None"))
            log.debug("environ mail: %s", environ.get(self.mail, "None"))
            log.debug("environ cn: %s", environ.get(self.name, "None"))

            user = self._get_or_create_user(environ)

            if not user:
                log.debug("User is None")
                return {}

            response = Response()
            response.status = 302
            response.location = url_for(controller="user", action="dashboard")
            environ["repoze.who.application"] = response

            return {
                "repoze.who.plugins.openid.userid": user.openid,
                "login": user.email,
                "password": "",
                "email": user.email,
                "fullname": user.email,
            }

        return {}
开发者ID:harripal,项目名称:ckanext-shibboleth,代码行数:51,代码来源:plugin.py

示例12: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
    def __call__(self, environ, start_response):
        self.requests += 1
        req = Request(environ)
        res = Response()

        filename = req.path_info.lstrip('/')
        filename = os.path.abspath(os.path.join(self.www_dir, filename))

        if filename.startswith(self.www_dir) and os.path.isfile(filename):
            res.status = 200
            res.body = open(filename).read()
        else:
            res.status = 404

        return res(environ, start_response)
开发者ID:jab,项目名称:melkman,代码行数:17,代码来源:helpers.py

示例13: get_err_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
def get_err_response(code):
    """
    Given an HTTP response code, create a properly formatted xml error response

    :param code: error code
    :returns: webob.response object
    """
    error_table = {
        'AccessDenied':
            (HTTP_FORBIDDEN, 'Access denied'),
        'BucketAlreadyExists':
            (HTTP_CONFLICT, 'The requested bucket name is not available'),
        'BucketNotEmpty':
            (HTTP_CONFLICT, 'The bucket you tried to delete is not empty'),
        'InvalidArgument':
            (HTTP_BAD_REQUEST, 'Invalid Argument'),
        'InvalidBucketName':
            (HTTP_BAD_REQUEST, 'The specified bucket is not valid'),
        'InvalidURI':
            (HTTP_BAD_REQUEST, 'Could not parse the specified URI'),
        'NoSuchBucket':
            (HTTP_NOT_FOUND, 'The specified bucket does not exist'),
        'SignatureDoesNotMatch':
            (HTTP_FORBIDDEN, 'The calculated request signature does not '\
            'match your provided one'),
        'NoSuchKey':
            (HTTP_NOT_FOUND, 'The resource you requested does not exist')}

    resp = Response(content_type='text/xml')
    resp.status = error_table[code][0]
    resp.body = error_table[code][1]
    resp.body = '<?xml version="1.0" encoding="UTF-8"?>\r\n<Error>\r\n  ' \
                '<Code>%s</Code>\r\n  <Message>%s</Message>\r\n</Error>\r\n' \
                 % (code, error_table[code][1])
    return resp
开发者ID:Nupta,项目名称:swift,代码行数:37,代码来源:swift3.py

示例14: get_err_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
def get_err_response(code):
    """
    Given an HTTP response code, create a properly formatted error response

    :param code: error code
    :returns: webob.response object
    """

    error_table = {
        'AccessDenied':
            (403, 'Access denied'),
        'BadRequest':
            (400, 'Bad request'),
        'MalformedBody':
            (400, 'Request body can not be parsed, malformed request body'),
        'NotFound':
            (404, 'Resource was not found'),
        'NotImplemented':
            (501, 'Not implemented'),
        'TestRequest':
            (200, 'Test request'),
        'Conflict':
            (409, 'The requested name already exists as a different type')}

    resp = Response()
    resp.status = error_table[code][0]
    resp.body = error_table[code][1]
    return resp
开发者ID:chrrrles,项目名称:cimi,代码行数:30,代码来源:cimiutils.py

示例15: challenge

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import status [as 别名]
 def challenge(self, environ, status, app_headers, forget_headers):
     # redirect to login_form
     res = Response()
     res.status = 401
     res.unicode_body = render_snippet('not_authorized.html')
     #res.location = '/data/not_authorized' #self.login_form_url+"?%s=%s" %(self.came_from_field, request.url)
     return res
开发者ID:diabulos,项目名称:ckanext-dgu,代码行数:9,代码来源:drupal_repoze_plugin.py


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