本文整理汇总了Python中webob.Response.content_length方法的典型用法代码示例。如果您正苦于以下问题:Python Response.content_length方法的具体用法?Python Response.content_length怎么用?Python Response.content_length使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类webob.Response
的用法示例。
在下文中一共展示了Response.content_length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: index
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def index(self, req):
""" Handle GET and HEAD requests for static files. Directory requests are not allowed"""
static_dir = os.path.normpath(os.path.join(os.path.dirname(__file__), '../static/'))
# filter out ..
try:
static_path = req.urlvars['path'].replace('/..', '')
except:
return HTTPForbidden()
path = os.path.join(static_dir, static_path)
if os.path.isdir(path):
return HTTPForbidden()
if req.method == 'GET' or req.method == 'HEAD':
if os.path.isfile(path):
etag, modified, mime_type, size = self._get_stat(path)
res = Response()
res.headers['content-type'] = mime_type
res.date = rfc822.formatdate(time.time())
res.last_modified = modified
res.etag = etag
if_modified_since = req.headers.get('HTTP_IF_MODIFIED_SINCE')
if if_modified_since:
if rfc822.parsedate(if_modified_since) >= rfc822.parsedate(last_modified):
return HTTPNotModified()
if_none_match = req.headers.get('HTTP_IF_NONE_MATCH')
if if_none_match:
if if_none_match == '*' or etag in if_none_match:
return HTTPNotModified()
# set the response body
if req.method == 'GET':
fd = open(path, 'rb')
if 'wsgi.file_wrapper' in req.environ:
res.app_iter = req.environ['wsgi.file_wrapper'](fd)
res.content_length = size
else:
res.app_iter = iter(lambda: fd.read(8192), '')
res.content_length = size
else:
res.body = ''
return res
else:
return None
else:
return None
示例2: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def make_response(uri, environ):
res = Response(conditional_response=True)
# check if the host is online. If not raise an http error
if not pingSMB( parseSMBuri(uri)["host"] ):
return HTTPGatewayTimeout("Host is currently offline. You may try again at a later time.")
try:
f = c.open(uri)
except smbc.NoEntryError:
return HTTPNotFound("The file you requested is no longer available!")
fs = f.fstat()
filesize = fs[6]
last_modified = fs[8] # mtime
filename = uri.split("/")[-1]
req = Request(environ)
log.debug("Incoming request: \n" + str(req))
if req.range:
log.debug("begin ranged transfer")
res.status_int = 206
res.content_range = req.range.content_range(filesize)
(start, stop) = req.range.range_for_length(filesize)
log.debug("filesize: " + str(filesize))
log.debug("start: " + str(start) + " stop: " + str(stop))
log.debug("Content-Range: " + str(res.content_range))
res.app_iter = FileIterable(uri, start=start, stop=stop)
res.content_length = stop - start
else:
log.debug("begin normal transfer")
res.app_iter = FileIterable(uri)
res.content_length = filesize
log.debug("Content-Length: " + str(res.content_length))
res.server_protocol = "HTTP/1.1"
# Make sure the file gets downloaded and not played live
res.content_type = "application/octet-stream"
res.last_modified = last_modified
res.etag = '%s-%s-%s' % (fs[8], fs[6], hash(f))
res.headers.add("Content-Disposition", 'attachment; filename="%s"' % str(filename) )
res.headers.add("Accept-Ranges", "bytes")
return res
示例3: do_download
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def do_download(self, collection_id, post_data, is_new=False):
if is_new:
return self.error_response('POST argument required: collection_id')
writer = post_data.get('writer', self.default_writer)
try:
log.info('download %s %s' % (collection_id, writer))
output_path = self.get_path(collection_id, self.output_filename, writer)
os.utime(output_path, None)
status = self.read_status_file(collection_id, writer)
response = Response()
response.app_iter = FileIterable(output_path)
response.content_length = os.path.getsize(output_path)
if 'content_type' in status:
response.content_type = status['content_type'].encode('utf-8', 'ignore')
else:
log.warn('no content type in status file')
if 'file_extension' in status:
response.headers['Content-Disposition'] = 'inline; filename=collection.%s' % (
status['file_extension'].encode('utf-8', 'ignore'),
)
else:
log.warn('no file extension in status file')
return response
except Exception, exc:
log.ERROR('exception in do_download(): %r' % exc)
return Response(status=500)
示例4: app
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def app(environ, start_response):
"""Multipart AJAX request example.
See: http://test.getify.com/mpAjax/description.html
"""
response = Response()
parts = []
for i in range(12):
for j in range(12):
parts.append(executor.submit(mul, i, j))
def stream(parts, timeout=None):
try:
for future in as_completed(parts, timeout):
mime, result = future.result()
result = result.encode('utf8')
yield "!!!!!!=_NextPart_{num}\nContent-Type: {mime}\nContent-Length: {length}\n\n".format(
num = randint(100000000, 999999999),
mime = mime,
length = len(result)
).encode('utf8') + result
except TimeoutError:
for future in parts:
future.cancel()
response.content_length = None
response.app_iter = stream(parts, 0.2)
return response(environ, start_response)
示例5: test_HEAD_conditional_response_range_empty_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def test_HEAD_conditional_response_range_empty_response():
from webob.response import EmptyResponse
req = Request.blank('/')
req.method = 'HEAD'
res = Response(request=req, conditional_response=True)
res.status_int = 200
res.body = 'Are we not men?'
res.content_length = len(res.body)
class FakeRequest:
method = 'HEAD'
if_none_match = 'none'
if_modified_since = False
def __init__(self, env):
self.env = env
self.range = self # simulate inner api
self.if_range = self
def content_range(self, length):
"""range attr"""
class Range:
start = 4
stop = 5
return Range
def match_response(self, res):
"""if_range_match attr"""
return True
def start_response(status, headerlist):
pass
res.RequestClass = FakeRequest
result = res({}, start_response)
ok_(isinstance(result, EmptyResponse), result)
示例6: __call__
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def __call__(self, environ, start_response):
res = Response(conditional_response=True)
def x():
for i in xrange(10):
yield str(i)
res.app_iter = x()
res.content_length = 10
return res(environ, start_response)
示例7: test_app_iter_del
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def test_app_iter_del():
res = Response()
res.content_length = 3
res._app_iter = ['123']
del res.app_iter
eq_(res._app_iter, None)
eq_(res._body, None)
eq_(res.content_length, None)
示例8: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def make_response(file, content_type):
response = Response(content_type=content_type)
response.app_iter = FileIterable(file)
stat = os.fstat(file.fileno())
response.content_length = stat.st_size
response.last_modified = stat.st_mtime
response.etag = '%s-%s' % (stat.st_mtime, stat.st_size)
return response
示例9: make_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def make_response(filename):
res = Response(content_type=get_mimetype(filename),
conditional_response=True)
res.app_iter = FileIterable(filename)
res.content_length = os.path.getsize(filename)
res.last_modified = os.path.getmtime(filename)
res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename), hash(filename))
return res
示例10: test_body_file_del
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def test_body_file_del():
res = Response()
res._body = '123'
res.content_length = 3
res._app_iter = ()
del res.body_file
eq_(res._body, None)
eq_(res.content_length, None)
eq_(res._app_iter, None)
示例11: test_unicode_body_del
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def test_unicode_body_del():
res = Response()
res._body = '123'
res.content_length = 3
res._app_iter = ()
del res.unicode_body
eq_(res._body, None)
eq_(res.content_length, None)
eq_(res._app_iter, None)
示例12: file_response
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def file_response(filename):
"""return a webob response object appropriate to a file name"""
res = Response(content_type=get_mimetype(filename),
conditional_response=True)
res.app_iter = FileIterable(filename)
res.content_length = os.path.getsize(filename)
res.last_modified = os.path.getmtime(filename)
res.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename), hash(filename))
return res
示例13: do_thumb
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def do_thumb(self, req, image):
"""
Serve a thumbnail of an image from the library
"""
if not image in self.library:
self.not_found(req)
resp = Response()
resp.content_type = 'image/jpeg'
resp.content_length = self.library.stat_thumbnail(image).st_size
resp.app_iter = FileWrapper(self.library.open_thumbnail(image))
return resp
示例14: do_image
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def do_image(self, req, image):
"""
Serve an image from the library
"""
if not image in self.library:
self.not_found(req)
resp = Response()
resp.content_type, resp.content_encoding = mimetypes.guess_type(
image, strict=False)
resp.content_length = self.library.stat_image(image).st_size
resp.app_iter = FileWrapper(self.library.open_image(image))
return resp
示例15: do_download
# 需要导入模块: from webob import Response [as 别名]
# 或者: from webob.Response import content_length [as 别名]
def do_download(self, req):
"""
Send the library as a .zip archive
"""
archive = self.library.archive()
size = archive.seek(0, io.SEEK_END)
archive.seek(0)
resp = Response()
resp.content_type = 'application/zip'
resp.content_length = size
resp.content_disposition = 'attachment; filename=images.zip'
resp.app_iter = FileWrapper(archive)
return resp