wikimedica-disease-search/data/fetch/mediawiki_api.py

57 lines
1.7 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from .http import session
import mwclient
def instanciate(site):
"""
Instancie un objet permettant daccéder à lAPI dun site MediaWiki.
:param site: Nom de domaine du site.
:return: Instance mwclient.Site pour le site.
"""
return mwclient.Site(site, pool=session)
def article_canonical(site, article):
"""
Obtient le nom canonique dun article après avoir suivi les redirections.
:param site: Instance mwclient.Site pour le site ciblé.
:param article: Article ciblé dans le site.
:return: Nom canonique de larticle.
"""
original_page = site.pages[article]
if not original_page.exists:
raise Exception(
'Article « {} » inexistant sur {}'
.format(article, site.host)
)
return original_page.resolve_redirect().name
def article_redirects(site, article):
"""
Récupère lensemble des pages redirigeant vers un article.
:param site: Instance mwclient.Site pour le site ciblé.
:param article: Article ciblé dans le site.
:return: Liste des pages redirigeant vers `article`.
"""
response = site.api('query', prop='redirects', titles=article)
page_response = list(response['query']['pages'].values())[0]
if 'missing' in page_response:
raise Exception(
'Article « {} » inexistant sur {}'
.format(article, site.host)
)
# Si la réponse ninclut pas la clé «redirects», cest quil nexiste
# aucune redirection vers la page
return [
item['title'] for item in
page_response['redirects']
] if 'redirects' in page_response else []