def get_blog_posts(name, blog_config, limit=None):
    """Retrieves blog posts for the given blog.

    This will try to use local caches in assets:blogs first and, if
    said caches do not exist, will get the RSS feed directly.

    Args:
        name: The name of the blog.
        blog_config: The configuration for the blog, specifying where
            the RSS feed may be found if it isn't cached.
        limit: A limit on the number of items retrieved from the feed.
            (Default: None, or no limit.)

    Returns:
        A feedparser-compatible blog feed object.
    """
    asset = 'assets:blogs/{}'.format(name)
    full_path = pyramid.path.AssetResolver().resolve(asset).abspath()

    try:
        with open(full_path, 'rb') as feed_file:
            feed = pickle.load(feed_file)
    except IOError:
        feed = feedparser.feed(blog_config['feed'])

    return feed['entries'][:limit]
Exemple #2
0
def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=None, request_headers=None, response_headers=None, resolve_relative_uris=None, sanitize_html=None):
    '''Parse a feed from a URL, file, stream, or string.

    :param url_file_stream_or_string:
        File-like object, URL, file path, or string. Both byte and text strings
        are accepted. If necessary, encoding will be derived from the response
        headers or automatically detected.

        Note that strings may trigger network I/O or filesystem access
        depending on the value. Wrap an untrusted string in
        a :class:`io.StringIO` or :class:`io.BytesIO` to avoid this. Do not
        pass untrusted strings to this function.

        When a URL is not passed the feed location to use in relative URL
        resolution should be passed in the ``Content-Location`` response header
        (see ``response_headers`` below).

    :param str etag: HTTP ``ETag`` request header.
    :param modified: HTTP ``Last-Modified`` request header.
    :type modified: :class:`str`, :class:`time.struct_time` 9-tuple, or
        :class:`datetime.datetime`
    :param str agent: HTTP ``User-Agent`` request header, which defaults to
        the value of :data:`feedparser.USER_AGENT`.
    :param referrer: HTTP ``Referer`` [sic] request header.
    :param request_headers:
        A mapping of HTTP header name to HTTP header value to add to the
        request, overriding internally generated values.
    :type request_headers: :class:`dict` mapping :class:`str` to :class:`str`
    :param response_headers:
        A mapping of HTTP header name to HTTP header value. Multiple values may
        be joined with a comma. If a HTTP request was made, these headers
        override any matching headers in the response. Otherwise this specifies
        the entirety of the response headers.
    :type response_headers: :class:`dict` mapping :class:`str` to :class:`str`

    :param bool resolve_relative_uris:
        Should feedparser attempt to resolve relative URIs absolute ones within
        HTML content?  Defaults to the value of
        :data:`feedparser.RESOLVE_RELATIVE_URIS`, which is ``True``.
    :param bool sanitize_html:
        Should feedparser skip HTML sanitization? Only disable this if you know
        what you are doing!  Defaults to the value of
        :data:`feedparser.SANITIZE_HTML`, which is ``True``.

    :return: A :class:`FeedParserDict`.
    '''
    if not agent or sanitize_html is None or resolve_relative_uris is None:
        import feedparser
    if not agent:
        agent = feedparser.USER_AGENT
    if sanitize_html is None:
        sanitize_html = feedparser.SANITIZE_HTML
    if resolve_relative_uris is None:
        resolve_relative_uris = feedparser.RESOLVE_RELATIVE_URIS

    result = FeedParserDict(
        bozo = False,
        entries = [],
        feed = FeedParserDict(),
        headers = {},
    )

    data = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers, request_headers, result)

    if not data:
        return result

    # overwrite existing headers using response_headers
    result['headers'].update(response_headers or {})

    data = convert_to_utf8(result['headers'], data, result)
    use_strict_parser = result['encoding'] and True or False

    result['version'], data, entities = replace_doctype(data)

    # Ensure that baseuri is an absolute URI using an acceptable URI scheme.
    contentloc = result['headers'].get('content-location', '')
    href = result.get('href', '')
    baseuri = _makeSafeAbsoluteURI(href, contentloc) or _makeSafeAbsoluteURI(contentloc) or href

    baselang = result['headers'].get('content-language', None)
    if isinstance(baselang, bytes_) and baselang is not None:
        baselang = baselang.decode('utf-8', 'ignore')

    if not _XML_AVAILABLE:
        use_strict_parser = 0
    if use_strict_parser:
        # initialize the SAX parser
        feedparser = StrictFeedParser(baseuri, baselang, 'utf-8')
        feedparser.resolve_relative_uris = resolve_relative_uris
        feedparser.sanitize_html = sanitize_html
        saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
        saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
        try:
            # disable downloading external doctype references, if possible
            saxparser.setFeature(xml.sax.handler.feature_external_ges, 0)
        except xml.sax.SAXNotSupportedException:
            pass
        saxparser.setContentHandler(feedparser)
        saxparser.setErrorHandler(feedparser)
        source = xml.sax.xmlreader.InputSource()
        source.setByteStream(_StringIO(data))
        try:
            saxparser.parse(source)
        except xml.sax.SAXException as e:
            result['bozo'] = 1
            result['bozo_exception'] = feedparser.exc or e
            use_strict_parser = 0
    if not use_strict_parser and _SGML_AVAILABLE:
        feedparser = LooseFeedParser(baseuri, baselang, 'utf-8', entities)
        feedparser.resolve_relative_uris = resolve_relative_uris
        feedparser.sanitize_html = sanitize_html
        feedparser.feed(data.decode('utf-8', 'replace'))
    result['feed'] = feedparser.feeddata
    result['entries'] = feedparser.entries
    result['version'] = result['version'] or feedparser.version
    result['namespaces'] = feedparser.namespacesInUse
    return result
Exemple #3
0
def parse(url_file_stream_or_string,
          etag=None,
          modified=None,
          agent=None,
          referrer=None,
          handlers=None,
          request_headers=None,
          response_headers=None,
          resolve_relative_uris=None,
          sanitize_html=None):
    """Parse a feed from a URL, file, stream, or string.

    :param url_file_stream_or_string:
        File-like object, URL, file path, or string. Both byte and text strings
        are accepted. If necessary, encoding will be derived from the response
        headers or automatically detected.

        Note that strings may trigger network I/O or filesystem access
        depending on the value. Wrap an untrusted string in
        a :class:`io.StringIO` or :class:`io.BytesIO` to avoid this. Do not
        pass untrusted strings to this function.

        When a URL is not passed the feed location to use in relative URL
        resolution should be passed in the ``Content-Location`` response header
        (see ``response_headers`` below).

    :param str etag: HTTP ``ETag`` request header.
    :param modified: HTTP ``Last-Modified`` request header.
    :type modified: :class:`str`, :class:`time.struct_time` 9-tuple, or
        :class:`datetime.datetime`
    :param str agent: HTTP ``User-Agent`` request header, which defaults to
        the value of :data:`feedparser.USER_AGENT`.
    :param referrer: HTTP ``Referer`` [sic] request header.
    :param request_headers:
        A mapping of HTTP header name to HTTP header value to add to the
        request, overriding internally generated values.
    :type request_headers: :class:`dict` mapping :class:`str` to :class:`str`
    :param response_headers:
        A mapping of HTTP header name to HTTP header value. Multiple values may
        be joined with a comma. If a HTTP request was made, these headers
        override any matching headers in the response. Otherwise this specifies
        the entirety of the response headers.
    :type response_headers: :class:`dict` mapping :class:`str` to :class:`str`

    :param bool resolve_relative_uris:
        Should feedparser attempt to resolve relative URIs absolute ones within
        HTML content?  Defaults to the value of
        :data:`feedparser.RESOLVE_RELATIVE_URIS`, which is ``True``.
    :param bool sanitize_html:
        Should feedparser skip HTML sanitization? Only disable this if you know
        what you are doing!  Defaults to the value of
        :data:`feedparser.SANITIZE_HTML`, which is ``True``.

    :return: A :class:`FeedParserDict`.
    """

    if not agent or sanitize_html is None or resolve_relative_uris is None:
        import feedparser
    if not agent:
        agent = feedparser.USER_AGENT
    if sanitize_html is None:
        sanitize_html = feedparser.SANITIZE_HTML
    if resolve_relative_uris is None:
        resolve_relative_uris = feedparser.RESOLVE_RELATIVE_URIS

    result = FeedParserDict(
        bozo=False,
        entries=[],
        feed=FeedParserDict(),
        headers={},
    )

    try:
        data = _open_resource(url_file_stream_or_string, etag, modified, agent,
                              referrer, handlers, request_headers, result)
    except urllib.error.URLError as error:
        result.update({
            'bozo': True,
            'bozo_exception': error,
        })
        return result

    if not data:
        return result

    # overwrite existing headers using response_headers
    result['headers'].update(response_headers or {})

    data = convert_to_utf8(result['headers'], data, result)
    use_strict_parser = result['encoding'] and True or False

    result['version'], data, entities = replace_doctype(data)

    # Ensure that baseuri is an absolute URI using an acceptable URI scheme.
    contentloc = result['headers'].get('content-location', '')
    href = result.get('href', '')
    baseuri = make_safe_absolute_uri(
        href, contentloc) or make_safe_absolute_uri(contentloc) or href

    baselang = result['headers'].get('content-language', None)
    if isinstance(baselang, bytes) and baselang is not None:
        baselang = baselang.decode('utf-8', 'ignore')

    if not _XML_AVAILABLE:
        use_strict_parser = 0
    if use_strict_parser:
        # initialize the SAX parser
        feedparser = StrictFeedParser(baseuri, baselang, 'utf-8')
        feedparser.resolve_relative_uris = resolve_relative_uris
        feedparser.sanitize_html = sanitize_html
        saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
        saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
        try:
            # disable downloading external doctype references, if possible
            saxparser.setFeature(xml.sax.handler.feature_external_ges, 0)
        except xml.sax.SAXNotSupportedException:
            pass
        saxparser.setContentHandler(feedparser)
        saxparser.setErrorHandler(feedparser)
        source = xml.sax.xmlreader.InputSource()
        source.setByteStream(io.BytesIO(data))
        try:
            saxparser.parse(source)
        except xml.sax.SAXException as e:
            result['bozo'] = 1
            result['bozo_exception'] = feedparser.exc or e
            use_strict_parser = 0
    if not use_strict_parser:
        feedparser = LooseFeedParser(baseuri, baselang, 'utf-8', entities)
        feedparser.resolve_relative_uris = resolve_relative_uris
        feedparser.sanitize_html = sanitize_html
        feedparser.feed(data.decode('utf-8', 'replace'))
    result['feed'] = feedparser.feeddata
    result['entries'] = feedparser.entries
    result['version'] = result['version'] or feedparser.version
    result['namespaces'] = feedparser.namespaces_in_use
    return result