Page MenuHomePhabricator

NoUsernameError on specific pywikibot classes
Closed, InvalidPublicBUG REPORT

Description

I am getting the following error when trying to instantiate Coordinate and Wbtime objects (for instance). PageItem works fine. My user-config.py file exists and I can echo CLIENT_ID, CLIENT SECRET, USER and the likes succesfully. What could be wrong here?

WARNING: API error mwoauth-invalid-authorization-invalid-user: The authorization headers in your request are for a user that does not exist here
---------------------------------------------------------------------------
NoUsernameError                           Traceback (most recent call last)
Cell In [54], line 3
      1 claim = pywikibot.Claim(repo, 'P1259')
      2 #target = pywikibot.Coordinate(-22.93743,-43.13612)
----> 3 target = pywikibot.WbTime(year=1926)

File /srv/paws/pwb/pywikibot/__init__.py:405, in WbTime.__init__(self, year, month, day, hour, minute, second, precision, before, after, timezone, calendarmodel, site)
    403 if calendarmodel is None:
    404     if site is None:
--> 405         site = Site().data_repository()
    406         if site is None:
    407             raise ValueError('Site {} has no data repository'
    408                              .format(Site()))

File /srv/paws/pwb/pywikibot/site/_apisite.py:1149, in APISite.data_repository(self)
   1146 req = self._request(
   1147     expiry=7, parameters={'action': 'query', 'meta': 'wikibase'})
   1148 req._warning_handler = handle_warning
-> 1149 data = req.submit()
   1150 if 'query' in data and 'wikibase' in data['query']:
   1151     data = data['query']['wikibase']['repo']['url']

File /srv/paws/pwb/pywikibot/data/api/_requests.py:1256, in CachedRequest.submit(self)
   1254 def submit(self):
   1255     """Submit cached request."""
-> 1256     cached_available = self._load_cache()
   1257     if not cached_available:
   1258         self._data = super().submit()

File /srv/paws/pwb/pywikibot/data/api/_requests.py:1226, in CachedRequest._load_cache(self)
   1221 def _load_cache(self) -> bool:
   1222     """Load cache entry for request, if available.
   1223 
   1224     :return: Whether the request was loaded from the cache
   1225     """
-> 1226     self._add_defaults()
   1227     try:
   1228         filename = self._cachefile_path()

File /srv/paws/pwb/pywikibot/data/api/_requests.py:440, in Request._add_defaults(self)
    434         self['prop'] = sorted(prop)
    435     # When neither 'continue' nor 'rawcontinue' is present and the
    436     # version number is at least 1.25wmf5 we add a dummy rawcontinue
    437     # parameter. Querying siteinfo is save as it adds 'continue'
    438     # except for 'tokens' (T284577)
    439     if ('tokens' not in meta and 'continue' not in self._params
--> 440             and self.site.mw_version >= '1.25wmf5'):
    441         self._params.setdefault('rawcontinue', [''])
    442 elif self.action == 'help' and self.site.mw_version > '1.24':

File /srv/paws/pwb/pywikibot/site/_apisite.py:1109, in APISite.mw_version(self)
   1103 mw_ver, cache_time = getattr(self, '_mw_version_time', (None, None))
   1104 if (
   1105     mw_ver is None
   1106     or cache_time is None
   1107     or time.time() - cache_time > 60 * 60 * 24
   1108 ):
-> 1109     mw_ver = MediaWikiVersion(self.version())
   1110     self._mw_version_time = mw_ver, time.time()
   1111 return mw_ver

File /srv/paws/pwb/pywikibot/site/_apisite.py:1082, in APISite.version(self)
   1077 """Return live project version number as a string.
   1078 
   1079 Use :py:obj:`pywikibot.site.mw_version` to compare MediaWiki versions.
   1080 """
   1081 try:
-> 1082     version = self.siteinfo.get('generator', expiry=1).split(' ')[1]
   1083 except APIError:
   1084     msg = 'You have no API read permissions.'

File /srv/paws/pwb/pywikibot/site/_siteinfo.py:304, in Siteinfo.get(self, key, get_default, cache, expiry)
    301         if not Siteinfo._is_expired(cached[1], expiry):
    302             return copy.deepcopy(cached[0])
--> 304 preloaded = self._get_general(key, expiry)
    305 if not preloaded:
    306     preloaded = self._get_siteinfo(key, expiry)[key]

File /srv/paws/pwb/pywikibot/site/_siteinfo.py:242, in Siteinfo._get_general(self, key, expiry)
    238     pywikibot.debug(
    239         "Load siteinfo properties '{}' along with 'general'"
    240         .format("', '".join(props)))
    241 props += ['general']
--> 242 default_info = self._get_siteinfo(props, expiry)
    243 for prop in props:
    244     self._cache[prop] = default_info[prop]

File /srv/paws/pwb/pywikibot/site/_siteinfo.py:167, in Siteinfo._get_siteinfo(self, prop, expiry)
    165 request._warning_handler = warn_handler
    166 try:
--> 167     data = request.submit()
    168 except APIError as e:
    169     if e.code == 'siunknown_siprop':

File /srv/paws/pwb/pywikibot/data/api/_requests.py:1258, in CachedRequest.submit(self)
   1256 cached_available = self._load_cache()
   1257 if not cached_available:
-> 1258     self._data = super().submit()
   1259     self._write_cache(self._data)
   1260 else:

File /srv/paws/pwb/pywikibot/data/api/_requests.py:1075, in Request.submit(self)
   1071         pywikibot.error(
   1072             'Retrying failed OAuth authentication for {}: {}'
   1073             .format(self.site, info))
   1074         continue
-> 1075     raise NoUsernameError('Failed OAuth authentication for {}: {}'
   1076                           .format(self.site, info))
   1077 if code == 'cirrussearch-too-busy-error':  # T170647
   1078     self.wait()

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

Event Timeline

I think I kind of solved it by manually editing user-config.py, but now item = pywikibot.ItemPage(repo, 'Q114776071') gives

AttributeError                            Traceback (most recent call last)
Cell In [21], line 1
----> 1 item = pywikibot.ItemPage(repo, 'Q114776071')

File /srv/paws/pwb/pywikibot/page/_wikibase.py:810, in ItemPage.__init__(self, site, title, ns)
    807 if not title:
    808     raise InvalidTitleError("Item's title cannot be empty")
--> 810 super().__init__(site, title, ns=ns)
    812 assert self.id == self._link.title

File /srv/paws/pwb/pywikibot/page/_wikibase.py:484, in WikibasePage.__init__(self, site, title, **kwargs)
    481         self._namespace = entity_type_ns
    482         kwargs['ns'] = self._namespace.id
--> 484 BasePage.__init__(self, site, title, **kwargs)
    486 # If a title was not provided,
    487 # avoid checks which may cause an exception.
    488 if not title:

File /srv/paws/pwb/pywikibot/page/_pages.py:128, in BasePage.__init__(self, source, title, ns)
    125     raise ValueError('Title cannot be None.')
    127 if isinstance(source, pywikibot.site.BaseSite):
--> 128     self._link = Link(title, source=source, default_namespace=ns)
    129     self._revisions = {}
    130 elif isinstance(source, Page):
    131     # copy all of source's attributes to this object
    132     # without overwriting non-None values

File /srv/paws/pwb/pywikibot/page/_links.py:303, in Link.__init__(self, text, source, default_namespace)
    300 self._text = self._text.strip()
    302 # Convert URL-encoded characters to unicode
--> 303 self._text = pywikibot.tools.chars.url2string(
    304     self._text, encodings=self._source.encodings())
    306 # Clean up the name, it can come from anywhere.
    307 # Convert HTML entities to unicode
    308 t = html2unicode(self._text)

AttributeError: module 'pywikibot' has no attribute 'tools'

It works for me:

>>> import pywikibot
>>> repo = pywikibot.Site('wikidata:wikidata')
>>> item = pywikibot.ItemPage(repo, 'Q114776071')
>>> item
ItemPage('Q114776071')
>>> import pywikibot
>>> from pywikibot.tools import ComparableMixin, first_upper, is_ip_address
>>> pywikibot.tools.chars.url2string
<function url2string at 0x000002089677D630>

AttributeError: module 'pywikibot' has no attribute 'tools'

This looks like an incomplete imported Pywikibot module somewhere. What is your Python version running?

I think I kind of solved it by manually editing user-config.py

What was the modification?

Like matej_suchanek I wasn't able to reproduce it.

Feel free to reopen if you have further informations to this issue