本文整理汇总了Python中werkzeug.http.parse_accept_header函数的典型用法代码示例。如果您正苦于以下问题:Python parse_accept_header函数的具体用法?Python parse_accept_header怎么用?Python parse_accept_header使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse_accept_header函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: choose_best_handler
def choose_best_handler(self):
# The best handler for the formatter instance depends on the
# request; in particular it relies on what the client has
# indicated it can accept
# Get the accept header
accept_header = ctx.request.headers.get("Accept")
if accept_header == "*/*" or accept_header is None:
if hasattr(self, 'default'):
return self.default, self.handlers[self.default]
else:
try:
return next(iter(self.handlers.items()))
except StopIteration:
raise ValueError("No handlers have been registered "
"for this formatter.")
else:
accept = parse_accept_header(accept_header, MIMEAccept)
mime_type = accept.best_match(self.handlers)
if mime_type is not None:
return mime_type, self.handlers[mime_type]
else:
raise NotAcceptable
# Parse the Accept header
accept = parse_accept_header(
ctx.request.headers.get("Accept", "*/*"),
MIMEAccept
)
mime_type = accept.best_match(self.handlers)
if mime_type is not None:
return mime_type, self.handlers[mime_type]
elif "*/*" in accept.values():
for mimetype in self.handlers:
return self.handlers[mimetype]
else:
# The requesting client will accept anything, but we
# don't have handlers at all. This is a LookupError
raise LookupError("No formatter handlers available at "
"all; cannot format this data.")
else:
# The output format that the requesting client asked for
# isn't supported. This is NotAcceptable
raise NotAcceptable
示例2: get_user_locale
def get_user_locale(self):
self.langs = self.application.service.langs
lang_codes = self.langs.keys()
if len(self.contest.allowed_localizations) > 0:
lang_codes = filter_language_codes(
lang_codes, self.contest.allowed_localizations)
# TODO We fallback on "en" if no language matches: we could
# return 406 Not Acceptable instead.
# Select the one the user likes most.
http_langs = [lang_code.replace("_", "-") for lang_code in lang_codes]
self.browser_lang = parse_accept_header(
self.request.headers.get("Accept-Language", ""),
LanguageAccept).best_match(http_langs, "en")
self.cookie_lang = self.get_cookie("language", None)
if self.cookie_lang in http_langs:
lang_code = self.cookie_lang
else:
lang_code = self.browser_lang
self.set_header("Content-Language", lang_code)
return self.langs[lang_code.replace("-", "_")]
示例3: test_language_accept
def test_language_accept(self):
a = http.parse_accept_header("de-AT,de;q=0.8,en;q=0.5", datastructures.LanguageAccept)
self.assert_equal(a.best, "de-AT")
self.assert_true("de_AT" in a)
self.assert_true("en" in a)
self.assert_equal(a["de-at"], 1)
self.assert_equal(a["en"], 0.5)
示例4: get_user_locale
def get_user_locale(self):
self.langs = self.application.service.langs
lang_codes = self.langs.keys()
if self.contest.allowed_localizations:
lang_codes = filter_language_codes(
lang_codes, self.contest.allowed_localizations)
# Select the one the user likes most.
basic_lang = 'en'
if self.contest.allowed_localizations:
basic_lang = lang_codes[0].replace("_", "-")
http_langs = [lang_code.replace("_", "-") for lang_code in lang_codes]
self.browser_lang = parse_accept_header(
self.request.headers.get("Accept-Language", ""),
LanguageAccept).best_match(http_langs, basic_lang)
self.cookie_lang = self.get_cookie("language", None)
if self.cookie_lang in http_langs:
lang_code = self.cookie_lang
else:
lang_code = self.browser_lang
self.set_header("Content-Language", lang_code)
return self.langs[lang_code.replace("-", "_")]
示例5: test_best_match_works
def test_best_match_works(self):
# was a bug in 0.6
rv = http.parse_accept_header(
"foo=,application/xml,application/xhtml+xml," "text/html;q=0.9,text/plain;q=0.8," "image/png,*/*;q=0.5",
datastructures.MIMEAccept,
).best_match(["foo/bar"])
self.assert_equal(rv, "foo/bar")
示例6: test_charset_accept
def test_charset_accept(self):
a = http.parse_accept_header('ISO-8859-1,utf-8;q=0.7,*;q=0.7',
datastructures.CharsetAccept)
assert a['iso-8859-1'] == a['iso8859-1']
assert a['iso-8859-1'] == 1
assert a['UTF8'] == 0.7
assert a['ebcdic'] == 0.7
示例7: test_accept
def test_accept(self):
a = http.parse_accept_header("en-us,ru;q=0.5")
self.assert_equal(list(itervalues(a)), ["en-us", "ru"])
self.assert_equal(a.best, "en-us")
self.assert_equal(a.find("ru"), 1)
self.assert_raises(ValueError, a.index, "de")
self.assert_equal(a.to_header(), "en-us,ru;q=0.5")
示例8: test_accept
def test_accept(self):
a = http.parse_accept_header("en-us,ru;q=0.5")
assert list(itervalues(a)) == ["en-us", "ru"]
assert a.best == "en-us"
assert a.find("ru") == 1
pytest.raises(ValueError, a.index, "de")
assert a.to_header() == "en-us,ru;q=0.5"
示例9: test_best_match_works
def test_best_match_works(self):
# was a bug in 0.6
rv = http.parse_accept_header('foo=,application/xml,application/xhtml+xml,'
'text/html;q=0.9,text/plain;q=0.8,'
'image/png,*/*;q=0.5',
datastructures.MIMEAccept).best_match(['foo/bar'])
self.assert_equal(rv, 'foo/bar')
示例10: setup_locale
def setup_locale(self):
lang_codes = list(iterkeys(self.available_translations))
browser_langs = parse_accept_header(
self.request.headers.get("Accept-Language", ""),
LanguageAccept).values()
automatic_lang = choose_language_code(browser_langs, lang_codes)
if automatic_lang is None:
automatic_lang = lang_codes[0]
self.automatic_translation = \
self.available_translations[automatic_lang]
cookie_lang = self.get_cookie("language", None)
if cookie_lang is not None:
chosen_lang = \
choose_language_code([cookie_lang, automatic_lang], lang_codes)
if chosen_lang == cookie_lang:
self.cookie_translation = \
self.available_translations[cookie_lang]
else:
chosen_lang = automatic_lang
self.translation = self.available_translations[chosen_lang]
self._ = self.translation.gettext
self.n_ = self.translation.ngettext
self.set_header("Content-Language", chosen_lang)
示例11: browse
def browse():
uri = request.args.get('uri', None)
if uri is None:
return document()
else:
if 'Accept' in request.headers:
mimetype = parse_accept_header(request.headers['Accept']).best
else:
log.debug("No accept header, using 'text/html'")
mimetype = 'text/html'
try:
if mimetype in ['text/html', 'application/xhtml_xml', '*/*']:
results = visit(uri, format='html', external=True)
local_results = localize_results(results)
return render_template('resource.html', local_resource='http://bla', resource=uri, results=local_results, local=LOCAL_STORE, preflabel=PREFLABEL_SERVICE)
elif mimetype in ['application/json']:
response = make_response(visit(uri, format='jsonld', external=True), 200)
response.headers['Content-Type'] = 'application/json'
return response
elif mimetype in ['application/rdf+xml', 'application/xml']:
response = make_response(visit(uri, format='rdfxml', external=True), 200)
response.headers['Content-Type'] = 'application/rdf+xml'
return response
elif mimetype in ['application/x-turtle', 'text/turtle']:
response = make_response(visit(uri, format='turtle', external=True), 200)
response.headers['Content-Type'] = 'text/turtle'
return response
except Exception as e:
log.error(e)
log.error(traceback.format_exc())
return traceback.format_exc()
示例12: test_charset_accept
def test_charset_accept(self):
a = http.parse_accept_header('ISO-8859-1,utf-8;q=0.7,*;q=0.7',
datastructures.CharsetAccept)
self.assert_equal(a['iso-8859-1'], a['iso8859-1'])
self.assert_equal(a['iso-8859-1'], 1)
self.assert_equal(a['UTF8'], 0.7)
self.assert_equal(a['ebcdic'], 0.7)
示例13: test_language_accept
def test_language_accept(self):
a = http.parse_accept_header("de-AT,de;q=0.8,en;q=0.5", datastructures.LanguageAccept)
assert a.best == "de-AT"
assert "de_AT" in a
assert "en" in a
assert a["de-at"] == 1
assert a["en"] == 0.5
示例14: get_lang
def get_lang(self, environ):
"""
Detects user's preferred language (either via the 'getlang' plugin or from HTTP_ACCEPT_LANGUAGE env value)
arguments:
environ -- WSGI environment variable
returns:
underscore-separated ISO 639 language code and ISO 3166 country code
"""
cookies = KonTextCookie(environ.get('HTTP_COOKIE', ''))
if plugins.runtime.GETLANG.exists:
lgs_string = plugins.runtime.GETLANG.instance.fetch_current_language(cookies)
else:
lang_cookie = cookies.get('kontext_ui_lang')
if not lang_cookie:
lgs_string = parse_accept_header(environ.get('HTTP_ACCEPT_LANGUAGE')).best
else:
lgs_string = lang_cookie.value
if len(lgs_string) == 2: # in case we obtain just an ISO 639 language code
lgs_string = self._installed_langs.get(lgs_string)
else:
lgs_string = lgs_string.replace('-', '_')
if lgs_string is None:
lgs_string = 'en_US'
return lgs_string
示例15: set_mimetype
def set_mimetype(self, environ):
client_accepts = dict(parse_accept_header(environ['HTTP_ACCEPT']))
if 'application/json' in client_accepts:
self.mime_type = 'application/json'
else:
#fallback if the client has not told us that it is calling the API
self.mime_type = 'text/html'