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


Python Response.body方法代码示例

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


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

示例1: make_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def make_response(obj, _content_type='application/json'):
    res = Response(content_type=_content_type)
    if _content_type=="application/json":
        res.body = dumps(obj)
    else:
        res.body = obj
    return res
开发者ID:Kirembu,项目名称:FreePyBX,代码行数:9,代码来源:util.py

示例2: get_err_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [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

示例3: json

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
    def json(self, req):
        resp = Response()
        resp.content_type = 'text/javascript'
        resp.charset = 'utf-8'
        alias = req.params.get('alias')
        url = req.params.get('url')

        path_info = req.path_info.lstrip('/')
        if path_info.startswith('json/stats'):
            if alias:
                c = get_stats(alias)
            else:
                c = Params(error='You must provide an alias !')
        else:
            if url:
                c = self.add(req, url, alias)
            else:
                c = Params(error='You must provide an url !')

        callback =req.params.get('callback')
        if callback:
            callback = str(callback)
            arg = req.params.get('arg')
            if arg:
                resp.body = '%s(%s, %s);' % (callback, json.dumps(arg), json.dumps(c))
            else:
                resp.body = '%s(%s);' % (callback, json.dumps(c))
        else:
            resp.body = json.dumps(c)
        return resp
开发者ID:gawel,项目名称:AuPoil,代码行数:32,代码来源:application.py

示例4: application

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def application(environ, start_response):
    """Determine the user's country based on their IP address."""
    request = Request(environ)
    response = Response(
        status=200,
        cache_control=('no-store, no-cache, must-revalidate, post-check=0, '
                       'pre-check=0, max-age=0'),
        pragma='no-cache',
        expires='02 Jan 2010 00:00:00 GMT',
    )

    client_ip = request.headers.get('HTTP_X_CLUSTER_CLIENT_IP',
                                    request.client_addr)
    geo_data = {
        'country_code': geoip.country_code_by_addr(client_ip),
        'country_name': geoip.country_name_by_addr(client_ip),
    }

    # Users can request either a JavaScript file or a JSON file for the output.
    path = request.path_info_peek()
    if path == 'country.js':
        response.content_type = 'text/javascript'
        response.body = """
            function geoip_country_code() {{ return '{country_code}'; }}
            function geoip_country_name() {{ return '{country_name}'; }}
        """.format(**geo_data)
    elif path == 'country.json':
        response.content_type = 'application/json'
        response.body = json.dumps(geo_data)
    else:
        response.status = 404
        response.content_type = 'application/json'
        response.body = json.dumps({'error': 'Function not supported.'})

    return response(environ, start_response)
开发者ID:Osmose,项目名称:geodude,代码行数:37,代码来源:geodude.py

示例5: handle_request

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
    def handle_request(self, req):
        if (req.method == 'GET'):
            resp = Response(request=req)
            resp.body = 'you send GET method'
	    pprint(req.environ)
	    print req.body
            return resp
        if (req.method == 'POST'):
            CHUNKSIZE = 4096000
            filename = req.environ.get('QUERY_STRING')
            fname=filename.split('=')[1]
            print fname
            #time.sleep(5)
            f = open(fname, "w")
            chunk = req.environ["wsgi.input"].read(CHUNKSIZE)
            # ----------  write files ----------------
            print 'bbbb'
            #print chunk
            count=1
            while chunk:
                f.write(chunk)
                chunk = req.environ["wsgi.input"].read(CHUNKSIZE)
                #print chunk
                print '--------------------'
                count=count+1
                print count
                f.close()
                resp = Response(request=req)
                resp.body = 'you send GET method'
                pprint(req.environ)
                print req.body
                return resp
开发者ID:jonahwu,项目名称:lab,代码行数:34,代码来源:myapp.py

示例6: static

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def static(request):
    response = Response()

    extension = os.path.splitext(request.path_url)[1].replace('.', '')
    mime = settings.mime_types.get(extension, 'text/html')

    file_path = os.path.join(settings.STATIC,
                             request.path_info.replace('/static/', ''))

    try:
        file = open(file_path, 'rb')
        response.body = file.read()
    except Exception:
        try:
            file_path = os.path.join(settings.MEDIA,
                                 request.path_info.replace('/media/', ''))
            file = open(file_path, 'rb')
            response.body = file.read()
        except Exception:
            return view_404(request)
        else:
            response.content_type = mime
    else:
        response.content_type = mime
    return response
开发者ID:AJleksei,项目名称:LigthIt_TZ,代码行数:27,代码来源:views.py

示例7: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
 def __call__(self, environ, start_response):
     req = Request(environ)
     path_info = req.path_info.lstrip('/')
     if path_info.startswith('json'):
         resp = self.json(req)
     elif path_info.startswith('stats'):
         resp = Response()
         alias = [p for p in path_info.split('/')[1:] if p]
         if alias:
             alias = '/'.join(alias)
             resp.body = self.stats.render(c=get_stats(alias))
     elif path_info and path_info != 'new':
         resp = self.redirect(req)
     elif not path_info and self.redirect_url:
         resp = exc.HTTPFound(location=self.redirect_url)
     else:
         resp = Response()
         resp.content_type = 'text/html'
         resp.charset = 'utf-8'
         if req.GET.get('url'):
             # save
             alias = req.GET.get('alias')
             alias = alias and alias or None
             url = req.GET.get('url')
             if url:
                 c = self.add(req, url, alias)
             else:
                 c = Params(error='You must provide an url !')
         else:
             c = Params(url=req.GET.get('post',''))
             c.title = req.params.get('title', '')
         c.plugin = req.params.get('p', False)
         resp.body = self.index.render(c=c)
     return resp(environ, start_response)
开发者ID:gawel,项目名称:AuPoil,代码行数:36,代码来源:application.py

示例8: app

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
 def app(environ, start_response):
     tmpl = '''<DOCTYPE !html>
     <html><body><form method="POST" action="" enctype="multipart/form-data">
     %s
     <input type="submit" id="submit" name="submit" />
     </form></body></html>'''
     req = Request(environ)
     resp = Response()
     if fieldset is None:
         fs = FieldSet(model)
     else:
         fs = fieldset.bind(model)
     if req.method == 'POST':
         if fieldset is None:
             fs = fs.bind(request=req)
         else:
             fs = fs.bind(model=model, request=req)
         if fs.validate():
             fs.sync()
             fs.readonly = True
             resp.body = tmpl % ('<b>OK<b>' + fs.render(),)
         else:
             resp.body = tmpl % fs.render()
     else:
         resp.body = tmpl % fs.render()
     return resp(environ, start_response)
开发者ID:Shu-Ji,项目名称:WebpyAdmin,代码行数:28,代码来源:__init__.py

示例9: GET

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [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

示例10: application

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def application(environ, start_response):
    req = Request(environ)
    response = Response()
    if req.method == 'GET':
        response.body = '<pre>Yeah !</pre>'
    else:
        response.body = '<a href="/plop">Yeah !</a>'
    return response(environ, start_response)
开发者ID:NickCis,项目名称:Okeykoclient,代码行数:10,代码来源:test.py

示例11: app

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def app(environ, start_response):
    req = Request(environ)
    resp = Response(content_type='application/json')
    if req.method in ('GET', 'PATCH'):
        resp.body = json.dumps(dict(id=1, value='value'))
    else:
        resp.body = req.body
    return resp(environ, start_response)
开发者ID:arthru,项目名称:webtest,代码行数:10,代码来源:json_fixt.py

示例12: make_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def make_response(obj, content_type='application/json'):
    res = Response(content_type=content_type)
    if(content_type=="application/json"):
        res.charset = 'utf8'
        res.body = dumps(obj)
    else:
        res.body = obj
    return res
开发者ID:JoneXiong,项目名称:FreePyBX,代码行数:10,代码来源:pymp.py

示例13: get_err_response

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [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

示例14: input_app

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
def input_app(environ, start_response):
    resp = Response()
    req = Request(environ)
    if req.path_info == '/':
        resp.body = '<input name="youyou" type="text" value="" />'
    elif req.path_info == '/submit':
        resp.body = '<input type="submit" value="OK" />'
    else:
        resp.body = ''
    return resp(environ, start_response)
开发者ID:NickCis,项目名称:Okeykoclient,代码行数:12,代码来源:test.py

示例15: __call__

# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import body [as 别名]
 def __call__(self, environ, start_response):
     request = Request(environ)
     response = Response()
     try:
         answer = self.handleRequest(request.body)
         response.body = answer
         response.content_type = "application/mobwrite"
     except Exception, e:
         log.exception("error in request handling")
         response.status = "500 Internal Server Error"
         response.body = str(e)
开发者ID:dineshkummarc,项目名称:Bespin,代码行数:13,代码来源:mobwrite_web.py


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