本文整理汇总了Python中pyramid.response.Response.last_modified方法的典型用法代码示例。如果您正苦于以下问题:Python Response.last_modified方法的具体用法?Python Response.last_modified怎么用?Python Response.last_modified使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.Response
的用法示例。
在下文中一共展示了Response.last_modified方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_file_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例2: SendFile
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例3: serve_gridfs_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例4: export
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [as 别名]
def export(self, extm, params, req):
csv_dialect = params.pop('csv_dialect', 'excel')
csv_encoding = params.pop('csv_encoding', 'utf_8')
fields = []
for field in extm.export_view:
if isinstance(field, PseudoColumn):
continue
fields.append(field)
if csv_encoding not in _encodings:
raise ValueError('Unknown encoding specified')
res = Response()
loc = get_localizer(req)
now = datetime.datetime.now()
res.last_modified = now
if csv_dialect in ('excel', 'excel-tab'):
res.content_type = 'application/vnd.ms-excel'
else:
res.content_type = 'text/csv'
res.charset = _encodings[csv_encoding][0]
res.cache_control.no_cache = True
res.cache_control.no_store = True
res.cache_control.private = True
res.cache_control.must_revalidate = True
res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
if PY3:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
urllib.parse.quote(loc.translate(extm.menu_name), ''),
now.date().isoformat()
)
else:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.csv' % (
urllib.quote(loc.translate(extm.menu_name).encode(), ''),
now.date().isoformat()
)
for prop in ('__page', '__start', '__limit'):
if prop in params:
del params[prop]
data = extm.read(params, req)['records']
res.app_iter = csv_generator(
data, fields, csv_dialect,
encoding=csv_encoding,
localizer=loc,
model=extm
)
return res
示例5: download
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例6: download_zip
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例7: serve
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [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
示例8: notmodified_tween
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [as 别名]
def notmodified_tween(request):
if os.path.isfile(lock_file):
response = Response(render('templates/maintenance.jinja2',
{},
request))
response.status_code = 503
return response
if (request.if_modified_since is not None and
request.if_modified_since >=
publication_date.replace(microsecond=0)):
return HTTPNotModified()
response = handler(request)
response.last_modified = publication_date
return response
示例9: export
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [as 别名]
def export(self, extm, params, req):
pdf_pagesz = params.pop('pdf_pagesz', 'a4')
pdf_orient = params.pop('pdf_orient', 'portrait')
try:
pdf_hmargins = float(params.pop('pdf_hmargins', 1.8))
except ValueError:
pdf_hmargins = 1.8
try:
pdf_vmargins = float(params.pop('pdf_vmargins', 2.0))
except ValueError:
pdf_vmargins = 2.0
fields = []
flddef = []
col_widths = []
col_flexes = []
total_width = 0
total_flex = 0
for field in extm.export_view:
if isinstance(field, PseudoColumn):
fld = field
field = fld.name
else:
fld = extm.get_column(field)
fields.append(field)
flddef.append(fld)
width = fld.column_width
flex = fld.column_flex
if not width:
width = fld.pixels
if not width:
width = 200
width = width / 200 * inch
col_widths.append(width)
if flex:
col_flexes.append(flex)
total_flex += flex
else:
col_flexes.append(None)
total_width += width
if pdf_pagesz not in PAGE_SIZES:
raise ValueError('Unknown page size specified')
if pdf_orient not in ('portrait', 'landscape'):
raise ValueError('Unknown page orientation specified')
res = Response()
loc = get_localizer(req)
now = datetime.datetime.now()
res.last_modified = now
res.content_type = 'application/pdf'
res.cache_control.no_cache = True
res.cache_control.no_store = True
res.cache_control.private = True
res.cache_control.must_revalidate = True
res.headerlist.append(('X-Frame-Options', 'SAMEORIGIN'))
if PY3:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.pdf' % (
urllib.parse.quote(loc.translate(extm.menu_name), ''),
now.date().isoformat()
)
else:
res.content_disposition = \
'attachment; filename*=UTF-8\'\'%s-%s.pdf' % (
urllib.quote(loc.translate(extm.menu_name).encode(), ''),
now.date().isoformat()
)
for prop in ('__page', '__start', '__limit'):
if prop in params:
del params[prop]
data = extm.read(params, req)['records']
doc = DefaultDocTemplate(
res,
request=req,
pagesize=pdf_pagesz,
orientation=pdf_orient,
topMargin=pdf_vmargins * cm,
leftMargin=pdf_hmargins * cm,
rightMargin=pdf_hmargins * cm,
bottomMargin=pdf_vmargins * cm,
title=loc.translate(_('{0}, exported at {1}')).format(
loc.translate(extm.menu_name),
format_datetime(now, locale=req.current_locale)
)
)
total_width = doc.width - total_width - 12
if total_flex > 0:
width_per_flex = total_width / total_flex
else:
width_per_flex = 0.0
table_widths = []
for idx, field in enumerate(fields):
if col_flexes[idx]:
table_widths.append(col_flexes[idx] * width_per_flex)
else:
#.........这里部分代码省略.........
示例10: __call__
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import last_modified [as 别名]
def __call__(self):
make_zip = False
request = self.request
user = request.user
filename = request.context.filename
download_dir = os.path.join(const._app_path, 'download')
fnamelower = filename.lower()
need_super = False
user_dom = None
if fnamelower.endswith('cic.zip'):
need_super = True
user_dom = user.cic
elif fnamelower.endswith('vol.zip'):
need_super = True
user_dom = user.vol
if need_super:
if not user_dom.SuperUser:
self._security_failure()
else:
username = filename.rsplit('_', 1)
if len(username) != 2 or username[0] != user.Login.replace(' ', '_'):
self._security_failure()
if '/' in filename or '\\' in filename or '..' in filename or \
':' in filename:
self._security_failure()
root, ext = os.path.splitext(filename)
root2, ext2 = os.path.splitext(root)
if ext.lower() == '.zip' and ext2:
make_zip = True
filename = root
fullpath = None
if fnamelower.endswith('cic.zip') or fnamelower.endswith('vol.zip'):
fullpath = os.path.join(download_dir, str(request.dboptions.MemberID).join(os.path.splitext(filename)))
else:
fullpath = os.path.join(download_dir, filename)
relativepath = os.path.relpath(fullpath, download_dir)
if '..' in relativepath or '/' in relativepath or '\\' in relativepath or \
':' in relativepath:
self._security_failure()
if not os.path.exists(fullpath):
raise NotFound(_('File not found', request))
if make_zip:
file = tempfile.TemporaryFile()
zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED)
zip.write(fullpath, strip_accents(filename))
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.last_modified = os.path.getmtime(fullpath)
else:
res = Response(content_type=get_mimetype(ext), conditional_response=True)
res.app_iter = FileIterable(fullpath)
res.content_length = os.path.getsize(fullpath)
res.last_modified = os.path.getmtime(fullpath)
res.etag = '%s-%s-%s' % (os.path.getmtime(fullpath),
os.path.getsize(fullpath), hash(fullpath))
res.headers['Content-Disposition'] = 'attachment;filename=' + strip_accents(request.context.filename).encode('utf8')
return res