| 1614 | MEDIAWIKI_REFERENCE = r"\s*\[[0-9]{1,3}\]" |
| 1615 | |
| 1616 | class MediaWiki(SearchEngine): |
| 1617 | |
| 1618 | def __init__(self, license=None, throttle=5.0, language="en"): |
| 1619 | SearchEngine.__init__(self, license or MEDIAWIKI_LICENSE, throttle, language) |
| 1620 | |
| 1621 | @property |
| 1622 | def _url(self): |
| 1623 | # Must be overridden in a subclass; see Wikia and Wikipedia. |
| 1624 | return None |
| 1625 | |
| 1626 | @property |
| 1627 | def MediaWikiArticle(self): |
| 1628 | return MediaWikiArticle |
| 1629 | @property |
| 1630 | def MediaWikiSection(self): |
| 1631 | return MediaWikiSection |
| 1632 | @property |
| 1633 | def MediaWikiTable(self): |
| 1634 | return MediaWikiTable |
| 1635 | |
| 1636 | def __iter__(self): |
| 1637 | return self.all() |
| 1638 | |
| 1639 | def all(self, **kwargs): |
| 1640 | """ Returns an iterator over all MediaWikiArticle objects. |
| 1641 | Optional parameters can include those passed to |
| 1642 | MediaWiki.list(), MediaWiki.search() and URL.download(). |
| 1643 | """ |
| 1644 | for title in self.list(**kwargs): |
| 1645 | yield self.search(title, **kwargs) |
| 1646 | |
| 1647 | articles = all |
| 1648 | |
| 1649 | def list(self, namespace=0, start=None, count=100, cached=True, **kwargs): |
| 1650 | """ Returns an iterator over all article titles (for a given namespace id). |
| 1651 | """ |
| 1652 | kwargs.setdefault("unicode", True) |
| 1653 | kwargs.setdefault("throttle", self.throttle) |
| 1654 | # Fetch article titles (default) or a custom id. |
| 1655 | id = kwargs.pop("_id", "title") |
| 1656 | # Loop endlessly (= until the last request no longer yields an "apcontinue"). |
| 1657 | # See: http://www.mediawiki.org/wiki/API:Allpages |
| 1658 | while start != -1: |
| 1659 | url = URL(self._url, method=GET, query={ |
| 1660 | "action": "query", |
| 1661 | "list": "allpages", |
| 1662 | "apnamespace": namespace, |
| 1663 | "apfrom": start or "", |
| 1664 | "aplimit": min(count, 500), |
| 1665 | "apfilterredir": "nonredirects", |
| 1666 | "format": "json" |
| 1667 | }) |
| 1668 | data = url.download(cached=cached, **kwargs) |
| 1669 | data = json.loads(data) |
| 1670 | for x in data.get("query", {}).get("allpages", {}): |
| 1671 | if x.get(id): |
| 1672 | yield x[id] |
| 1673 | start = data.get("query-continue", {}).get("allpages", {}) |
no outgoing calls
no test coverage detected
searching dependent graphs…