In [1]:
import json
import pywikibot
import time

wikidata_site = pywikibot.Site('wikidata', 'wikidata')
repo = wikidata_site.data_repository()

with open('elo_ratings_for_import.json') as fh:
    inputdata = json.load(fh)

for i, obj in enumerate(inputdata):
    eloAlreadySet = False
    
    Qitem = pywikibot.ItemPage(repo, obj['QID'])
    Qitem.get()
    if Qitem.claims and 'P1087' in Qitem.claims:
        for eloClaim in Qitem.claims['P1087']:
            if eloClaim.qualifiers and 'P585' in eloClaim.qualifiers:
                for j, dummy in enumerate(eloClaim.qualifiers['P585']):
                    pointInTime = eloClaim.qualifiers['P585'][j].getTarget()
                    if pointInTime.year==obj['P585']['Y'] and pointInTime.month==obj['P585']['M']:
                        eloAlreadySet = True
                        print('{}: Elo claim for {}-{:02d} already exists with value {}; skip'.format(obj['QID'], obj['P585']['Y'], obj['P585']['M'], eloClaim.getTarget().amount))
            
    if eloAlreadySet==False:
        newElo = pywikibot.Claim(repo, 'P1087')
        newElo.setTarget(value=pywikibot.WbQuantity(site=repo, amount=obj['P1087']))
        Qitem.addClaim(newElo)
        
        timestmp = pywikibot.Claim(repo, 'P585')
        timestmp.setTarget(value=pywikibot.WbTime(year=obj['P585']['Y'], month=obj['P585']['M']))
        newElo.addQualifier(timestmp)
        
        if 'P1440' in obj:
            statedIn = pywikibot.Claim(repo, 'P248')
            statedIn.setTarget(value=pywikibot.ItemPage(repo, 'Q27038151')); # Q27038151 is ratings.fide.org
            fideId = pywikibot.Claim(repo, 'P1440')
            fideId.setTarget(value=obj['P1440'])
            retrieved = pywikibot.Claim(repo, 'P813')
            retrieved.setTarget(value=pywikibot.WbTime(year=obj['P813']['Y'], month=obj['P813']['M'], day=obj['P813']['D']))
            newElo.addSources([statedIn, fideId, retrieved])
        elif 'P854' in obj:
            url = pywikibot.Claim(repo, 'P854')
            url.setTarget(value=obj['P854'])
            retrieved = pywikibot.Claim(repo, 'P813')
            retrieved.setTarget(value=pywikibot.WbTime(year=obj['P813']['Y'], month=obj['P813']['M'], day=obj['P813']['D']))
            if 'P1476' in obj:
                title = pywikibot.Claim(repo, 'P1476')
                title.setTarget(value=pywikibot.WbMonolingualText(text=obj['P1476'], language='en'))
                newElo.addSources([url, retrieved, title])
            else:
                newElo.addSources([url, retrieved])
            
        print('{}: Elo claim for {}-{:02d} with value {} successfully added'.format(obj['QID'], obj['P585']['Y'], obj['P585']['M'], obj['P1087']))
    else:
        time.sleep(1) # wait 1 second to avoid reading too fast from the API
        
print('All done, task finished')
Sleeping for 5.0 seconds, 2020-06-08 13:06:15
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-1-bc6a1480f590> in <module>
     12     eloAlreadySet = False
     13 
---> 14     Qitem = pywikibot.ItemPage(repo, obj['QID'])
     15     Qitem.get()
     16     if Qitem.claims and 'P1087' in Qitem.claims:

/srv/paws/pwb/pywikibot/page/__init__.py in __init__(self, site, title, ns)
   4681         """
   4682         if ns is None:
-> 4683             ns = site.item_namespace
   4684         # Special case for empty item.
   4685         if title is None or title == '-1':

/srv/paws/pwb/pywikibot/site/__init__.py in item_namespace(self)
   7721         """
   7722         if self._item_namespace is None:
-> 7723             self._item_namespace = self.get_namespace_for_entity_type('item')
   7724         return self._item_namespace
   7725 

/srv/paws/pwb/pywikibot/site/__init__.py in get_namespace_for_entity_type(self, entity_type)
   7705         """
   7706         if not hasattr(self, '_entity_namespaces'):
-> 7707             self._cache_entity_namespaces()
   7708         if entity_type in self._entity_namespaces:
   7709             return self._entity_namespaces[entity_type]

/srv/paws/pwb/pywikibot/site/__init__.py in _cache_entity_namespaces(self)
   7688         self._entity_namespaces = {}
   7689         for entity_type in self._type_to_class.keys():
-> 7690             for namespace in self.namespaces.values():
   7691                 if not hasattr(namespace, 'defaultcontentmodel'):
   7692                     continue

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

/srv/paws/pwb/pywikibot/site/__init__.py in _build_namespaces(self)
   2653         _namespaces = {}
   2654 
-> 2655         for nsdata in self.siteinfo.get('namespaces', cache=False).values():
   2656             ns = nsdata.pop('id')
   2657             if ns == 0:

/srv/paws/pwb/pywikibot/site/__init__.py in get(self, key, get_default, cache, expiry)
   1680                 elif not Siteinfo._is_expired(cached[1], expiry):
   1681                     return copy.deepcopy(cached[0])
-> 1682         preloaded = self._get_general(key, expiry)
   1683         if not preloaded:
   1684             preloaded = self._get_siteinfo(key, expiry)[key]

/srv/paws/pwb/pywikibot/site/__init__.py in _get_general(self, key, expiry)
   1626                     .format("', '".join(props)), _logger)
   1627             props += ['general']
-> 1628             default_info = self._get_siteinfo(props, expiry)
   1629             for prop in props:
   1630                 self._cache[prop] = default_info[prop]

/srv/paws/pwb/pywikibot/site/__init__.py in _get_siteinfo(self, prop, expiry)
   1549         request._warning_handler = warn_handler
   1550         try:
-> 1551             data = request.submit()
   1552         except api.APIError as e:
   1553             if e.code == 'siunknown_siprop':

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2249         cached_available = self._load_cache()
   2250         if not cached_available:
-> 2251             self._data = super(CachedRequest, self).submit()
   2252             self._write_cache(self._data)
   2253         else:

/srv/paws/pwb/pywikibot/data/api.py in submit(self)
   2026                     lag = float(lag.group('lag')) if lag else 0.0
   2027 
-> 2028                 self.site.throttle.lag(lag * retries)
   2029                 continue
   2030 

/srv/paws/pwb/pywikibot/throttle.py in lag(self, lagtime)
    311             # account for any time we waited while acquiring the lock
    312             wait = delay - (time.time() - started)
--> 313             self.wait(wait)

/srv/paws/pwb/pywikibot/throttle.py in wait(self, seconds)
    254             pywikibot.log(message)
    255 
--> 256         time.sleep(seconds)
    257 
    258     def __call__(self, requestsize=1, write=False):

KeyboardInterrupt: 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]: