John Vandenberg has uploaded a new change for review.

  https://gerrit.wikimedia.org/r/135410

Change subject: WIP: Improve support for items not stored in repo
......................................................................

WIP: Improve support for items not stored in repo

ItemPage initialiser allowed no value for title, however it would
cause all methods to fail, even exists()

Replace magic 'null' inside ItemPage.fromPage with '-1' as a consistent
way to refer to an item which does not have a Qxx allocated by the
repository.
- ItemPage.__init__ title = None uses title '-1'
- update getID() and title() to use '-1'

Add checking to ItemPage.fromPage to raise NoPage if page does not
exist, or does not have an item in the repository, simplifying error
handling in scripts.

After item.editEntity, refresh the item if a Q was allocated to it
by the repository.

This complements change Ibe77c51fc5cf3dae8ece533cc5787bf960f0ebed
allowing an empty item to be instantiated and populated before
submitting it to the repository.

WIP: add tests

Change-Id: Ibea8f84242a6e938882059f5d5fa28394b8a7a23
---
M pywikibot/page.py
1 file changed, 42 insertions(+), 16 deletions(-)


  git pull ssh://gerrit.wikimedia.org:29418/pywikibot/core 
refs/changes/10/135410/1

diff --git a/pywikibot/page.py b/pywikibot/page.py
index b40ec42..d16843a 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -2405,7 +2405,12 @@
     def title(self, **kwargs):
         if self.namespace() == 0:
             self._link._text = self.getID()
-            del self._link._title
+
+            # if instantiated via ItemPage.fromPage using site and title,
+            # remove the temporary values.
+            if self._link._text != '-1' and hasattr(self._link,'_title'):
+                del self._link._title
+                del self._link._site
         return Page(self).title(**kwargs)
 
     @deprecated("_defined_by")
@@ -2430,19 +2435,18 @@
             id = 'ids'
             site = 'sites'
             title = 'titles'
-        # id overrides all
-        if hasattr(self, 'id'):
-            params[id] = self.id
-            return params
 
-        # the rest only applies to ItemPages, but is still needed here.
-        if hasattr(self, '_site') and hasattr(self, '_title'):
+        # id overrides all
+        if hasattr(self, 'id') and self.id != '-1':
+            params[id] = self.id
+
+        # if instantiated via ItemPage.fromPage,
+        # look up using _site and _title
+        elif hasattr(self, '_title'):
             params[site] = self._site.dbName()
             params[title] = self._title
-        else:
-            quit()
-            params[id] = self.getID()
 
+        # if none of the above applies, this item cant be queried
         return params
 
     def exists(self):
@@ -2461,7 +2465,11 @@
         args can be used to specify custom props.
         """
         if force or not hasattr(self, '_content'):
-            data = self.repo.loadcontent(self._defined_by(), *args)
+            identification = self._defined_by()
+            if not identification:
+                raise pywikibot.NoPage(self)
+
+            data = self.repo.loadcontent(identification, *args)
             self.id = list(data.keys())[0]
             self._content = data[self.id]
         if 'lastrevid' in self._content:
@@ -2504,8 +2512,13 @@
         """
         if not hasattr(self, 'id') or force:
             self.get(force=force)
+
         if numeric:
-            return int(self.id[1:])
+            if self.id == '-1':
+                return -1
+            else:
+                return int(self.id[1:])
+
         return self.id
 
     def latestRevision(self):
@@ -2554,6 +2567,9 @@
                                        baserevid=baserevid, **kwargs)
         self.lastrevid = updates['entity']['lastrevid']
 
+        if not hasattr(self, 'id') or self.id == '-1':
+            self.__init__(self.site, title=updates['entity']['id'])
+
     def editLabels(self, labels, **kwargs):
         """
         Labels should be a dict, with the key
@@ -2601,26 +2617,35 @@
         @type site: pywikibot.site.DataSite
         @param title: id number of item, "Q###"
         """
-        super(ItemPage, self).__init__(site, title, ns=0)
-        self.id = title.upper()  # This might cause issues if not ns0?
+        if not title:
+            super(ItemPage, self).__init__(site, u'-1', ns=0)
+            self.id = u'-1'
+        else:
+            super(ItemPage, self).__init__(site, title, ns=0)
+            self.id = title.upper()  # This might cause issues if not ns0?
 
     @classmethod
-    def fromPage(cls, page):
+    def fromPage(cls, page, raise_nopage_exception=True):
         """
         Get the ItemPage based on a Page that links to it
         @param page: Page
         @return: ItemPage
         """
         repo = page.site.data_repository()
+        if raise_nopage_exception and not page.exists():
+            raise pywikibot.NoPage(page)
         if hasattr(page,
                    '_pageprops') and page.properties().get('wikibase_item'):
             # If we have already fetched the pageprops for something else,
             # we already have the id, so use it
             return cls(repo, page.properties().get('wikibase_item'))
-        i = cls(repo, 'null')
+        i = cls(repo)
+        # clear id, and temporarily store data to look up item in getID()
         del i.id
         i._site = page.site
         i._title = page.title()
+        if raise_nopage_exception and not i.exists():
+            raise pywikibot.NoPage(i)
         return i
 
     def get(self, force=False, *args):
@@ -2931,6 +2956,7 @@
             if not isinstance(value, types[self.getType()]):
                 raise ValueError("%s is not type %s."
                                  % (value, str(types[self.getType()])))
+        print 'setting value to %s' % value
         self.target = value
 
     def changeTarget(self, value=None, snaktype='value', **kwargs):

-- 
To view, visit https://gerrit.wikimedia.org/r/135410
To unsubscribe, visit https://gerrit.wikimedia.org/r/settings

Gerrit-MessageType: newchange
Gerrit-Change-Id: Ibea8f84242a6e938882059f5d5fa28394b8a7a23
Gerrit-PatchSet: 1
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Owner: John Vandenberg <[email protected]>

_______________________________________________
MediaWiki-commits mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/mediawiki-commits

Reply via email to