Ejemplo n.º 1
0
def prepare_api_request(request):
    """Prepares the request for API usage."""
    request.in_api = True
    lang = request.args.get("lang")
    if lang is not None:
        if not has_section(lang):
            raise BadRequest(_(u"Unknown language"))
        request.locale = lang

    locale = request.args.get("locale")
    if locale is not None:
        try:
            locale = Locale.parse(locale)
            if not has_locale(locale):
                raise UnknownLocaleError()
        except UnknownLocaleError:
            raise BadRquest(_(u"Unknown locale"))
        request.view_lang = locale
Ejemplo n.º 2
0
def get_serializer(request):
    """Returns the serializer for the given API request."""
    format = request.args.get("format")
    if format is not None:
        rv = _serializer_map.get(format)
        if rv is None:
            raise BadRequest(_(u'Unknown format "%s"') % escape(format))
        return rv

    # webkit sends useless accept headers. They accept XML over
    # HTML or have no preference at all. We spotted them, so they
    # are obviously not regular API users, just ignore the accept
    # header and return the debug serializer.
    if request.user_agent.browser in ("chrome", "safari"):
        return _serializer_map["debug"]

    best_match = (None, 0)
    for mimetype, serializer in _serializer_for_mimetypes.iteritems():
        quality = request.accept_mimetypes[mimetype]
        if quality > best_match[1]:
            best_match = (serializer, quality)

    if best_match[0] is None:
        raise BadRequest(
            _(
                u"Could not detect format.  You have to specify "
                u"the format as query argument or in the accept "
                u"HTTP header."
            )
        )

    # special case.  If the best match is not html and the quality of
    # text/html is the same as the best match, we prefer HTML.
    if best_match[0] != "text/html" and best_match[1] == request.accept_mimetypes["text/html"]:
        return _serializer_map["debug"]

    return _serializer_map[best_match[0]]