lahwaacz / wiki-scripts

Framework for writing bots, maintenance scripts or performing data analysis on wikis powered by MediaWiki
http://lahwaacz.github.io/wiki-scripts/
GNU General Public License v3.0
27 stars 12 forks source link

Usage question for template_expansion.expand_templates #89

Closed Jontpan closed 2 years ago

Jontpan commented 2 years ago

Hi!

I am looking into solutions to expand templates from mwparserfromhell and I happened upon this project, but I am finding it difficult to understand what exactly I need in order for me to use the function parser_helpers.template_expansion.expand_templates().

If you could give me example code for the simplest way to use this function that would be much appreciated!

lahwaacz commented 2 years ago

Hi!

You need to have templates available somewhere so they can be used for expansion. The way it is used in this project assumes that they are in the wiki-scripts' SQL database, but the expand_templates function does not assume that and you can actually implement your own content_getter function:

from ws.client import API
from ws.parser_helpers.template_expansion import expand_templates
import mwparserfromhell

api_url = "https://wiki.archlinux.org/api.php"
index_url = "https://wiki.arclinux.org/index.php"
session = API.make_session()

api = API(api_url, index_url, session)

def content_getter(title):
    if title.fullpagename == "Main page":
        return "{{Foo}}"
    elif title.fullpagename == "Template:Foo":
        return "Bar"
    else:
        raise ValueError

title = api.Title("Main page")
wikicode = mwparserfromhell.parse(content_getter(title))
expand_templates(title, wikicode, content_getter)
assert wikicode == "Bar", wikicode

Note that you still need to use the API object from wiki-scripts which is needed for the Title object. You could even write the content_getter such that it fetches pages on-demand from the API, but that would be really slow (and unnecessary waste of the server resources), even if you cached the results. Let me know how this works for you, I can help you get started with the SQL database.