本文整理汇总了Python中pyramid.response.Response.app_iter方法的典型用法代码示例。如果您正苦于以下问题:Python Response.app_iter方法的具体用法?Python Response.app_iter怎么用?Python Response.app_iter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyramid.response.Response
的用法示例。
在下文中一共展示了Response.app_iter方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_file_response
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [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: pvc1_show_imageh5
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def pvc1_show_imageh5(request):
# Loads JPEG images from hdf5 file
h5_image_file = 'pvc1/pvc1_movie_frames.h5'
movie_id = int(request.matchdict['movie_id'])
segment_id = int(request.matchdict['segment_id'])
frame = int(request.matchdict['frame'])
image_dir = 'movie%03u_%03u.images' % (movie_id, segment_id)
image_name = 'movie%03u_%03u_%03u.jpeg' % (movie_id, segment_id, frame)
path = image_dir + '/' + image_name
response = Response(content_type='image/jpeg')
h5f = h5py.File(h5_image_file, 'r')
try:
ds = h5f[path]
except KeyError:
# missing file, generate an image to return
img = Image.new("RGB", (320, 220,), "#cccccc" )
draw = ImageDraw.Draw(img)
draw.text((15, 60), image_name + ' missing', fill='#000')
f = cStringIO.StringIO()
img.save(f, "jpeg")
f.seek(0)
response.app_iter = f
else:
dsv = ds.value
response.app_iter = dsv
h5f.close()
return response
示例3: show_img
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def show_img(request):
'''画像表示
'''
file_name = request.matchdict['file_name']
md = model(request.db)
file = md.get_file(file_name)
response = Response()
if file is not None:
response.content_type = file.content_type
response.app_iter = file
else:
response.content_type = 'image/jpeg'
response.app_iter = open('nopict.jpg', 'rb')
return response
示例4: pdf_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def pdf_file(request):
sbid = request.matchdict['sbid']
req_part = request.matchdict['part']
monograph = Monograph.get(request.db, sbid)
if req_part == monograph.isbn:
try:
pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'], stream=True)
except (couchdbkit.ResourceNotFound, AttributeError):
raise exceptions.NotFound()
else:
parts = get_book_parts(monograph._id, request)
try:
selected_part = parts[int(req_part)]
except (IndexError, ValueError):
raise exceptions.NotFound()
part = Part.get(request.db, selected_part['part_sbid'])
try:
pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'], stream=True)
except (couchdbkit.ResourceNotFound, AttributeError):
raise exceptions.NotFound()
response = Response(content_type='application/pdf')
response.app_iter = pdf_file
return response
示例5: cover
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def cover(request):
sbid = request.matchdict['sbid']
response_headers = {'content_type': 'image/jpeg',}
try:
monograph = request.db.get(sbid)
if 'thumbnail' in request.path:
img = request.db.fetch_attachment(monograph,monograph['cover_thumbnail']['filename'], stream=True)
else:
img = request.db.fetch_attachment(monograph,monograph['cover']['filename'], stream=True)
response_headers['expires'] = datetime_rfc822(365)
except (couchdbkit.ResourceNotFound, KeyError):
img = urllib2.urlopen(static_url('scielobooks:static/images/fakecover.jpg', request))
response = Response(**response_headers)
response.app_iter = img
try:
response.etag = str(hash(img))
except TypeError:
#cannot generate a hash for the object, return it without the ETag
pass
return response
示例6: download_backup
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def download_backup(request):
encoded_filename = request.matchdict['backup_id']
headers = []
try:
filename = base64.b64decode(encoded_filename).decode('utf-8')
except TypeError:
return HTTPNotFound()
backups_dir = get_backups_dir()
all_backups = [x for x in os.listdir(backups_dir) if os.path.isfile(os.path.join(backups_dir, x))]
if filename not in all_backups:
return HTTPNotFound()
full_path = os.path.join(backups_dir, filename)
if not os.path.isfile(full_path):
return HTTPNotFound()
headers = []
content_length = os.path.getsize(full_path)
headers.append(('Content-Length', str(content_length)))
headers.append(('Content-Disposition', str('attachment; filename={0}'.format(filename))))
response = Response(content_type='application/octet-stream')
try:
response.app_iter = open(full_path, 'rb')
except IOError:
return HTTPNotFound()
response.headerlist += headers
return response
示例7: get_dues18_invoice
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def get_dues18_invoice(invoice, request):
"""
Gets the invoice and returns a PDF response.
Args:
invoice: The invoice for which the PDF is requested.
request: The pyramid.request.Request object.
Returns:
A PDF response in case the invoice exists. Otherwise a redirect to the
error page.
"""
if invoice is None:
request.session.flash(
u'No invoice found!',
'danger' # message queue for user
)
return HTTPFound(request.route_url('error'))
if invoice.is_reversal:
pdf_file = make_reversal_pdf_pdflatex(invoice)
else:
pdf_file = make_invoice_pdf_pdflatex(invoice)
response = Response(content_type='application/pdf')
pdf_file.seek(0)
response.app_iter = open(pdf_file.name, "r")
return response
示例8: view_download
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def view_download(request):
req = request
url_dict = req.matchdict
id1 = url_dict['id'].isdigit() and url_dict['id'] or 0
dis = url_dict['disposisi_id'].isdigit() and url_dict['disposisi_id'] or 0
si = DBSession.query(Disposisi.surat_id).\
filter(Disposisi.id==dis,
)
row = DBSession.query(SuratDetail
).filter(SuratDetail.id==id1
).first()
b = row.path
c = row.name
d = row.mime
if not row:
return {'success':False, "msg":self.id_not_found()}
settings = get_settings()
dir_path = os.path.realpath(settings['static_files'])
filename = os.path.join(dir_path, b)
headers = [('Content-Disposition', 'attachment; filename=' + str(c))]
response = Response(content_type=d, headerlist=headers)
f = open(filename)
response.app_iter = FileIter(f)
print "----------------path------------------",b
print "--------------nama file---------------",c
print "------------content type--------------",d
return response
示例9: SendFile
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [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
示例10: sponsor_image_small
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def sponsor_image_small(request):
"""
return a smaller image depending on the amount given
(see get_sponsorshipGrade)
"""
#print "this is sponsor image"
_code = request.matchdict['linkcode']
_abo = Abo.get_by_linkcode(_code)
if isinstance(_abo, NoneType):
if request.locale_name == 'de':
the_url = 'zabo:static/ungueltig_s.png'
else:
the_url = 'zabo:static/invalid_s.png'
return HTTPFound(request.static_url(the_url))
#the_url = 'zabo:static/badge' + _abo.get_sponsorshipGrade() + '.png'
#return HTTPFound(request.static_url(the_url))
# XXX TODO: spool the files, don't serve from static !!!
# link must be unknown to outside!
base_path = request.registry.settings['base_path'] or ''
the_file = os.path.abspath(
os.path.join(
base_path,
'zabo/static_offline/badge' + _abo.get_sponsorshipGrade() + '_s.png')
)
response = Response(content_type='image/png')
response.app_iter = open(the_file, "r")
return response # pragma: no cover
示例11: __call__
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [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
示例12: swf_file
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def swf_file(request):
sbid = request.matchdict['sbid']
req_part = request.matchdict['part']
monograph = Monograph.get(request.db, sbid)
if req_part == monograph.isbn:
try:
pdf_file = request.db.fetch_attachment(monograph._id, monograph.pdf_file['filename'])
except (couchdbkit.ResourceNotFound, AttributeError):
raise exceptions.NotFound()
else:
parts = get_book_parts(monograph._id, request)
try:
selected_part = parts[int(req_part)]
except (IndexError, ValueError):
raise exceptions.NotFound()
part = Part.get(request.db, selected_part['part_sbid'])
try:
pdf_file = request.db.fetch_attachment(part._id, part.pdf_file['filename'])
except (couchdbkit.ResourceNotFound, AttributeError):
raise exceptions.NotFound()
swf_file = functions.convert_pdf2swf(pdf_file)
response = Response(content_type='application/x-shockwave-flash', expires=datetime_rfc822(365))
response.app_iter = swf_file
try:
response.etag = str(hash(swf_file))
except TypeError:
#cannot generate a hash for the object, return it without the ETag
pass
return response
示例13: translation_template
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def translation_template(request):
resp = Response()
resp.content_disposition = 'attachment; filename=oscad.pot'
resp.app_iter = resource_stream('oscad', 'locale/oscad.pot')
# otherwise Firefox thinks its a PowerPoint
resp.content_type = 'text/plain'
return resp
示例14: xhr_filemgr
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def xhr_filemgr(self):
cmd = ''
cmd_args = dict()
for k in self.request.params:
if k == '_':
continue
if k == 'cmd':
cmd = self.request.params[k]
else:
if k.endswith("[]"):
k2 = k.rstrip("[]")
cmd_args[k2] = self.request.params.getall(k)
else:
cmd_args[k] = self.request.params[k]
finder = create_finder(self.context, self.request)
try:
finder.run(cmd, cmd_args)
except FinderError as e:
L.exception(e)
if e.status:
self.request.response.status = e.status
if 'file' in finder.response:
resp = Response()
resp.app_iter = finder.response['file']
if finder.headers:
for k, v in finder.headers.items():
resp.headers[k] = v
return resp
else:
if finder.headers:
for k, v in finder.headers.items():
self.request.response.headers[k] = v
return finder.response
示例15: get_ticket
# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import app_iter [as 别名]
def get_ticket(request):
"""
this view gives a user access to her ticket via URL with code
the response is a PDF download
"""
_code = request.matchdict['code']
_email = request.matchdict['email']
_ticket = PartyTicket.get_by_code(_code)
if isinstance(_ticket, NoneType):
return HTTPFound(location=request.route_url('party'))
if not (_ticket.email == _email):
#print("no match!")
return HTTPFound(location=request.route_url('party'))
# prepare ticket URL with email & code
# 'https://events.c3s.cc/ci/p1402/' + _ticket.email + _ticket.email_confirm_code
# 'https://192.168.2.128:6544/ci/p1402/' + _ticket.email + _ticket.email_confirm_code
_url = request.registry.settings[
'c3spartyticketing.url'] + '/ci/p1402/' + _ticket.email_confirm_code
# return a pdf file
pdf_file = make_qr_code_pdf(_ticket, _url)
response = Response(content_type='application/pdf')
pdf_file.seek(0) # rewind to beginning
response.app_iter = open(pdf_file.name, "r")
return response