当前位置: 首页>>代码示例>>Python>>正文


Python Response.content_disposition方法代码示例

本文整理汇总了Python中pyramid.response.Response.content_disposition方法的典型用法代码示例。如果您正苦于以下问题:Python Response.content_disposition方法的具体用法?Python Response.content_disposition怎么用?Python Response.content_disposition使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyramid.response.Response的用法示例。


在下文中一共展示了Response.content_disposition方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: export

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [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
开发者ID:hermes-jr,项目名称:npui,代码行数:52,代码来源:csv.py

示例2: download_roster

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
    def download_roster(self):
        fieldnames = [
            'last_name', 'first_name', 'grade', 'school', 'experience',
            'tourneys', 'emails', 'guardian1_name', 'guardian1_emails']
        output = StringIO()
        writer = DictWriter(output, fieldnames=fieldnames)
        headers = dict((n, n) for n in fieldnames)
        writer.writerow(headers)
        for player in self.context.players():

            g1 = player.guardians()[0]
            g1_last_name = g1.last_name
            g1_first_name = g1.first_name
            g1_title = g1.title
            g1_emails = ','.join(g1.emails)

            writer.writerow(dict(
                last_name=player.last_name,
                first_name=player.first_name,
                grade=player.props['grade'],
                school=player.props['school'],
                experience=player.props['years_experience'],
                tourneys='/'.join(player.tourneys()),
                emails=', '.join(player.emails),
                guardian1_name=g1_title,
                guardian1_emails=g1_emails
            ))

        fn = self.context.__name__ + '-roster.csv'
        res = Response(content_type='text/csv', )
        res.content_disposition = 'attachment;filename=%s' % fn
        res.body = output.getvalue()

        return res
开发者ID:reebalazs,项目名称:fastbreak,代码行数:36,代码来源:views.py

示例3: post

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
    def post(self):
        rows = self.session.query('cid', 'cname', 'uid', 'uname', 'date', 'time').from_statement("""
        SELECT c.id as cid, c.name as cname, u.id as uid, u.name as uname, date_trunc('month', t.date) as date, SUM(t.time) as time
        FROM time_entry t, project p, client c, "user" u
        WHERE t.project_id = p.id AND
              p.client_id = c.id AND
              t.user_id = u.id AND
              t.deleted = false
        GROUP BY c.id, c.name, u.id, u.name, date_trunc('month', t.date)
        ORDER BY date_trunc('month', t.date)
        """).all()

        monthly = h.groupby(rows, lambda row: (row[2], row[-2]), lambda row: row[5])

        rows = [(
            row[1],
            row[3],
            row[5],
            row[4].strftime('%Y-%m-%d'),
            sum(monthly[row[2], row[-2]]),
        ) for row in rows]


        stream = self._to_excel(rows)

        response = Response(
            content_type='application/vnd.ms-excel',
            app_iter=stream,
        )
        response.headers['Cache-Control'] = 'no-cache'
        response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime('%d-%m-%Y--%H-%M-%S')

        return response
开发者ID:adamgr,项目名称:intranet,代码行数:35,代码来源:client.py

示例4: backups_export

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
def backups_export(request):
    passwords = get_user_passwords(request.db, request.user)
    data = compress(passwords)
    response = Response(body=data, content_type='application/yith-library')
    today = datetime.date.today()
    filename = get_backup_filename(today)
    response.content_disposition = 'attachment; filename=%s' % filename
    return response
开发者ID:srus,项目名称:yith-library-server,代码行数:10,代码来源:views.py

示例5: dump_entries_to_excel

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
def dump_entries_to_excel(entries, group_by, bigger_than):
    wbk = xlwt.Workbook()
    sheet = wbk.add_sheet("Hours")

    heading_xf = xlwt.easyxf("font: bold on; align: wrap on, vert centre, horiz center")
    headings = ("Client", "Project", "Ticket id", "Employee", "Description", "Date", "Time")
    headings_width = (x * 256 for x in (20, 30, 10, 40, 100, 12, 10))
    for colx, value in enumerate(headings):
        sheet.write(0, colx, value, heading_xf)
    for i, width in enumerate(headings_width):
        sheet.col(i).width = width

    sheet.set_panes_frozen(True)
    sheet.set_horz_split_pos(1)
    sheet.set_remove_splits(True)

    rows, asum = ExcelRow.from_ordered_data(entries, group_by, bigger_than)
    for j, row in enumerate(rows):
        row = row.pprint_row()
        for i, cell in enumerate(row):
            sheet.write(j + 1, i, *cell)

    file_path = "/tmp/tmp.xls"
    wbk.save(file_path)

    file = open(file_path, "rb")
    response = Response(content_type="application/vnd.ms-excel", app_iter=file)
    response.headers["Cache-Control"] = "no-cache"
    response.content_disposition = 'attachment; filename="report-%s.xls"' % datetime.datetime.now().strftime(
        "%d-%m-%Y--%H-%M-%S"
    )

    return file, response
开发者ID:kalek,项目名称:intranet,代码行数:35,代码来源:times.py

示例6: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
    def __call__(self):

                # # find the filename, css files, and format they wanted
                # filename = params['filename'] || 'RegionReport'
                # format = params['format'] || 'html'
                # css_to_include = (params['css'] && params['css'].split(',')) || []

        # grab some params
        filename = self.request.params.get('filename', 'RegionReport')
        css_inclusions = self.request.params.get('css', '')
        css_inclusions = css_inclusions.split(',')

        # start our response
        response = Response()
        # use this to write body content to (better than a giant memory-hogging string)
        body = response.body_file

        # tell the client this is a downloadable html file
        response.content_type='application/octet-stream'
        response.content_disposition='attachment; filename="' + filename + '.html"'
        response.headers['Content-Desciption'] = 'File Transfer' # unnecessary?

        # don't cache this file
        response.cache_expires(0) # sets various cache headers

        # now start filling out the body
        body.write("<html><head>\n")

        # add in the css they wanted
        for css in css_inclusions:
            # skip a blank css file (from splitting a blank string, for example)
            if len(css) == 0:
                continue
            # throw away path in case we're being hacked
            css_file = os.path.join(
                os.path.dirname(__file__),
                '..', 'static', 'css',
                # also replace extension with .css coz SECURITAY
                os.path.splitext(os.path.basename(css))[0] + '.css'
            )
            css_content = ''
            try:
                with file(css_file) as f:
                    css_content = f.read()
            except IOError:
                css_content = '/* could not load "' + cgi.escape(css, True) + '" */'

            body.write("<style>" + css_content + "</style>\n")

        content = self.request.params.get('content', '(no content was supplied)')
        content = content.replace(
            '<img src="/',
            '<img src="' + self.request.route_url('home')
        )

        body.write("</head><body><div id='report'>\n")
        body.write(content)
        body.write("\n</div></body></html>\n")

        return response
开发者ID:DanielBaird,项目名称:CliMAS-Next-Generation,代码行数:62,代码来源:reflectorview.py

示例7: get_reporting_instance_usage_file

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
 def get_reporting_instance_usage_file(self):
     conn = self.get_connection(conn_type='ec2reports')
     if not self.is_csrf_valid():
         return JSONResponse(status=400, message="missing CSRF token")
     granularity = self.request.params.get('granularity')
     group_by = self.request.params.get('groupBy')
     dates = self.dates_from_params(self.request.params)
     filters = self.request.params.get('filters') or '[]'
     filters = json.loads(filters)
     with boto_error_handler(self.request):
         # use "ViewInstanceUsageReport" call to fetch usage information
         ret = conn.view_instance_usage_report(
             dates.from_date, dates.to_date, filters, group_by, report_granularity=granularity
         )
         filename = 'EucalyptusInstanceUsage-{0}-{1}-{2}.csv'.format(
             self.request.session.get('account'),
             dates.from_date,
             dates.to_date
         )
         response = Response(content_type='text/csv')
         response.text = ret.get('usageReport')
         response.content_disposition = 'attachment; filename="{name}"'.format(name=filename)
         response.cache_control = 'no-store'
         response.pragma = 'no-cache'
         return response
开发者ID:,项目名称:,代码行数:27,代码来源:

示例8: translation_template

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [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
开发者ID:AmadeusITGroup,项目名称:oscad2,代码行数:9,代码来源:views.py

示例9: image

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
    def image(self, subpath=None):
        """Return the image in a specific scale, either inline
        (default) or as attachment.

        :param subpath: [<image_scale>]/download] (optional).
                        When 'download' is the last element in subpath,
                        the image is served with a 'Content-Disposition:
                        attachment' header.  <image_scale> has to be one of the
                        predefined image_scales - either from the defaults in
                        this module or one set with a
                        kotti.image_scales.<scale_name> in your app config ini
                        file.
        :type subpath: str

        :result: complete response object
        :rtype: pyramid.response.Response
        """

        if subpath is None:
            subpath = self.request.subpath

        width, height = (None, None)
        subpath = list(subpath)

        if (len(subpath) > 0) and (subpath[-1] == "download"):
            disposition = "attachment"
            subpath.pop()
        else:
            disposition = "inline"

        if len(subpath) == 1:
            scale = subpath[0]
            if scale in image_scales:
                # /path/to/image/scale/thumb
                width, height = image_scales[scale]

        if not (width and height):
            return self.request.uploaded_file_response(
                self.context.data, disposition)

        image, format, size = scaleImage(self.context.data.file.read(),
                                         width=width,
                                         height=height,
                                         direction="thumb")
        res = Response(
            headerlist=[
                ('Content-Disposition', '{0};filename="{1}"'.format(
                    disposition,
                    self.context.filename.encode('ascii', 'ignore'))),
                ('Content-Length', str(len(image))),
                ('Content-Type', str(self.context.mimetype)),
            ],
            body=image,
        )
        res.content_disposition = rfc6266.build_header(
            self.context.filename, disposition=disposition,
            filename_compat=unidecode(self.context.filename))

        return res
开发者ID:Kotti,项目名称:kotti_image,代码行数:61,代码来源:__init__.py

示例10: csv_download

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
def csv_download(request):
    """ CSV Download of vocabulary """
    context = get_global_store()[request.matchdict['id']]
    retval = Response(context.export_as_csv())
    retval.content_disposition = 'attachment; filename="%s.csv"' % \
        request.context.__name__
    retval.content_type = 'application/octet-stream'
    return retval
开发者ID:starzel,项目名称:vdexeditor,代码行数:10,代码来源:vdex_editor.py

示例11: download_wiki_archive

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
 def download_wiki_archive(self):
     archiver = WikiArchiver(self.request.db)
     archiver.create_new_zipfile()
     archive = archiver.archive_pages()
     content_type = 'application/zip'
     r = Response(content_type=content_type, body=archive)
     r.content_disposition = 'attachment; filename="tutwiki-archive.zip"'
     self.response = r
开发者ID:umeboshi2,项目名称:trumpet.history,代码行数:10,代码来源:sitetext.py

示例12: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [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
开发者ID:,项目名称:,代码行数:10,代码来源:

示例13: _make_response

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
def _make_response(content, content_type, status, file_name=None):
    """
    Custom response function that is called by pyexcel-webio
    """
    response = Response(content, content_type=content_type, status=status)
    if file_name:
        response.content_disposition = "attachment; filename=%s" % (file_name)
    return response
开发者ID:mromero107,项目名称:pyramid-excel,代码行数:10,代码来源:__init__.py

示例14: export_document

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
 def export_document(self):
     id = self.request.matchdict['id']
     id = datetime.strptime(id, dt_isoformat)
     doc = self.sdm.get(id)
     r = Response(content_type='application/pdf',
                  body=doc.file.content)
     filename = doc.name
     r.content_disposition = 'attachment; filename="%s"' % filename
     self.response = r
开发者ID:umeboshi2,项目名称:mslemon,代码行数:11,代码来源:pdfscans.py

示例15: job_preset

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import content_disposition [as 别名]
def job_preset(request):
    id = request.matchdict['job']
    session = DBSession()
    job = session.query(Job).get(id)
    response = Response()
    response.text = job.josm_preset
    response.content_disposition = 'attachment; filename=hotosm_tasking_manager_job_%s.xml' % job.id
    response.content_type = 'application/x-josm-preset'
    return response
开发者ID:Bulathge,项目名称:osm-tasking-manager,代码行数:11,代码来源:jobs.py


注:本文中的pyramid.response.Response.content_disposition方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。