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


Python Response.charset方法代码示例

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


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

示例1: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [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,代码来源:

示例2: view_export_locations

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
def view_export_locations(request):
    contents = ""
    for location in DBSession.query(ShippingLocation).all():
        contents += location.name + ';' + location.address + '\n'

    resp = Response()
    resp.charset = "utf-8"
    resp.text = contents
    resp.headerlist.append(("Content-Disposition", "attachment"))
    return resp
开发者ID:varesa,项目名称:shopify_shipping_calculator,代码行数:12,代码来源:views_data_locations.py

示例3: return_plain_data

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

    response = Response(content_type='application/html')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'

    return response
开发者ID:yeastgenome,项目名称:SGDFrontend,代码行数:12,代码来源:__init__.py

示例4: connector

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
def connector(request):
    # init connector and pass options
    root = request.registry.settings['pyramid_elfinder_root']
    options = {
        'root': os.path.abspath(root),
        'URL': request.registry.settings['pyramid_elfinder_url']
    }
    elf = elfinder.connector(options)

    # fetch only needed GET/POST parameters
    httpRequest = {}
    form = request.params
    for field in elf.httpAllowedParameters:
        if field in form:
            # Russian file names hack
            if field == 'name':
                httpRequest[field] = form.getone(field).encode('utf-8')

            elif field == 'targets[]':
                httpRequest[field] = form.getall(field)

            # handle CGI upload
            elif field == 'upload[]':
                upFiles = {}
                cgiUploadFiles = form.getall(field)
                for up in cgiUploadFiles:
                    if isinstance(up, FieldStorage):
                        # pack dict(filename: filedescriptor)
                        upFiles[up.filename.encode('utf-8')] = up.file
                httpRequest[field] = upFiles
            else:
                httpRequest[field] = form.getone(field)

    # run connector with parameters
    status, header, response = elf.run(httpRequest)

    # get connector output and print it out
    result = Response(status=status)
    try:
        del header['Connection']
    except Exception:
        pass
    result.headers = header
    result.charset = 'utf8'

    if response is not None and status == 200:
        # send file
        if 'file' in response and hasattr(response['file'], 'read'):
            result.body = response['file'].read()
            response['file'].close()
        # output json
        else:
            result.text = json.dumps(response)
    return result
开发者ID:uralbash,项目名称:pyramid_elfinder,代码行数:56,代码来源:views.py

示例5: set_download_file

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
def set_download_file(filename, content):
    
    response = Response(content_type='application/file')
    headers = response.headers
    if not response.charset:
        response.charset = 'utf8'
    response.text = content
    headers['Content-Type'] = 'text/plain'
    headers['Content-Disposition'] = str('attachment; filename=' + '"' + filename + '"')
    headers['Content-Description'] = 'File Transfer'
    return response
开发者ID:yeastgenome,项目名称:SGDFrontend,代码行数:13,代码来源:__init__.py

示例6: export

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
 def export(self):
     exch = Exchange(Base.metadata, 
                     ignlist=['cpu_types', 'machine_types', 'nic_types'])
     fp = StringIO.StringIO()
     exch.export_xml()
     exch.write_xml(fp)
     resp = Response()
     resp.headerlist=[('Content-Type', 'text/html; charset=UTF-8'),]
     resp.text=fp.getvalue()
     resp.content_disposition = 'attachment; filename="qtubes_export.xml"'
     resp.charset='utf-8'
     return resp
开发者ID:tty72,项目名称:qemu-tubes,代码行数:14,代码来源:views.py

示例7: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
 def __call__(self):
     check_update = True if self.request.GET.get('check_update', 'true') == 'true' else False
     package = self.context.__parent__.__parent__
     last_remote_version = Package.get_last_remote_version(self.proxy, package.name)
     if check_update:
         if not package.repository_is_up_to_date(last_remote_version):
             return not_found(self.request)
     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()
     return response
开发者ID:ldgeo,项目名称:papaye,代码行数:15,代码来源:simple.py

示例8: test_response_properties

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
def test_response_properties():
    root_response = Response(
        headers={"X-Some-Special-Header": "foobar"},
        body='{"myKey": 42}'
    )
    # these must be set for the "text" attribute of webob.Response to be
    # readable, and setting them in the constructor gets into a conflict
    # with the custom header argument
    root_response.content_type = "application/json"
    root_response.charset = 'utf8'
    response = PyramidSwaggerResponse(root_response)
    assert '{"myKey": 42}' == response.text
    assert "foobar" == response.headers["X-Some-Special-Header"]
    assert 'application/json' == response.content_type
开发者ID:ATRAN2,项目名称:pyramid_swagger,代码行数:16,代码来源:tween_test.py

示例9: export

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [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

示例10: view_export_products

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
def view_export_products(request):
    contents = ""
    for product in DBSession.query(Product).all():
        contents += product.handle + ';' + product.type + ';' + product.subtype + ';' + str(product.maara_per_lavametri) + ';' + str(product.km_raja)
        for location in product.locations:
            contents += ';' + str(location.name)
        contents += '\n'
#            ';'.join(product.locations) + '\n'

    resp = Response()
    resp.charset = "utf-8"
    resp.text = contents
    resp.headerlist.append(("Content-Disposition", "attachment"))
    return resp
开发者ID:varesa,项目名称:shopify_shipping_calculator,代码行数:16,代码来源:views_data_products.py

示例11: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
    def __call__(self, context=None, request=None, **kw):
        if self.path is None:
            inst = self.__get__()
            return inst(context=context, request=request, **kw)

        result = self.render(context=context, request=request, **kw)
        if isinstance(result, basestring):
            response = Response(body=result)
        else:
            response = Response(app_iter=result)
            response.content_length = os.path.getsize(self.path)

        content_type = self.content_type
        if content_type is None:
            content_type = type(self).content_type
        response.content_type = content_type
        response.charset = self.encoding
        return response
开发者ID:mmariani,项目名称:pyramid_skins,代码行数:20,代码来源:models.py

示例12: __call__

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]
    def __call__(self, context=None, request=None, **kw):
        if request is None:
            request = get_current_request()
        if self.path is None:
            registry = request.registry
            inst = registry.queryAdapter(request, ISkinObject, name=self.name)
            if inst is None:
                inst = registry.getUtility(ISkinObject, name=self.name)
            return inst(context=context, request=request, **kw)

        result = self.render(context=context, request=request, **kw)
        if isinstance(result, string_types):
            response = Response(body=result)
        else:
            response = Response(app_iter=result)
            response.content_length = os.path.getsize(self.path)

        content_type = self.content_type
        if content_type is None:
            content_type = type(self).content_type
        response.content_type = content_type
        response.charset = self.encoding
        return response
开发者ID:Pylons,项目名称:pyramid_skins,代码行数:25,代码来源:models.py

示例13: convertToCSV2

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [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

示例14: convertToCSV

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [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

示例15: convertToCSVLegacy

# 需要导入模块: from pyramid.response import Response [as 别名]
# 或者: from pyramid.response.Response import charset [as 别名]

#.........这里部分代码省略.........
        try:
            data['*Scribe (for ELA non-writing items and Math items)'].append(el['designated']['15']['selected']['value'])
        except (NameError, TypeError):
            data['*Scribe (for ELA non-writing items and Math items)'].append('')

        try:
            data['Separate Setting'].append(el['designated']['8']['selected']['value'])
        except (NameError, TypeError):
            data['Separate Setting'].append('')

        try:
            data['*Speech-to-text'].append(el['accommodations']['7']['selected']['value'])
        except (NameError, TypeError):
            data['*Speech-to-text'].append('')

        try:
            data['*Stacked Translations for Math'].append(el['designated']['12']['selected']['value'])
        except (NameError, TypeError):
            data['*Stacked Translations for Math'].append('')

        try:
            data['*Text-to-speech for ELA Reading Passages Grades 6-8 and 11'].append(el['accommodations']['3']['selected']['value'])
        except (NameError, TypeError):
            data['*Text-to-speech for ELA Reading Passages Grades 6-8 and 11'].append('')

        try:
            data['*Text-to-speech for Math and ELA Items'].append(el['designated']['3']['selected']['value'])
        except (NameError, TypeError):
            data['*Text-to-speech for Math and ELA Items'].append('')

        try:
            data['Translated Text Directions'].append(el['designated']['16']['selected']['value'])
        except (NameError, TypeError):
            data['Translated Text Directions'].append('')

        try:
            data['Translated Test Directions for Math'].append(el['designated']['10']['selected']['value'])
        except (NameError, TypeError):
            data['Translated Test Directions for Math'].append('')

        try:
            data['*Translation Glossaries for Math (ET) (EMBEDDED)'].append(el['designated']['11']['selected']['value'])
        except (NameError, TypeError):
            data['*Translation Glossaries for Math (ET) (EMBEDDED)'].append('')

        try:
            data['Translation Glossaries for Math (ET) (NON-EMBEDDED)'].append(el['designated']['14']['selected']['value'])
        except (NameError, TypeError):
            data['Translation Glossaries for Math (ET) (NON-EMBEDDED)'].append('')


    col_order = [
            'Student Last Name',
            'Student First Name',
            'SSID (consistent with TIDE)',
            'Grade',
            'Educator(s) completing ISAAP',
            'Teacher of Record',
            'School ID',
            'School Name',
            'Abacus',
            '*Alternate Response Options (including any external devices/assistive technologies)',
            'American Sign Language for ELA Listening and Math Items',
            'Bilingual Dictionary for ELA Full Writes (ET)',
            'Braille',
            'Calculator',
            'Closed Captioning for ELA Listening Items',
            'Color Contrast (EMBEDDED)',
            '*Color Contrast (NON-EMBEDDED)',
            'Color Overlays',
            '*Magnification',
            'Masking',
            'Multiplication Table',
            'Noise Buffers',
            '*Print on Demand',
            '*Read Aloud for ELA Reading Passages Grades 6-8 and 11',
            '*Read Aloud for Math and ELA Items',
            '*Scribe',
            '*Scribe (for ELA non-writing items and Math items)',
            'Separate Setting',
            '*Speech-to-text',
            '*Stacked Translations for Math',
            '*Text-to-speech for ELA Reading Passages Grades 6-8 and 11',
            '*Text-to-speech for Math and ELA Items',
            'Translated Text Directions',
            'Translated Test Directions for Math',
            '*Translation Glossaries for Math (ET) (EMBEDDED)',
            'Translation Glossaries for Math (ET) (NON-EMBEDDED)',
        ]


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