本文整理汇总了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
示例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
示例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
示例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)
示例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
示例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
示例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)
示例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)
示例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
示例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)
示例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)
示例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
示例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
示例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)
示例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)