本文整理汇总了Python中pyramid.response.FileResponse.content_disposition方法的典型用法代码示例。如果您正苦于以下问题:Python FileResponse.content_disposition方法的具体用法?Python FileResponse.content_disposition怎么用?Python FileResponse.content_disposition使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.FileResponse
的用法示例。
在下文中一共展示了FileResponse.content_disposition方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: artifact_download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例2: export_to_moe_view
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例3: file_serve
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例4: downloadFile
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例5: export_focl_struct
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例6: vector_style_qml
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
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
示例7: download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def download(photo, request):
"""
Downloads photo as attachment.
"""
response = FileResponse(photo.get_image(request.fs).path,
request,
content_type=photo.content_type)
response.content_disposition = "attachment;filename=%s" % photo.image
return response
示例8: get_video_file
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def get_video_file(request):
if request.user.keyname == 'guest':
raise HTTPForbidden()
video_id = int(request.matchdict['id'])
task = VideoProduceTask.filter(VideoProduceTask.user_id == request.user.id, VideoProduceTask.id == video_id)[0]
fileobj = FileObj.filter(FileObj.id == task.fileobj_id, FileObj.component == COMP_ID)[0]
fn = env.file_storage.filename(fileobj)
fr = FileResponse(fn, content_type=bytes(task.file_mime_type), request=request)
fr.content_disposition = (u'attachment; filename="%s"' % task.file_name).encode('utf-8') #quote_plus
return fr
示例9: codebook_download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def codebook_download(context, request):
"""
Returns full codebook file
"""
export_dir = request.registry.settings['studies.export.dir']
codebook_name = exports.codebook.FILE_NAME
path = os.path.join(export_dir, codebook_name)
if not os.path.isfile(path):
log.warn('Trying to download codebook before it\'s pre-cooked!')
raise HTTPBadRequest(u'Codebook file is not ready yet')
response = FileResponse(path)
response.content_disposition = 'attachment;filename=%s' % codebook_name
return response
示例10: download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def download(self):
str_id = self.request.matchdict["id"]
id = self.storage.model.id_type(str_id)
type = self.request.matchdict.get("type", self.storage.default_type)
path = os.path.join(self.storage.directory, str_id, type)
response = FileResponse(path, self.request, self.storage.cache_max_age)
item = self.storage.model.with_id(id)
self.storage.one(item)
response.content_disposition = 'attachment; filename="%s"' % item["filename"]
return response
示例11: action_get_ae_pkg
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def action_get_ae_pkg(self):
"""
Generates the AppEnsemble-package for downloading
:return: Response with AppEnsemble-package
"""
ae = self.pool.get_AppEnsemble(self.uri)
response = FileResponse(
ae.ae_pkg_path,
request=self.request,
content_type='application/vnd.aof.package-archive'
)
response.content_disposition = 'attachement; filename="' + str(self.uri) + ".ae"
return response
示例12: get_pkpass
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def get_pkpass(request):
loc = get_localizer(request)
cfg = request.registry.settings
sess = DBSession()
client_pass = None
token = None
passserial = request.current_route_path().split('/')[-1].split("?")[0]
try:
token = request.params.get('authtoken', None)
sess = DBSession()
if token:
try:
client_pass = sess.query(PassbookPass).filter(
PassbookPass.token == token,
).one()
except NoResultFound:
raise KeyError('Invalid token')
else:
try:
client_pass = sess.query(PassbookPass).filter(
PassbookPass.serial == passserial,
).one()
token = client_pass.token
except NoResultFound:
raise KeyError('Invalid setial')
except ValueError:
pass
p12_cert = cfg.get('netprofile.client.pkpass.p12', None)
pem_cert = cfg.get('netprofile.client.pkpass.pem', None)
teamId = cfg.get('netprofile.client.pkpass.teamId', None)
passId = cfg.get('netprofile.client.pkpass.passId', None)
passfile = tempfile.NamedTemporaryFile()
pkpass = P.PyPKPass.PKPass.PKPass(passId, passserial)
pkpass.webServiceURL = request.url.split("?")[0]
pkpass.authenticationToken = token
pkpass.backgroundColor="rgb(23, 187, 82)"
pkpass.teamIdentifier=teamId
pkpass.passTypeIdentifier=passId
pkpass.addHeaderField("Name", "Netprofile Account", 'My Netprofile Account Details')
pkpass.addPrimaryField("username", client_pass.stash.entity.nick, "Username")
pkpass.addPrimaryField("Account Name", client_pass.stash.name, 'Account Name')
pkpass.addSecondaryField("Amount", "{0}".format(client_pass.stash.amount), "Amont")
pkpass.addSecondaryField("Credit", "{0}".format(client_pass.stash.credit), "Credit")
pkpass.sign(p12_cert, "", passfile.name, pem_cert)
resp = FileResponse(passfile.name)
resp.content_disposition = 'attachment; filename="{0}.pkpass"'.format(passId)
return resp
示例13: download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def download(request):
"""
Handler serving download requests.
"""
uid = request.matchdict["uid"]
filename = get_file_for_download(request, uid)
if filename is None:
return HTTPNotFound()
response = FileResponse(filename, request)
response.content_disposition = "attachment;filename=\"{0}\"".format(
os.path.basename(filename))
return response
示例14: download
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def download(context, request):
"""
Returns specific download attachement
The user should only be allowed to download their exports.
"""
export = context
if export.status != 'complete':
raise HTTPBadRequest('Export is not complete')
export_dir = request.registry.settings['studies.export.dir']
path = os.path.join(export_dir, export.name)
response = FileResponse(path)
response.content_disposition = 'attachment;filename=export.zip'
return response
示例15: send_file
# 需要导入模块: from pyramid.response import FileResponse [as 别名]
# 或者: from pyramid.response.FileResponse import content_disposition [as 别名]
def send_file(request):
if 'file_id' in request.matchdict:
file_id = request.matchdict['file_id']
log.info('[event=send_file][file_id=%s', file_id)
_file = request.db['file_locations'].find_one(
{'_id': ObjectId(file_id)})
if _file['deleted'] == 'False' and _file['visible'] == 'True':
response = FileResponse(_file['location'], request=request)
response.content_disposition = (
'attachment; filename="%s"' % (_file['filename']))
request.db['file_locations'].update(
{'_id': ObjectId(request.matchdict['file_id'])},
{'$inc': {'downloads': 1}})
return response
raise HTTPNotFound