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


Python Response.headers['Content-Disposition']方法代码示例

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


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

示例1: downloadfile

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
    def downloadfile(self):
        request = self.request

        filename = request.matchdict.get('filename')

        if not filename.endswith('.xml.zip'):
            raise HTTPNotFound()

        if filename == 'latest.xml.zip':
            try:
                filename = next(self._get_files())[1]
            except StopIteration:
                raise HTTPNotFound()

        # this should not happend because the routing engine will not match, but lets be sure
        if any(x in filename for x in bad_filename_contents):
            raise HTTPNotFound()

        fullpath = os.path.join(const.publish_dir, filename)

        relativepath = os.path.relpath(fullpath, const.publish_dir)

        if any(x in relativepath for x in bad_filename_contents):
            raise HTTPNotFound()

        xmlfile = open(fullpath, 'rb')
        res = Response(content_type='application/zip', app_iter=xmlfile)
        res.headers['Content-Disposition'] = 'attachment;filename=%s' % filename
        return res
开发者ID:OpenCIOC,项目名称:communityrepository,代码行数:31,代码来源:downloads.py

示例2: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
	def __call__(self):
		request = self.request
		user = request.user

		if not user:
			return make_401_error(u'Access Denied')

		if 'airsexport' not in user.cic.ExternalAPIs:
			return make_401_error(u'Insufficient Permissions')

		model_state = modelstate.ModelState(request)
		model_state.schema = AIRSExportOptionsSchema()
		model_state.form.method = None

		if not model_state.validate():
			if model_state.is_error('DST'):
				msg = u"Invalid Distribution"
			elif model_state.is_error("version"):
				msg = u"Invalid Version"
			else:
				msg = u"An unknown error occurred."

				log.error('AIRS Export Errors: %s: %s', msg, model_state.form.errors)
			return make_internal_server_error(msg)

		res = Response(content_type='application/zip', charset=None)
		res.app_iter, res.length = _zip_stream(request, model_state)

		res.headers['Content-Disposition'] = 'attachment;filename=Export.zip'
		return res
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:32,代码来源:airs.py

示例3: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [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
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:30,代码来源:pull.py

示例4: serve

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
 def serve(spec):
     """Resolve the asset ``spec`` to a file path and return a static
       file response that serves it. If the file isn't found, return
       a 404.
     """
     
     # Resolve the spec to a url.
     url = request.static_url(spec)
     if url.startswith('//'):
         url = 'https:' + url
     
     # Download the url.
     r = requests.get(url)
     if r.status_code != requests.codes.ok:
         msg = not_found_msg if r.status_code == 404 else err_message
         return not_found(explanation=msg)
     
     # Return the file response.
     filename = spec.split('/')[-1]
     disposition = 'attachment; filename="{0}"'.format(filename)
     mime_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
     response = Response(content_type=mime_type)
     response.headers['Content-Disposition'] = disposition
     response.body = r.content
     return response
开发者ID:andrecp,项目名称:pyramid_weblayer,代码行数:27,代码来源:serve.py

示例5: gb_all_nicks_view

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
def gb_all_nicks_view(request):
    tf = tempfile.NamedTemporaryFile(prefix='genbank_export_nick_%s' % request.job.key,
                                     suffix='.gb', delete=True)
    tf.write(genbank.all_nicks_to_GB(request.job.id))
    tf.seek(0)
    response = Response(content_type='text/plain')
    response.app_iter = tf
    response.headers['Content-Disposition'] = ("attachment; filename=all_nickases.gb")

    return response
开发者ID:yinqingl,项目名称:zlab_crisprtool,代码行数:12,代码来源:views_export.py

示例6: get

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
    def get(self):
        request = self.request
        context = self.context
        adapter = request.registry.queryMultiAdapter(
            (context, request),
            IEditable
            )
        if adapter is None:
            return HTTPNotFound()
        body, mimetype = adapter.get()
        headers = {}
        headers['url'] = request.current_route_url()
        headers['meta_type'] = str(request.registry.content.typeof(context))
        headers['title'] = context.__name__ or ''
        headers['content_type'] = mimetype
        headers['cookie'] = request.environ.get('HTTP_COOKIE', '')
        headers['borrow_lock'] = str(
            self.could_lock_resource(context, request.user) and 1 or 0
            )
        locks = self.discover_resource_locks(context)
        if locks:
            lock = locks[0]
            headers['lock-token'] = lock.__name__

        headerlist = ['%s:%s\n' % (k, v) for k, v in sorted(headers.items())]
        headerlist.insert(0, 'application:zopeedit\n') 
        # Rationale for inserting "application:zopeedit" at position zero in
        # file: it can be used for desktop environment magic file detection.
        #
        # The browser's content-type is ignored in systems like Chromium, which
        # delegate to xdg-open to figure out the application to open.  xdg-open
        # isn't provided the browser content-type at all, and dead reckons
        # using the shared mime info provided by the OS.  Under normal
        # circumstances, the .zem extension will be the trigger, but under
        # custom circumstances where the .zem extension is not used,
        # magic can be used to determine the content type.
        #
        # The value of "application:zopeedit" is not used by the client at all,
        # but it is compatible with the format expected by the client.
        headerlist = [x.encode('utf-8') for x in headerlist]
        app_iter = itertools.chain(headerlist, (b'\n',), body)
        response = Response(
            app_iter=app_iter,
            content_type='application/x-zope-edit'
            )
        disp = 'attachment'
        filename = '%s.zem' % self.context.__name__
        # use RFC2047 MIME encoding for filename* value
        mencoded = Header(filename, 'utf-8').encode()
        urlencoded = url_quote(filename)
        disp += '; filename*="%s"' % mencoded
        disp += '; filename="%s"' % urlencoded
        response.headers['Content-Disposition'] = disp
        return response
开发者ID:Pylons,项目名称:sdexternaledit,代码行数:56,代码来源:__init__.py

示例7: download

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
def download(model, request):
    check_submitter_access(model, request)
    a_type = model.attrs['attachment_type']
    payload = model.attrs['payload']
    response = Response()
    if a_type == 'text':
        response.text = html_2_text(payload)
        response.headers['Content-Type'] = 'text/plain'
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}.txt'.format(model.name)
    elif a_type == 'file':
        payload = pickle.loads(payload)
        file_data = payload['file']
        file_data.seek(0)
        response.body = file_data.read()
        response.headers['Content-Type'] = payload['mimetype']
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}'.format(
                payload['filename'].encode('utf-8'))
    elif a_type == 'image':
        payload = pickle.loads(payload)
        scale = request.params.get('scale')
        filename = payload['filename']
        if scale:
            image_data = payload['scales'][scale]
            filename = '{0}_{1}.{2}'.format(
                filename[:filename.rfind('.')], scale,
                filename[filename.rfind('.') + 1:])
        else:
            image_data = payload['image']
        image_data.seek(0)
        response.body = image_data.read()
        response.headers['Content-Type'] = payload['mimetype']
        response.headers['Content-Disposition'] = \
            'attachment;filename={0}'.format(filename)
    return response
开发者ID:,项目名称:,代码行数:38,代码来源:

示例8: csv_all_guides_view

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
def csv_all_guides_view(request):
    tf = tempfile.NamedTemporaryFile(prefix='csv_export_all_guides_%s' % request.job.key,
                                     suffix='.csv', delete=True)
        # this is where I usually put stuff in the file


    job = request.job

    tf.write(genbank.all_spacers_to_CSV(job))
    tf.seek(0)

    response = Response(content_type='application/csv')
    response.app_iter = tf
    response.headers['Content-Disposition'] = ("attachment; filename=offtargets.csv")
    return response
开发者ID:yinqingl,项目名称:zlab_crisprtool,代码行数:17,代码来源:views_export.py

示例9: csv_one_spacer_view

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
def csv_one_spacer_view(request):
    tf = tempfile.NamedTemporaryFile(prefix='csv_export_one_spacer_%s' % request.job.key,
                                     suffix='.csv', delete=True)
        # this is where I usually put stuff in the file


    job = request.job
    spacer = Session.query(Spacer).get(request.matchdict["spacerid"])

    tf.write(genbank.one_spacer_to_CSV(job,spacer))
    tf.seek(0)

    response = Response(content_type='application/csv')
    response.app_iter = tf
    response.headers['Content-Disposition'] = ("attachment; filename=offtargets.csv")
    return response
开发者ID:yinqingl,项目名称:zlab_crisprtool,代码行数:18,代码来源:views_export.py

示例10: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
	def __call__(self):
		request = self.request
		user = request.user

		if not user:
			return make_401_error('Access Denied', 'Export')

		if 'clbcexport' not in user.cic.ExternalAPIs:
			return make_401_error('Insufficient Permissions', 'Export')


		with request.connmgr.get_connection('admin') as conn:
			cursor = conn.execute('SELECT CAST(Vendor AS nvarchar(max)) AS Vendor FROM CLBC_VENDOR_EXPORT')
			
			data = [x[0] for x in cursor.fetchall()]

			cursor.close()

		data.insert(0, u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<Vendors>')
		data.append(u'</Vendors>')
		data = u'\r\n'.join(data).encode('utf8')

		file = tempfile.TemporaryFile()
		zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED)
		zip.writestr('export.xml', data)
		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
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:38,代码来源:clbcexport.py

示例11: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
	def __call__(self):
		request = self.request
		user = request.user

		if not user.vol.SuperUser:
			self._security_failure()

		sql = 'SELECT * FROM VOL_SHARE_VIEW_EN vo WHERE ' + request.viewdata.WhereClauseVOL.replace('NON_PUBLIC', 'XNP').replace('DELETION_DATE', 'XDEL').replace('UPDATE_DATE', 'XUPD').replace('vod.', 'vo.').replace('vo.MemberID=1', '1=1')

		log.debug('SQL: %s', sql)

		log.debug('sql: %s', sql)
		data = [u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<ROOT xmlns="urn:ciocshare-schema-vol">'.encode('utf8')]
		with request.connmgr.get_connection('admin') as conn:
			cursor = conn.execute(sql)

			data.extend(u''.join([u'<RECORD VNUM="', unicode(x.VNUM), u'" RECORD_OWNER="', unicode(x.RECORD_OWNER), u'" HAS_ENGLISH="', unicode(x.HAS_ENGLISH), u'" HAS_FRENCH="', unicode(x.HAS_FRENCH), u'">'] + map(unicode, x[7:]) + [u'</RECORD>']).encode('utf8') for x in cursor.fetchall())

			cursor.close()

		data.append(u'</ROOT>'.encode('utf8'))
		data = u'\r\n'.encode('utf8').join(data)

		file = tempfile.TemporaryFile()
		zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED)
		zip.writestr('export.xml', data)
		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
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:38,代码来源:export.py

示例12: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
	def __call__(self):
		request = self.request
		user = request.user

		if not user:
			return make_401_error(u'Access Denied')

		if 'o211export' not in user.cic.ExternalAPIs:
			return make_401_error(u'Insufficient Permissions')

		model_state = modelstate.ModelState(request)
		model_state.schema = O211ExportOptionsSchema()
		model_state.form.method = None

		if not model_state.validate():
			if model_state.is_error('date'):
				msg = u"Invalid date"
			elif model_state.is_error('feed'):
				msg = u"Invalid feed."
			else:
				msg = u"An unknown error occurred."

			return make_internal_server_error(msg)

		feed = model_state.value('feed')
		date = model_state.value('date')

		args = []
		if not feed:
			sql = ['SELECT CAST(record AS nvarchar(max)) AS record FROM O211SC_RECORD_EXPORT btd']

			if request.viewdata.cic.PB_ID:
				args.append(request.viewdata.cic.PB_ID)
				sql.append(" INNER JOIN CIC_BT_PB pb ON btd.NUM=pb.NUM AND pb.PB_ID=?")

			if date:
				args.append(date)
				sql.append('''
						WHERE EXISTS (SELECT * FROM GBL_BaseTable_History h
							INNER JOIN GBL_FieldOption fo
									ON h.FieldID=fo.FieldID
								WHERE h.NUM=btd.NUM AND h.LangID=btd.LangID
									AND h.MODIFIED_DATE >= ?
									AND fo.FieldName IN ('ORG_LEVEL_1','ORG_LEVEL_2','ORG_LEVEL_3','ORG_LEVEL_4','ORG_LEVEL_5',
									'ACCESSIBILITY','AFTER_HRS_PHONE','ALT_ORG','APPLICATION','AREAS_SERVED',
									'CONTACT_1','CONTACT_2','EXEC_1','EXEC_2','VOLCONTACT',
									'CRISIS_PHONE','ELIGIBILITY','E_MAIL','FAX','FORMER_ORG','HOURS','INTERSECTION',
									'LANGUAGES','LOCATED_IN_CM','MAIL_ADDRESS','PUBLIC_COMMENTS',
									'OFFICE_PHONE','SERVICE_LEVEL','RECORD_OWNER','DESCRIPTION','SITE_ADDRESS','SUBJECTS',
									'TDD_PHONE','TOLL_FREE_PHONE','WWW_ADDRESS', 'UPDATE_DATE', 'NUM', 'SUBMIT_CHANGES_TO', 'SOURCE_DB')
							)''')

			sql = ' '.join(sql)

		elif feed == 'recordids':
			sql = ['SELECT CAST((SELECT id=btd.NUM, language=btd.Culture FROM O211SC_RECORD_EXPORT btd']
			if request.viewdata.cic.PB_ID:
				args.append(request.viewdata.cic.PB_ID)
				sql.append(" INNER JOIN CIC_BT_PB pb ON btd.NUM=pb.NUM AND pb.PB_ID=?")

			sql.append("FOR XML PATH('record'), TYPE) AS nvarchar(max)) AS data ")

			sql = ' '.join(sql)

		elif feed == 'taxonomy':
			sql = "SELECT CAST(record AS nvarchar(max)) AS record from O211SC_TAXONOMY_EXPORT"

		elif feed == 'community':
			sql = "SELECT CAST(record AS nvarchar(max)) AS record from O211SC_COMMUNITY_EXPORT"

		else:
			#XXX we should never get here
			return make_internal_server_error(u'Invalid feed.')

		log.debug('sql: %s', sql)
		with request.connmgr.get_connection('admin') as conn:
			cursor = conn.execute(sql, *args)

			data = [x[0] for x in cursor.fetchall()]

			cursor.close()

		data.insert(0, u'<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<records>')
		data.append(u'</records>')
		data = u'\r\n'.join(data).encode('utf8')

		file = tempfile.TemporaryFile()
		zip = zipfile.ZipFile(file, 'w', zipfile.ZIP_DEFLATED)
		zip.writestr('export.xml', data)
		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
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:101,代码来源:o211export.py

示例13: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [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
开发者ID:OpenCIOC,项目名称:onlineresources,代码行数:78,代码来源:download.py

示例14: convertToCSV2

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]
def convertToCSV2(context, request):

    session = request.db

    students = json.loads(request.POST['json_data'])

    #students = request.json_body['students']

    fp = ''

    for el in students:
        fp += el['firstname']+','+el['lastname']+','+el['ssid']+','+el['school']+','+el['grade']+','+el['teacher']

        this_item = el['universal_tools']
        this_list = (
                'Breaks', 
                'Calculator', 
                'Digital Notes' , 
                'English Dictionary', 
                'English Glossary', 
                'Expandable Passages', 
                'Global Notes', 
                'Highlighter', 
                'Keyboard Navigation', 
                'Mark for Review', 
                'Math Tools', 
                'Spell Check', 
                'Strikethrough', 
                'Writing Tools', 
                'Zoom'
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'



        this_item = el['universal_tools_ne']
        this_list = (
                'Breaks', 
                'Scratch Paper', 
                'Thesaurus' , 
                'English Dictionary', 
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'


        this_item = el['ident_student_needs']
        this_list = (
                'Individualized Education Program', 
                '504 Plan', 
                'Educator(s) Recommendation', 
                )
        for el2 in this_list:
            x = list(filter(lambda x: x['text'] == el2, this_item))[0]
            if (x['select'] == True):
                fp += ','+x['text']
            else:
                fp += ',,'


        fp += '\n'

    response = Response(content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment; filename="data.csv"'
    response.charset = 'utf8'
    response.body = fp.encode(encoding='UTF-8',errors='strict')
    return response
开发者ID:SmarterApp,项目名称:ARI_Prototype,代码行数:78,代码来源:api.py

示例15: convertToCSV

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import headers['Content-Disposition'] [as 别名]

#.........这里部分代码省略.........
            if alt == None:
                raise TypeError
            non_accom += alt + ";"
        except (NameError, TypeError):
            pass
        # Calculator
        try:
            calc = el['accommodations']['5']['selected']['value']
            if calc == None:
                raise TypeError
            if calc == 'NEA_Calc (Math only)':
                calc = 'NEA_Calc'
            non_accom += calc + ";"
        except (NameError, TypeError):
            pass
        # Multiplication Table
        try:
            mult = el['accommodations']['6']['selected']['value']
            if mult == None:
                raise TypeError
            if multi == 'NEA_MT (Math only)':
                multi = 'NEA_MT'
            non_accom += multi + ";"
        except (NameError, TypeError):
            pass
        # Print on Demand
        #try:
        #    non_accom += el['accommodations']['1']['selected']['value'] + ";"
        #except (NameError, TypeError):
        #    pass
        # Read Aloud - *Read Aloud for ELA Reading Passages Grades 6-8 and 11
        try:
            read = el['accommodations']['4']['selected']['value']
            if read == None:
                raise TypeError
            if read == 'NEA_RA_Stimuli (ELA only)':
                read = 'NEA_RA_Stimuli'
            non_accom += read + ";"
        except (NameError, TypeError):
            pass
        # Scribe
        try:
            scribe = el['accommodations']['8']['selected']['value']
            if scibe == None:
                raise TypeError
            if scribe == 'NEA_SC_WritItems (ELA only)':
                scribe = 'NEA_SC_WritItems'
            non_accom += scribe + ";"
        except (NameError, TypeError):
            pass
        # Speech-to-text
        try:
            speech = el['accommodations']['7']['selected']['value']
            if speech == None:
                raise TypeError
            non_accom += speech + ";"
        except (NameError, TypeError):
            pass

        non_accom = non_accom.replace(';;', ';')
        data['NonEmbeddedAccommodations'].append(non_accom)


        try:
            data['Other'].append('')
        except (NameError, TypeError):
            data['Other'].append('')



    col_order = [
            'StudentIdentifier',
            'StateAbbreviation',
            'Subject',
            'AmericanSignLanguage',
            'ColorContrast',
            'ClosedCaptioning',
            'Language',
            'Masking',
            'PermissiveMode',
            'PrintOnDemand',
            'Zoom',
            'StreamlinedInterface',
            'TexttoSpeech',
            'Translation',
            'NonEmbeddedDesignatedSupports',
            'NonEmbeddedAccommodations',
            'Other',
        ]


    df = pd.DataFrame(data)
    df = df[col_order]

    
    response = Response(content_type='application/octet-stream')
    response.headers['Content-Disposition'] = 'attachment; filename="data.csv"'
    response.charset = 'utf8'
    response.body = df.to_csv(index=False).encode(encoding='UTF-8',errors='strict')
    return response
开发者ID:SmarterApp,项目名称:ARI_Prototype,代码行数:104,代码来源:api.py


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