本文整理汇总了Python中pyramid.response.Response.content_length方法的典型用法代码示例。如果您正苦于以下问题:Python Response.content_length方法的具体用法?Python Response.content_length怎么用?Python Response.content_length使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.Response
的用法示例。
在下文中一共展示了Response.content_length方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def plot(request):
"""
http://stackoverflow.com/a/5515994/185820
"""
import cStringIO
from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg
x, y = 4, 4
qs = parse_qs(request.query_string)
if 'x' in qs:
x = int(qs['x'][0])
if 'y' in qs:
y = int(qs['y'][0])
fig = Figure(figsize=[x, y])
ax = fig.add_axes([.1, .1, .8, .8])
ax.scatter([1, 2], [3, 4])
canvas = FigureCanvasAgg(fig)
# write image data to a string buffer and get the PNG image bytes
buf = cStringIO.StringIO()
canvas.print_png(buf)
data = buf.getvalue()
# write image bytes back to the browser
response = Response(data)
response.content_type = 'image/png'
response.content_length = len(data)
return response
示例2: __call__
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def __call__(self):
data, record_data = self._really_do_it()
data = json.dumps(data)
file = tempfile.TemporaryFile()
zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED)
zip.writestr('export.json', data)
if record_data:
try:
zip.write(record_data, 'record_data.xml')
finally:
try:
os.unlink(record_data)
except:
pass
zip.close()
length = file.tell()
file.seek(0)
res = Response(content_type='application/zip', charset=None)
res.app_iter = FileIterator(file)
res.content_length = length
res.headers['Content-Disposition'] = 'attachment;filename=Export.zip'
return res
示例3: SendFile
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def SendFile(self, file):
"""
Creates the response and sends the file back. Uses the FileIterator.
#!date format
"""
if not file:
return HTTPNotFound()
last_mod = file.mtime()
if not last_mod:
last_mod = self.context.meta.pool_change
r = Response(content_type=str(GetMimeTypeExtension(file.extension)), conditional_response=True)
iterator = file.iterator()
if iterator:
r.app_iter = iterator
else:
try:
r.body = file.read()
except FileNotFound:
raise NotFound
r.content_length = file.size
r.last_modified = last_mod
r.etag = '%s-%s' % (last_mod, hash(file.path))
r.cache_expires(self.fileExpires)
return r
示例4: get_file_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def get_file_response(filename, document_root=None, accel_header=None):
"""helper the get a file response"""
if not os.path.isfile(filename):
return HTTPNotFound()
resp = Response(content_type=get_mimetype(filename),
conditional_response=True)
resp.content_length = os.path.getsize(filename)
resp.last_modified = os.path.getmtime(filename)
resp.etag = '%s-%s-%s' % (os.path.getmtime(filename),
os.path.getsize(filename), hash(filename))
if accel_header:
if accel_header.lower() == "x-accel-redirect":
# return full path
filename = filename[len(os.path.dirname(document_root)):]
filename = '/%s' % filename.strip('/')
resp.headers[accel_header.title()] = filename
elif accel_header.lower() == "x-sendfile":
# return full path
resp.headers[accel_header.title()] = filename
else:
raise RuntimeError(
"Can't find a way to use your %s header" % accel_header)
resp.app_iter = [b'']
else:
resp.app_iter = FileIterable(filename)
return resp
示例5: __call__
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def __call__(self):
response = Response()
response.content_disposition = 'attachment; filename="{}"'.format(self.context.filename)
response.charset = 'utf-8'
response.content_type = self.context.content_type
response.body_file = self.context.content.open()
response.content_length = self.context.size
return response
示例6: toolbar_handler
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def toolbar_handler(request):
root_path = request.route_path("debugtoolbar.root")
request.exc_history = exc_history
remote_addr = request.remote_addr
if request.path.startswith(root_path) or (not remote_addr in hosts):
return handler(request)
toolbar = DebugToolbar(request, panel_classes)
request.debug_toolbar = toolbar
_handler = handler
for panel in toolbar.panels:
_handler = panel.wrap_handler(_handler)
try:
response = _handler(request)
except Exception:
info = sys.exc_info()
if exc_history is not None:
tb = get_traceback(info=info, skip=1, show_hidden_frames=False, ignore_system_exceptions=True)
for frame in tb.frames:
exc_history.frames[frame.id] = frame
exc_history.tracebacks[tb.id] = tb
body = tb.render_full(request, evalex=True).encode("utf-8", "replace")
response = Response(body, status=500)
toolbar.process_response(response)
return response
raise
else:
if intercept_redirects:
# Intercept http redirect codes and display an html page with a
# link to the target.
if response.status_int in redirect_codes:
redirect_to = response.location
redirect_code = response.status_int
if redirect_to:
content = render(
"pyramid_debugtoolbar:templates/redirect.jinja2",
{"redirect_to": redirect_to, "redirect_code": redirect_code},
)
content = content.encode(response.charset)
response.content_length = len(content)
response.location = None
response.app_iter = [content]
response.status_int = 200
toolbar.process_response(response)
return response
finally:
# break circref
del request.debug_toolbar
示例7: download_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def download_file(request):
url = request.application_url
currentDir = os.path.dirname(os.path.realpath(__file__))
downloadFolder = currentDir + '/../downloads/'
file = downloadFolder + request.GET.get('FileName')
size = os.path.getsize(file)
response = Response(content_type='application/force-download', content_disposition='attachment; filename=' + request.GET.get('FileName'))
response.app_iter = open(file, 'rb')
response.content_length = size
return response
示例8: serve_gridfs_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def serve_gridfs_file(file):
response = Response()
response.content_type = file.content_type
response.last_modified = file.upload_date
response.etag = file.md5
for chunk in file:
response.body_file.write(chunk)
file.close()
response.content_length = file.length
return response
示例9: captcha
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def captcha(request):
form_id = request.matchdict.get('form_id', u'') # 2 routes: with and without form_id
image, ctype = Captcha(request.client_addr, form_id).render()
response = Response(body=image, content_type=ctype)
response.content_length = len(image)
response.cache_control = 'no-cache, no-store'
return response
示例10: jsonrpc_error_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def jsonrpc_error_response(error, id=None):
""" Marshal a Python Exception into a webob ``Response``
object with a body that is a JSON string suitable for use as
a JSON-RPC response with a content-type of ``application/json``
and return the response."""
body = json.dumps({"jsonrpc": "2.0", "id": id, "error": error.as_dict()})
response = Response(body)
response.content_type = "application/json"
response.content_length = len(body)
return response
示例11: download_zip
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def download_zip(request):
check_login(request)
res = Response(content_type='application/zip')
res.headers.add('Content-Disposition', 'attachment;filename=saved-module.zip')
save_dir = os.path.join(request.registry.settings['transform_dir'],
request.session['upload_dir'])
zipfile = open(os.path.join(save_dir, 'upload.zip'), 'rb')
stat = os.fstat(zipfile.fileno())
res.app_iter = iter(lambda: zipfile.read(4096), '')
res.content_length = stat.st_size
res.last_modified = datetime.datetime.utcfromtimestamp(
stat.st_mtime).strftime('%a, %d %b %Y %H:%M:%S GMT')
return res
示例12: download
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def download(self, value, filename, request):
from mimetypes import guess_type
content_type, encoding = guess_type(filename)
file_path = value.file_path(filename)
res = Response(content_type=content_type, conditional_response=True)
res.app_iter = open(file_path,'rb')
res.content_length = os.path.getsize(file_path)
res.last_modified = os.path.getmtime(file_path)
res.etag = '%s-%s-%s' % (os.path.getmtime(file_path),
os.path.getsize(file_path),
hash(file_path))
return res
示例13: jsonrpc_error_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def jsonrpc_error_response(error, id=None):
""" Marshal a Python Exception into a webob ``Response``
object with a body that is a JSON string suitable for use as
a JSON-RPC response with a content-type of ``application/json``
and return the response."""
body = json.dumps({
'jsonrpc': '2.0',
'id': id,
'error': error.as_dict(),
})
response = Response(body)
response.content_type = 'application/json'
response.content_length = len(body)
return response
示例14: serve
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def serve(self, request):
""" Serve the GridFS file referred to by this object.
Returns a :class:`pyramid.response.Response` if a matching file was found in the GridFS.
Otherwise returns :class:`pyramid.httpexceptions.HTTPNotFound`.
"""
file = self.get_gridfs_file(request)
if file is None:
return HTTPNotFound("No file found for %s." % repr(self._id))
response = Response()
response.content_type = str(file.content_type)
response.last_modified = file.upload_date
response.etag = file.md5
for chunk in file:
response.body_file.write(chunk)
file.close()
response.content_length = file.length
return response
示例15: __call__
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_length [as 别名]
def __call__(self, context=None, request=None, **kw):
if self.path is None:
inst = self.__get__()
return inst(context=context, request=request, **kw)
result = self.render(context=context, request=request, **kw)
if isinstance(result, basestring):
response = Response(body=result)
else:
response = Response(app_iter=result)
response.content_length = os.path.getsize(self.path)
content_type = self.content_type
if content_type is None:
content_type = type(self).content_type
response.content_type = content_type
response.charset = self.encoding
return response