import pywikibot

from pywikibot import pagegenerators as pg

def list_template_usage(site_obj, tmpl_name):
    """
    Takes Site object and template name and returns a generator.

    The function expects a Site object (pywikibot.Site()) and
    a template name (String). It creates a list of all
    pages using that template and returns them as a generator.
    The generator will load 50 pages at a time for iteration.
    """
    name = "{}:{}".format(site_obj.namespace(10), tmpl_name)
    tmpl_page = pywikibot.Page(site_obj, name)
    ref_gen = pg.ReferringPageGenerator(tmpl_page, onlyTemplateInclusion=True)
    filter_gen = pg.NamespaceFilterPageGenerator(ref_gen, namespaces=[0])
    generator = site_obj.preloadpages(filter_gen, pageprops=True)
    return generator

site = pywikibot.Site("en", 'wikipedia')
tmpl_gen = list_template_usage(site, "Infobox meteorite")

for page in tmpl_gen:
    item = pywikibot.ItemPage.fromPage(page)
    print(page.title(), item.getID())
WARNING: API error mwoauth-invalid-authorization-invalid-user: The authorization headers in your request are for a user that does not exist here
---------------------------------------------------------------------------
NoUsername                                Traceback (most recent call last)
<ipython-input-3-b3792c780c30> in <module>()
     22 tmpl_gen = list_template_usage(site, "Infobox meteorite")
     23 
---> 24 for page in tmpl_gen:
     25     item = pywikibot.ItemPage.fromPage(page)
     26     print(page.title(), item.getID())

/srv/paws/pwb/pywikibot/site.py in preloadpages(self, pagelist, groupsize, templates, langlinks, pageprops)
   3210         rvprop = ['ids', 'flags', 'timestamp', 'user', 'comment', 'content']
   3211 
-> 3212         for sublist in itergroup(pagelist, groupsize):
   3213             # Do not use p.pageid property as it will force page loading.
   3214             pageids = [str(p._pageid) for p in sublist

/srv/paws/pwb/pywikibot/tools/__init__.py in itergroup(iterable, size)
    636     """
    637     group = []
--> 638     for item in iterable:
    639         group.append(item)
    640         if len(group) == size:

/srv/paws/pwb/pywikibot/pagegenerators.py in NamespaceFilterPageGenerator(generator, namespaces, site)
   1428         site = pywikibot.Site()
   1429     try:
-> 1430         namespaces = site.namespaces.resolve(namespaces)
   1431     except KeyError as e:
   1432         pywikibot.log('Failed resolving namespaces:')

/srv/paws/pwb/pywikibot/site.py in namespaces(self)
   1012         """Return dict of valid namespaces on this wiki."""
   1013         if not hasattr(self, '_namespaces'):
-> 1014             self._namespaces = NamespacesDict(self._build_namespaces())
   1015         return self._namespaces
   1016 

/srv/paws/pwb/pywikibot/site.py in _build_namespaces(self)
   2610         # For versions lower than 1.14, APISite needs to override
   2611         # the defaults defined in Namespace.
-> 2612         is_mw114 = MediaWikiVersion(self.version()) >= MediaWikiVersion('1.14')
   2613 
   2614         for nsdata in self.siteinfo.get('namespaces', cache=False).values():

/srv/paws/pwb/pywikibot/site.py in version(self)
   2723         if not version:
   2724             try:
-> 2725                 version = self.siteinfo.get('generator', expiry=1).split(' ')[1]
   2726             except pywikibot.data.api.APIError:
   2727                 # May occur if you are not logged in (no API read permissions).

/srv/paws/pwb/pywikibot/site.py in get(self, key, get_default, cache, expiry)
   1674                 elif not Siteinfo._is_expired(cached[1], expiry):
   1675                     return copy.deepcopy(cached[0])
-> 1676         preloaded = self._get_general(key, expiry)
   1677         if not preloaded:
   1678             preloaded = self._get_siteinfo(key, expiry)[key]

/srv/paws/pwb/pywikibot/site.py in _get_general(self, key, expiry)
   1620                         u"', '".join(props)), _logger)
   1621             props += ['general']
-> 1622             default_info = self._get_siteinfo(props, expiry)
   1623             for prop in props:
   1624                 self._cache[prop] = default_info[prop]

/srv/paws/pwb/pywikibot/site.py in _get_siteinfo(self, prop, expiry)
   1546             # warnings are handled later
   1547             request._warning_handler = warn_handler
-> 1548             data = request.submit()
   1549         except api.APIError as e:
   1550             if e.code == 'siunknown_siprop':

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2340         cached_available = self._load_cache()
   2341         if not cached_available:
-> 2342             self._data = super(CachedRequest, self).submit()
   2343             self._write_cache(self._data)
   2344         else:

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2173                     continue
   2174                 raise NoUsername('Failed OAuth authentication for %s: %s'
-> 2175                                  % (self.site, info))
   2176             # raise error
   2177             try:

NoUsername: Failed OAuth authentication for wikipedia:test: The authorization headers in your request are for a user that does not exist here