• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python acceptparse.Accept类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中webob.acceptparse.Accept的典型用法代码示例。如果您正苦于以下问题:Python Accept类的具体用法?Python Accept怎么用?Python Accept使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



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

示例1: test_best_match

def test_best_match():
    accept = Accept("text/html, foo/bar")
    assert accept.best_match(["text/html", "foo/bar"]) == "text/html"
    assert accept.best_match(["foo/bar", "text/html"]) == "foo/bar"
    assert accept.best_match([("foo/bar", 0.5), "text/html"]) == "text/html"
    assert accept.best_match([("foo/bar", 0.5), ("text/html", 0.4)]) == "foo/bar"
    assert_raises(ValueError, accept.best_match, ["text/*"])
开发者ID:ckey,项目名称:webob,代码行数:7,代码来源:test_acceptparse.py


示例2: generate_response

 def generate_response(self, environ, start_response):
     if self.content_length is not None:
         del self.content_length
     headerlist = list(self.headerlist)
     accept_value = environ.get('HTTP_ACCEPT', '')
     accept = Accept(accept_value)
     match = accept.best_match(['application/json', 'text/html',
                                'text/plain'], default_match='text/plain')
     if match == 'text/html':
         content_type = 'text/html'
         body = self.html_body(environ)
     elif match == 'application/json':
         content_type = 'application/json'
         body = self.json_body(environ)
     else:
         content_type = 'text/plain'
         body = self.plain_body(environ)
     extra_kw = {}
     if isinstance(body, text_type):
         extra_kw.update(charset='utf-8')
     resp = Response(body,
         status=self.status,
         headerlist=headerlist,
         content_type=content_type,
         **extra_kw
     )
     resp.content_type = content_type
     return resp(environ, start_response)
开发者ID:5m0k3r,项目名称:desarrollo_web_udp,代码行数:28,代码来源:exc.py


示例3: test_accept_match

def test_accept_match():
    accept = Accept('Content-Type', 'text/html')
    #FIXME: Accept._match should be standalone function _match that is
    # attached as Accept._match during Accept.__init__.
    assert accept._match('*', 'text/html')
    assert accept._match('text/html', 'text/html')
    assert accept._match('TEXT/HTML', 'text/html')
    assert not accept._match('foo/bar', 'text/html')
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:8,代码来源:test_acceptparse.py


示例4: test_best_match_with_complex_q

def test_best_match_with_complex_q():
    accept = Accept('text/html, foo/bar;q=0.55, baz/gort;q=0.59')
    assert accept.best_match(['text/html', 'foo/bar']) == 'text/html'
    accept = Accept('text/html;q=0.5, foo/bar;q=0.586, baz/gort;q=0.5966')
    assert "baz/gort;q=0.597" in str(accept)
    assert "foo/bar;q=0.586" in str(accept)
    assert "text/html;q=0.5" in str(accept)
    assert accept.best_match(['text/html', 'baz/gort']) == 'baz/gort'
开发者ID:B-Rich,项目名称:webob,代码行数:8,代码来源:test_acceptparse.py


示例5: test_best_match

def test_best_match():
    accept = Accept('Content-Type', 'text/html, foo/bar')
    assert accept.best_match(['text/html', 'foo/bar']) == 'text/html'
    assert accept.best_match(['foo/bar', 'text/html']) == 'foo/bar'
    assert accept.best_match([('foo/bar', 0.5),
                              'text/html']) == 'text/html'
    assert accept.best_match([('foo/bar', 0.5),
                              ('text/html', 0.4)]) == 'foo/bar'
    assert_raises(ValueError, accept.best_match, ['text/*'])
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:9,代码来源:test_acceptparse.py


示例6: lookup_template_engine

    def lookup_template_engine(self, tgl):
        """Return the template engine data.

        Provides a convenience method to get the proper engine,
        content_type, template, and exclude_names for a particular
        tg_format (which is pulled off of the request headers).

        """
        request = tgl.request
        response = tgl.response

        try:
            render_custom_format = request._render_custom_format[self.controller]
        except:
            render_custom_format = self.render_custom_format

        if render_custom_format:
            (content_type, engine, template, exclude_names, render_params
                ) = self.custom_engines[render_custom_format]
        else:
            if self.default_engine:
                content_type = self.default_engine
            elif self.engines:
                if request._response_type and request._response_type in self.engines:
                    accept_types = request._response_type
                else:
                    accept_types = request.headers.get('accept', '*/*')
                content_type = Accept(accept_types).best_match(self.engines_keys, self.engines_keys[0])
            else:
                content_type = 'text/html'

            # check for overridden content type from the controller call
            try:
                controller_content_type = response.headers['Content-Type']
                # make sure we handle content_types like 'text/html; charset=utf-8'
                content_type = controller_content_type.split(';')[0]
            except KeyError:
                pass

            # check for overridden templates
            try:
                cnt_override_mapping = request._override_mapping[self.controller]
                engine, template, exclude_names, render_params = cnt_override_mapping[content_type.split(";")[0]]
            except (AttributeError, KeyError):
                (engine, template, exclude_names, render_params
                    ) = self.engines.get(content_type, (None,) * 4)

        if 'charset' not in content_type and (content_type.startswith('text')
                or  content_type in ('application/xhtml+xml',
                        'application/xml', 'application/json')):
            content_type += '; charset=utf-8'

        return content_type, engine, template, exclude_names, render_params
开发者ID:984958198,项目名称:tg2,代码行数:53,代码来源:decorators.py


示例7: offer_sort_key

    def offer_sort_key(value):
        """
        (type_weight, params_weight)

        type_weight:
            - index of specific ``type/subtype`` in order list
            - ``max_weight * 2`` if no match is found

        params_weight:
            - index of specific ``type/subtype;params`` in order list
            - ``max_weight`` if not found
            - ``max_weight + 1`` if no params at all

        """
        parsed = Accept.parse_offer(value)

        type_w = find_order_index(
            parsed.type + '/' + parsed.subtype, max_weight
        )

        if parsed.params:
            param_w = find_order_index(value, max_weight)

        else:
            param_w = max_weight + 1

        return (type_w, param_w)
开发者ID:Pylons,项目名称:pyramid,代码行数:27,代码来源:predicates.py


示例8: concept

def concept(request, lccn):
    concept = get_object_or_404(m.Concept, lccn=lccn)
    host = request.get_host()

    accept = Accept('Accept', request.META.get('HTTP_ACCEPT', 'text/html'))
    best_match = accept.best_match(['text/html', 'application/rdf+xml']) 
    if best_match == 'application/rdf+xml':
        r = concept_rdf(request, lccn)
    else:
        alt_labels = concept.alternate_labels.all().order_by('text')
        broader = concept.broader.all().order_by('pref_label')
        extra_broader = concept.extra_broader()
        narrower = concept.narrower.all().order_by('pref_label')
        related = concept.related.all().order_by('pref_label')
        r = render_to_response('concept.html', dictionary=locals(), 
                               context_instance=RequestContext(request))
    # let downstream caches know that the resonse can vary depending 
    # on the Accept header that the client sent 
    r['Vary'] = 'Accept' 
    return r
开发者ID:edsu,项目名称:id,代码行数:20,代码来源:views.py


示例9: test_best_matches

def test_best_matches():
    accept = Accept('Content-Type', 'text/html, foo/bar')
    assert accept.best_matches() == ['text/html', 'foo/bar']
    accept = Accept('Content-Type', 'text/html, foo/bar;q=0.5')
    assert accept.best_matches() == ['text/html', 'foo/bar']
    accept = Accept('Content-Type', 'text/html;q=0.5, foo/bar')
    assert accept.best_matches() == ['foo/bar', 'text/html']
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:7,代码来源:test_acceptparse.py


示例10: from_settings

    def from_settings(cls, settings):
        """Create a new instance based on the `settings` dict.

        The locales supported by the application are read from the
        "locales" key. The format of the value is the same as that of
        the Accept-Language header, i.e.:

          <locale1>;q=<q1>,<locale2>;q=<q2>,...

        The q-values indicate the quality of the locale, but are
        optional.
        """
        locales = list(Accept.parse(settings.get("locales", "")))
        return cls(locales)
开发者ID:MarcSchmitzer,项目名称:pylf,代码行数:14,代码来源:i18n.py


示例11: test_accept_match_lang

def test_accept_match_lang():
    accept = Accept('Accept-Language', 'da, en-gb;q=0.8, en;q=0.7')
    #FIXME: Accept._match_lang should be standalone function _match_lang
    # that is attached as Accept._match during Accept.__init__.
    assert accept._match('*', 'da')
    assert accept._match('da', 'DA')
    assert accept._match('en', 'en-gb')
    assert accept._match('en-gb', 'en-gb')
    assert not accept._match('en-gb', 'fr-fr')
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:9,代码来源:test_acceptparse.py


示例12: process

    def process(self, environ, start_response):
        self._begin = datetime.datetime.now()
        if self._debug:
            open("/tmp/cog_sql", "w")
        try:
            self.clear()
            self._environ = environ
#            open("/tmp/cog_tmp_xxx", "w").write("{}".format(environ))
            self._script_name = self._environ.get('SCRIPT_NAME', '')
            self._server_name = self._environ['HTTP_HOST']
            self._url_scheme = self._environ['wsgi.url_scheme']
            self._url = "{}://{}{}".format(
                self._url_scheme, self._server_name, self._script_name)
            self._path_info = self._environ['PATH_INFO'].lower()
            alnum = "[a-z0-9]{4}"
            oid_pattern = '^/{}{}-{}-{}-{}-{}{}{}$'.format(*(alnum,)*8)
            if re.match(oid_pattern, self._path_info):
                obj = self.db.get_elt_by_oid(self._path_info[1:])
                self.add_json_res({'#page_ref':self.get_page_ref()})
                self.direct_obj_ref = obj.w3display
            self.load_site()
            self.__request = Request(environ)
            self.__lang = Accept(str(self.__request.accept_language))
            self.i18n = gettext.translation(
                'messages', '/usr/share/collorg/locale',
                [self.__lang.best_match(('en', 'fr', 'fr-FR')) or 'en'])
            if WebController.__static_body is None:
                WebController.__tags = self.__get_tags()
                WebController.__static_body = self.__get_static_body()
            self.__response = Response()
            self.__reset()
            if not(self._cog_method is None and '#page_ref' in self._json_res):
                    self.add_json_res({'#page_ref':self.get_page_ref()})
            self.__response.unicode_body = self._unicode(self.__exec())
            if(self.__response.content_type != 'text/html' or
                self.__response.status_int != 200):
                # Not an HTML response, we don't want to
                # do anything to it
                return self.__response(environ, start_response)
            # Make sure the content isn't gzipped:
            self.__response.decode_content()
            return self.__response(environ, start_response)
        except Exception as err:
            if self.db._cog_params['debug']:
                response = Response()
                response.unicode_body = self._unicode(err)
                return response(environ, start_response)
            if raise_error:
                raise err
开发者ID:joel-m,项目名称:collorg,代码行数:49,代码来源:web.py


示例13: test_first_match

def test_first_match():
    accept = Accept('Content-Type', 'text/html, foo/bar')
    assert accept.first_match(['text/html', 'foo/bar']) == 'text/html'
    assert accept.first_match(['foo/bar', 'text/html']) == 'foo/bar'
    assert accept.first_match(['xxx/xxx', 'text/html']) == 'text/html'
    assert accept.first_match(['xxx/xxx']) == 'xxx/xxx'
    assert accept.first_match([None, 'text/html']) is None
    assert accept.first_match(['text/html', None]) == 'text/html'
    assert accept.first_match(['foo/bar', None]) == 'foo/bar'
    assert_raises(ValueError, accept.first_match, [])
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:10,代码来源:test_acceptparse.py


示例14: test_best_match

def test_best_match():
    accept = Accept('text/html, foo/bar')
    assert accept.best_match(['text/html', 'foo/bar']) == 'text/html'
    assert accept.best_match(['foo/bar', 'text/html']) == 'foo/bar'
    assert accept.best_match([('foo/bar', 0.5),
                              'text/html']) == 'text/html'
    assert accept.best_match([('foo/bar', 0.5),
                              ('text/html', 0.4)]) == 'foo/bar'
    with pytest.raises(ValueError):
        accept.best_match(['text/*'])
开发者ID:adamchainz,项目名称:webob,代码行数:10,代码来源:test_acceptparse.py


示例15: test_best_matches_with_fallback

def test_best_matches_with_fallback():
    accept = Accept('Content-Type', 'text/html, foo/bar')
    assert accept.best_matches('xxx/yyy') == ['text/html',
                                              'foo/bar',
                                              'xxx/yyy']
    accept = Accept('Content-Type', 'text/html;q=0.5, foo/bar')
    assert accept.best_matches('xxx/yyy') == ['foo/bar',
                                              'text/html',
                                              'xxx/yyy']
    assert accept.best_matches('foo/bar') == ['foo/bar']
    assert accept.best_matches('text/html') == ['foo/bar', 'text/html']
开发者ID:AgentJay,项目名称:webapp-improved,代码行数:11,代码来源:test_acceptparse.py


示例16: test_quality_not_found

def test_quality_not_found():
    accept = Accept("text/html")
    assert accept.quality("foo/bar") is None
开发者ID:ckey,项目名称:webob,代码行数:3,代码来源:test_acceptparse.py


示例17: test_best_match_with_one_lower_q

def test_best_match_with_one_lower_q():
    accept = Accept("text/html, foo/bar;q=0.5")
    assert accept.best_match(["text/html", "foo/bar"]) == "text/html"
    accept = Accept("text/html;q=0.5, foo/bar")
    assert accept.best_match(["text/html", "foo/bar"]) == "foo/bar"
开发者ID:ckey,项目名称:webob,代码行数:5,代码来源:test_acceptparse.py


示例18: normalize_accept_offer

def normalize_accept_offer(offer):
    return str(Accept.parse_offer(offer))
开发者ID:Pylons,项目名称:pyramid,代码行数:2,代码来源:predicates.py


示例19: WebController


#.........这里部分代码省略.........
    def get_cookie(self, key):
        return self._session_key

    def delete_cookie(self, key):
        self.__response.delete_cookie(key)

    def set_cookie(self, key):
        value = self.new_session
        self.__response.set_cookie(key, bytes(value))
        return value

    def process(self, environ, start_response):
        self._begin = datetime.datetime.now()
        if self._debug:
            open("/tmp/cog_sql", "w")
        try:
            self.clear()
            self._environ = environ
#            open("/tmp/cog_tmp_xxx", "w").write("{}".format(environ))
            self._script_name = self._environ.get('SCRIPT_NAME', '')
            self._server_name = self._environ['HTTP_HOST']
            self._url_scheme = self._environ['wsgi.url_scheme']
            self._url = "{}://{}{}".format(
                self._url_scheme, self._server_name, self._script_name)
            self._path_info = self._environ['PATH_INFO'].lower()
            alnum = "[a-z0-9]{4}"
            oid_pattern = '^/{}{}-{}-{}-{}-{}{}{}$'.format(*(alnum,)*8)
            if re.match(oid_pattern, self._path_info):
                obj = self.db.get_elt_by_oid(self._path_info[1:])
                self.add_json_res({'#page_ref':self.get_page_ref()})
                self.direct_obj_ref = obj.w3display
            self.load_site()
            self.__request = Request(environ)
            self.__lang = Accept(str(self.__request.accept_language))
            self.i18n = gettext.translation(
                'messages', '/usr/share/collorg/locale',
                [self.__lang.best_match(('en', 'fr', 'fr-FR')) or 'en'])
            if WebController.__static_body is None:
                WebController.__tags = self.__get_tags()
                WebController.__static_body = self.__get_static_body()
            self.__response = Response()
            self.__reset()
            if not(self._cog_method is None and '#page_ref' in self._json_res):
                    self.add_json_res({'#page_ref':self.get_page_ref()})
            self.__response.unicode_body = self._unicode(self.__exec())
            if(self.__response.content_type != 'text/html' or
                self.__response.status_int != 200):
                # Not an HTML response, we don't want to
                # do anything to it
                return self.__response(environ, start_response)
            # Make sure the content isn't gzipped:
            self.__response.decode_content()
            return self.__response(environ, start_response)
        except Exception as err:
            if self.db._cog_params['debug']:
                response = Response()
                response.unicode_body = self._unicode(err)
                return response(environ, start_response)
            if raise_error:
                raise err

    def debug(self, error = None):
        output = []
        css_style = 'debug hidden toggle'
        css_error = ''
        if error:
开发者ID:joel-m,项目名称:collorg,代码行数:67,代码来源:web.py


示例20: checkMimetype

def checkMimetype(acceptHeader):
    accept = Accept('Accept', acceptHeader)
    best = accept.best_match(['application/rdf', 'application/rdf+xml', 'text/n3', 'application/xml', 'application/json', 'text/xml', 'application/xhtml+xml'])
    if best is None:
        best = "text/html"
    return best
开发者ID:zeitkunst,项目名称:JJPS,代码行数:6,代码来源:server.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python byterange.ContentRange类代码示例发布时间:2022-05-26
下一篇:
Python webob.Response类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap