本文整理匯總了Python中webob.acceptparse.Accept類的典型用法代碼示例。如果您正苦於以下問題:Python Accept類的具體用法?Python Accept怎麽用?Python Accept使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了Accept類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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/*"])
示例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)
示例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')
示例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'
示例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/*'])
示例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
示例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)
示例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
示例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']
示例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)
示例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')
示例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
示例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, [])
示例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/*'])
示例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']