本文整理汇总了Python中webob.response.Response.body方法的典型用法代码示例。如果您正苦于以下问题:Python Response.body方法的具体用法?Python Response.body怎么用?Python Response.body使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.response.Response
的用法示例。
在下文中一共展示了Response.body方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: import_resources
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def import_resources(self, request, _suffix=''):
"""
Import resources into the recommender.
"""
response = Response()
response.headers['Content-Type'] = 'application/json'
if not self.get_user_is_staff():
response.status = 403
response.body = json.dumps({'error': self.ugettext('Only staff can import resources')})
tracker.emit('import_resources', {'Status': 'NOT_A_STAFF'})
return response
# Check invalid file types
file_types = {
'json': {
'extension': [".json"],
'mimetypes': ['application/json', 'text/json', 'text/x-json']
}
}
file_type_error_msg = self.ugettext('Please submit the JSON file obtained with the download resources button')
result = self._check_upload_file(
request, file_types, file_type_error_msg, 'import_resources', 31457280
)
if isinstance(result, Response):
return result
try:
data = json.load(request.POST['file'].file)
self.flagged_accum_resources = data['flagged_accum_resources']
self.endorsed_recommendation_reasons = data['endorsed_recommendation_reasons']
self.endorsed_recommendation_ids = data['endorsed_recommendation_ids']
if 'removed_recommendations' in data:
self.removed_recommendations = data_structure_upgrade(data['removed_recommendations'])
data['removed_recommendations'] = self.removed_recommendations
self.recommendations = data_structure_upgrade(data['recommendations'])
data['recommendations'] = self.recommendations
tracker.emit('import_resources', {'Status': 'SUCCESS', 'data': data})
response.body = json.dumps(data, sort_keys=True)
response.status = 200
return response
except (ValueError, KeyError):
response.status = 415
response.body = json.dumps(
{'error': self.ugettext('Please submit the JSON file obtained with the download resources button')}
)
tracker.emit('import_resources', {'Status': 'FILE_FORMAT_ERROR'})
return response
except IOError:
return self._raise_pyfs_error('import_resources')
示例2: download
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def download(path, filename):
"""
Возвращает клиенту файл.
Deprecated.
"""
res = Response(content_type='text/javascript', app_iter=None)
try:
res.body = open(path + filename, 'r').read()
except:
res.body = 'alert("Scenario file not found!");'
logger.debug("[MultiEngineXBlock]: " + "Scenario file not found!")
return res
示例3: test_md5_etag
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_md5_etag():
res = Response()
res.body = b"""\
In A.D. 2101
War was beginning.
Captain: What happen ?
Mechanic: Somebody set up us the bomb.
Operator: We get signal.
Captain: What !
Operator: Main screen turn on.
Captain: It's You !!
Cats: How are you gentlemen !!
Cats: All your base are belong to us.
Cats: You are on the way to destruction.
Captain: What you say !!
Cats: You have no chance to survive make your time.
Cats: HA HA HA HA ....
Captain: Take off every 'zig' !!
Captain: You know what you doing.
Captain: Move 'zig'.
Captain: For great justice."""
res.md5_etag()
assert res.etag
assert '\n' not in res.etag
assert res.etag == 'pN8sSTUrEaPRzmurGptqmw'
assert res.content_md5 is None
示例4: _check_upload_file
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def _check_upload_file(self, request, file_types, file_type_error_msg, event, file_size_threshold):
"""
Check the type and size of uploaded file. If the file type is
unexpected or the size exceeds the threshold, log the error and return
to browser, otherwise, return None.
"""
# Check invalid file types
file_type_error = False
file_type = [ft for ft in file_types
if any(str(request.POST['file'].file).lower().endswith(ext)
for ext in file_types[ft]['extension'])]
# Check extension
if not file_type:
file_type_error = True
else:
file_type = file_type[0]
# Check mimetypes
if request.POST['file'].file.content_type not in file_types[file_type]['mimetypes']:
file_type_error = True
else:
if 'magic' in file_types[file_type]:
# Check magic number
headers = file_types[file_type]['magic']
if request.POST['file'].file.read(len(headers[0]) / 2).encode('hex') not in headers:
file_type_error = True
request.POST['file'].file.seek(0)
if file_type_error:
response = Response()
tracker.emit(event, {'uploadedFileName': 'FILE_TYPE_ERROR'})
response.status = 415
response.body = json.dumps({'error': file_type_error_msg})
response.headers['Content-Type'] = 'application/json'
return response
# Check whether file size exceeds threshold (30MB)
if request.POST['file'].file.size > file_size_threshold:
response = Response()
tracker.emit(event, {'uploadedFileName': 'FILE_SIZE_ERROR'})
response.status = 413
response.body = json.dumps({'error': self.ugettext('Size of uploaded file exceeds threshold')})
response.headers['Content-Type'] = 'application/json'
return response
return file_type
示例5: test_body_file_del
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_body_file_del():
res = Response()
res.body = b'123'
eq_(res.content_length, 3)
eq_(res.app_iter, [b'123'])
del res.body_file
eq_(res.body, b'')
eq_(res.content_length, 0)
示例6: test_body_file_del
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_body_file_del():
res = Response()
res.body = b'123'
assert res.content_length == 3
assert res.app_iter == [b'123']
del res.body_file
assert res.body == b''
assert res.content_length == 0
示例7: static
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def static(self, request, suffix=''):
filename = os.path.join( os.path.dirname(__file__), 'static', suffix )
mime = mimetypes.guess_type(filename)[0]
content = None
try:
content = open(filename,'rb').read()
except Exception as e:
print e
return Response(status=404)
else:
res = Response(content_type=mime)
if mime.startswith('text'):
res.body = content.format(self=self)
else:
res.body = content
return res
示例8: test_body_file_del
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_body_file_del():
res = Response()
res.body = b"123"
eq_(res.content_length, 3)
eq_(res.app_iter, [b"123"])
del res.body_file
eq_(res.body, b"")
eq_(res.content_length, 0)
示例9: upload_screenshot
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def upload_screenshot(self, request, _suffix=''): # pylint: disable=unused-argument
"""
Upload a screenshot for an entry of resource as a preview (typically to S3 or filesystem).
Args:
request: HTTP POST request
request.POST['file'].file: the file to be uploaded
Returns:
response: HTTP response
response.body (response.responseText): name of the uploaded file
We validate that this is a valid JPG, GIF, or PNG by checking magic number, mimetype,
and extension all correspond. We also limit to 30MB. We save the file under its MD5
hash to (1) avoid name conflicts, (2) avoid race conditions and (3) save space.
"""
# Check invalid file types
image_types = {
'jpeg': {
'extension': [".jpeg", ".jpg"],
'mimetypes': ['image/jpeg', 'image/pjpeg'],
'magic': ["ffd8"]
},
'png': {
'extension': [".png"],
'mimetypes': ['image/png'],
'magic': ["89504e470d0a1a0a"]
},
'gif': {
'extension': [".gif"],
'mimetypes': ['image/gif'],
'magic': ["474946383961", "474946383761"]
}
}
file_type_error_msg = 'Please upload an image in GIF/JPG/PNG'
result = self._check_upload_file(
request, image_types, file_type_error_msg, 'upload_screenshot', 31457280
)
if isinstance(result, Response):
return result
try:
content = request.POST['file'].file.read()
file_id = hashlib.md5(content).hexdigest()
file_name = (file_id + '.' + result)
fhwrite = self.fs.open(file_name, "wb")
fhwrite.write(content)
fhwrite.close()
except IOError:
return self._raise_pyfs_error('upload_screenshot')
response = Response()
response.body = json.dumps({'file_name': str("fs://" + file_name)})
response.headers['Content-Type'] = 'application/json'
tracker.emit('upload_screenshot',
{'uploadedFileName': response.body})
response.status = 200
return response
示例10: test_decode_content_with_deflate
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_decode_content_with_deflate():
res = Response()
body = b'Hey Hey Hey'
# Simulate inflate by chopping the headers off
# the gzip encoded data
res.body = zlib.compress(body)[2:-4]
res.content_encoding = 'deflate'
res.decode_content()
assert res.body == body
assert res.content_encoding is None
示例11: test_decode_content_with_deflate
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_decode_content_with_deflate():
res = Response()
body = b"Hey Hey Hey"
# Simulate inflate by chopping the headers off
# the gzip encoded data
res.body = zlib.compress(body)[2:-4]
res.content_encoding = "deflate"
res.decode_content()
eq_(res.body, body)
eq_(res.content_encoding, None)
示例12: test_unicode_body
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_unicode_body():
res = Response()
res.charset = "utf-8"
bbody = b"La Pe\xc3\xb1a" # binary string
ubody = text_(bbody, "utf-8") # unicode string
res.body = bbody
assert res.unicode_body == ubody
res.ubody = ubody
assert res.body == bbody
del res.ubody
assert res.body == b""
示例13: test_unicode_body
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_unicode_body():
res = Response()
res.charset = 'utf-8'
bbody = b'La Pe\xc3\xb1a' # binary string
ubody = text_(bbody, 'utf-8') # unicode string
res.body = bbody
eq_(res.unicode_body, ubody)
res.ubody = ubody
eq_(res.body, bbody)
del res.ubody
eq_(res.body, b'')
示例14: test_unicode_body
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_unicode_body():
res = Response()
res.charset = "utf-8"
bbody = b"La Pe\xc3\xb1a" # binary string
ubody = text_(bbody, "utf-8") # unicode string
res.body = bbody
eq_(res.unicode_body, ubody)
res.ubody = ubody
eq_(res.body, bbody)
del res.ubody
eq_(res.body, b"")
示例15: test_unicode_body
# 需要导入模块: from webob.response import Response [as 别名]
# 或者: from webob.response.Response import body [as 别名]
def test_unicode_body():
res = Response()
res.charset = 'utf-8'
bbody = b'La Pe\xc3\xb1a' # binary string
ubody = text_(bbody, 'utf-8') # unicode string
res.body = bbody
assert res.unicode_body == ubody
res.ubody = ubody
assert res.body == bbody
del res.ubody
assert res.body == b''