Repository with sources and generator of https://larlet.fr/david/ https://larlet.fr/david/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.md 1.8KB

title: Python et cache

J’ai eu plusieurs demandes techniques concernant la mise en cache des articles liés cette année. J’utilise la bibliothèque readability-lxml de manière assez standard :

:::python
import requests
from readability.readability import Document

def extract_page(url):
    """From an URL, extract title and content.

    The title is shortened through the `short_title` method.
    The content doesn't contain `<body>` tags to be directly
    embeddable in the template and rendered as is.
    """
    # Retrieves the resource and turns it into a doc.
    response = requests.get(url)
    document = Document(response.text, debug=True)

    # The short title is more concise and readable.
    title = document.short_title()
    content = document.summary(html_partial=True)

    # Removing the added <div> and spaces.
    content = content[5:-6].strip()
    return title, content

La seule chose à prendre en compte, ce sont les erreurs particulières qui peuvent être remontées que je gère ainsi :

:::python
try:
    title, content = extract_page(url)
except (requests.adapters.SSLError, 
        lxml.etree.XMLSyntaxError,
        requests.exceptions.ConnectionError), e:
    print('WARNING: {error}'.format(error=e))

Dans ces cas je récupère la page à la main. J’avais pas mal de bugs lors du téléchargement des pages mais je viens de me rendre compte des nombreuses versions qui ont été publiées depuis ma dernière mise à jour. J’espère avoir moins à retravailler le markup maintenant… ce qui me permettrait d’automatiser la récupération des vieux articles.