本文整理汇总了Python中pyramid.response.FileResponse类的典型用法代码示例。如果您正苦于以下问题:Python FileResponse类的具体用法?Python FileResponse怎么用?Python FileResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FileResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: download_log
def download_log(request):
sys_mgr = sysinfo.sys_mgr() # get sys manager
sys_mgr.rm_sys_log() # rm the exist tar log file
log_tar_file = sys_mgr.tar_sys_log()
response = FileResponse(log_tar_file, request=request, content_type='application/force-download')
response.headers['Content-Disposition'] = 'attachment; filename=%s' % (os.path.basename(log_tar_file))
return response
示例2: file_serve
def file_serve(request):
serve_engine = request.registry.settings.get('serve_engine', 'local')
try:
t = Token.get_by_urlid(request.matchdict.get('token'))
except NoResultFound:
return HTTPNotFound()
f = t.upload.file
if serve_engine == 'nginx':
print(f.get_file_path())
headers = request.response.headers
headers['Content-Disposition'] = str(f.filename)
headers['Content-Type'] = 'application/force-download'
headers['Accept-Ranges'] = 'bytes'
headers['X-Accel-Redirect'] = '/getfile/'+f.hash+';'
return request.response
else:
fr = FileResponse(
f.get_file_path(),
request=request,
content_type=str(f.mime)
)
fr.content_disposition = 'filename="{0}"'.format(str(f.filename))
return fr
示例3: export_to_moe_view
def export_to_moe_view(request):
import io, re
from tempfile import NamedTemporaryFile
import xlwt
from pyramid_sqlalchemy import Session
from ..models import NewStudentModel
from pyramid.response import FileResponse
with NamedTemporaryFile(delete=True) as f:
wb = xlwt.Workbook()
ws = wb.add_sheet('sheet1')
ws.write(0, 0, '姓名')
ws.write(0, 1, '身分證號')
regex = re.compile(r'^[A-Z]\d{9}$') # 比對是否為身分證號
counter = 1
for each_new_student in Session.query(NewStudentModel).filter(NewStudentModel.status==1):
if regex.match(each_new_student.id_number):
ws.write(counter, 0, each_new_student.name)
ws.write(counter, 1, each_new_student.id_number)
counter += 1
wb.save(f.name)
f.flush()
f.seek(0)
response = FileResponse(f.name)
response.content_type = 'application/octet-stream'
response.content_disposition = 'attachment; filename="moe.xls"'
return response
示例4: whitenoise_tween
def whitenoise_tween(request):
whn = request.registry.whitenoise
if whn.autorefresh:
static_file = whn.find_file(request.path_info)
else:
static_file = whn.files.get(request.path_info)
# We could not find a static file, so we'll just continue processing
# this as normal.
if static_file is None:
return handler(request)
request_headers = dict(kv for kv in request.environ.items() if kv[0].startswith("HTTP_"))
if request.method not in {"GET", "HEAD"}:
return HTTPMethodNotAllowed()
else:
path, headers = static_file.get_path_and_headers(request_headers)
headers = MultiDict(headers)
resp = FileResponse(
path,
request=request,
content_type=headers.pop("Content-Type", None),
content_encoding=headers.pop("Content-Encoding", None),
)
resp.md5_etag()
resp.headers.update(headers)
return resp
示例5: zip_response_adv
def zip_response_adv(request, filename, files):
"""Return a Response object that is a zipfile with name filename.
:param request: The request object.
:param filename: The filename the browser should save the file as.
:param files: A list of tupples mapping
(type, name in zip, filepath or content)
i.e.
('file', name in zip, './myfile.txt')
('text', name in zip, 'a.out foo bar baz the quick fox jumps over the lazy dog')
only supported types are 'file' and 'text'
"""
tmp_file = NamedTemporaryFile()
try:
with ZipFile(tmp_file, 'w') as zip_file:
for type, zip_path, actual in files:
if type == "file":
zip_file.write(actual, zip_path)
else:
zip_file.writestr(zip_path, actual)
tmp_file.flush() # Just in case
response = FileResponse(tmp_file.name, request=request,
content_type=str('application/zip'))
response.headers['Content-disposition'] = ('attachment; filename="{0}"'
.format(filename))
return response
finally:
tmp_file.close()
示例6: get_movie
def get_movie(request):
movie = session.query(Movie).filter(Movie.movie_id == request.matchdict['movie_id']).one()
movie_file = os.path.join(ConfigManager.monitor_dir, movie.movie_file)
file_name = os.path.basename(movie_file)
response = FileResponse(path=movie_file)
response.headerlist = {'Content-disposition': 'attachment; filename=\"%s\"' % (file_name)}
return response
示例7: get_artifact
def get_artifact(self):
artifact = self.request.context
response = FileResponse(artifact.location,
request=self.request)
cdh = 'attachment; filename="{0}"'.format(artifact.name)
response.headers['Content-Disposition'] = cdh
return response
示例8: content
def content(self):
filename = abspath(self.format)
response = FileResponse(filename)
response.headers['Content-type'] = 'application/octet-stream'
response.headers['Content-Disposition'] = 'attachment; filename="{0}";'.format(
basename(filename))
return response
示例9: artifact_download
def artifact_download(request, inline):
af = get_artifact(request)
if af.is_bundle:
if inline:
raise HTTPBadRequest("Inline view not supported for bundles")
# We have a bundle. So we need to prepare a zip (unless we already have one)
disk_name = af.file
# Locking on a separate file since zipfile did not want to write to the
# same file we are locking on. It just means that we need to clean up
# that file at the same time as the main cache file.
with portalocker.Lock(disk_name + ".lock", timeout=300, check_interval=1):
if not os.path.exists(disk_name):
with zipfile.ZipFile(disk_name, 'w', compression=zipfile.ZIP_BZIP2) as _zip:
for cf in af.artifacts:
_zip.write(cf.file, arcname=cf.bundle_filename(af))
file_name = af.name + ".zip"
else:
disk_name = af.file
file_name = af.filename
mime, encoding = mimetypes.guess_type(file_name)
if mime is None:
mime = ('text/plain' if inline else 'application/octet-stream')
# If the current simple approach proves to be a problem the discussion
# at http://stackoverflow.com/q/93551/11722 can be considered.
response = FileResponse(disk_name, request=request, content_type=mime)
response.content_disposition = '{}; filename="{}"'.format('inline' if inline else 'attachment', file_name)
# Specifically needed for jquery.fileDownload
response.set_cookie('fileDownload', 'true')
return response
示例10: download
def download(context, request):
path = open_file(context.filesystem_path).name
response = FileResponse(path=path, request=request,
content_type=context.mimetype)
response.headers['Content-Disposition'] = ('attachment; filename="%s"' %
context.filename)
return response
示例11: download
def download(context, request):
path = open_file(context.filesystem_path).name
mimetype = context.mimetype or 'application/octet-stream'
response = FileResponse(path=path, request=request,
content_type=mimetype.encode('utf8'))
response.headers['Content-Disposition'] = ('inline; filename="%s"' %
context.filename.encode('utf8'))
return response
示例12: downloadFile
def downloadFile(self, Department, File, request):
global FILESYS_PATH
global BASE_ROOT
urlOfFile = BASE_ROOT+'/'+FILESYS_PATH+'/'+Department+'/'+File
typeOfFile = mimetypes.guess_type(url=urlOfFile)[0]
response = FileResponse(urlOfFile, request=request,content_type= mimetypes.guess_type(url=urlOfFile)[0] )
response.content_disposition = 'attachment; filename="'+File+'"'
return response
示例13: export_focl_struct
def export_focl_struct(request, export_type):
res_id = request.matchdict['id']
dbsession = DBSession()
try:
focl_resource = dbsession.query(FoclStruct).get(res_id)
except:
raise HTTPNotFound()
if not focl_resource.has_permission(DataScope.read, request.user):
raise HTTPForbidden()
LogEntry.info('Export resource %s to %s' % (res_id, export_type), component=COMP_ID)
#create temporary dir
zip_dir = tempfile.mkdtemp()
# save layers to geojson (FROM FEATURE_LAYER)
for layer in focl_resource.children:
if layer.identity == VectorLayer.identity and layer.feature_query()().total_count > 0:
json_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'json'))
_save_resource_to_file(layer, json_path, single_geom=export_type == 'csv')
if export_type == 'kml':
kml_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'kml'))
_json_to_kml(json_path, kml_path)
# remove json
os.remove(json_path.encode('utf-8'))
if export_type == 'csv':
csv_path = path.join(zip_dir, '%s.%s' % (layer.display_name, 'csv'))
_json_to_csv(json_path, csv_path)
# remove json
os.remove(json_path.encode('utf-8'))
with tempfile.NamedTemporaryFile(delete=True) as temp_file:
# write archive
zip_file = ZipFile(temp_file, mode="w", compression=ZIP_DEFLATED)
zip_subpath = focl_resource.display_name + '/'
for file_name in os.listdir(zip_dir):
src_file = path.join(zip_dir, file_name)
zip_file.write(src_file, (zip_subpath+unicode(file_name, 'utf-8')).encode('cp866', errors='ignore'))
zip_file.close()
# remove temporary dir
rmtree(zip_dir)
# send
temp_file.seek(0, 0)
response = FileResponse(
path.abspath(temp_file.name),
content_type=bytes('application/zip'),
request=request
)
disp_name = focl_resource.display_name
for ch in '\\/:*?"<>|':
disp_name = disp_name.replace(ch, '')
response.content_disposition = (u'attachment; filename="%s [%s].zip"' % (disp_name, export_type)).encode('utf-8')
return response
示例14: vector_style_qml
def vector_style_qml(request):
request.resource_permission(ResourceScope.read)
fn = env.file_storage.filename(request.context.qml_fileobj)
response = FileResponse(fn, request=request)
response.content_disposition = (b'attachment; filename=%d.qml'
% request.context.id)
return response
示例15: download_csv
def download_csv(request):
global result_paths_dict
csv_ref=request.matchdict['csv_ref']
path = result_paths_dict[csv_ref]['csv']
response = FileResponse(
path,
request=request,
content_type='text/csv'
)
response.headers['Content-Disposition'] = ("attachment; filename="+os.path.basename(path))
return response