http://www.mediawiki.org/wiki/Special:Code/pywikipedia/11213

Revision: 11213
Author:   legoktm
Date:     2013-03-16 09:43:19 +0000 (Sat, 16 Mar 2013)
Log Message:
-----------
Add support for creating claims (not references)

*Clean up fromJSON logic
*Implement getType() method for properties
*Rename methods to use lowerCamelCase
*Some minor PEP8 fixes and other things

Modified Paths:
--------------
    branches/rewrite/pywikibot/page.py
    branches/rewrite/pywikibot/site.py

Modified: branches/rewrite/pywikibot/page.py
===================================================================
--- branches/rewrite/pywikibot/page.py  2013-03-16 02:47:23 UTC (rev 11212)
+++ branches/rewrite/pywikibot/page.py  2013-03-16 09:43:19 UTC (rev 11213)
@@ -2193,6 +2193,7 @@
         Page.__init__(self, site, title)
         if isinstance(self.site, pywikibot.site.DataSite):
             self.repo = self.site
+            self.id = title.lower()
         else:
             self.repo = self.site.data_repository()
 
@@ -2259,6 +2260,19 @@
                 'descriptions':self.descriptions,
                 }
 
+    def getID(self, numeric=False, force=False):
+        """
+        @param numeric Strip the first letter and return an int
+        @type numeric bool
+        @param force Force an update of new data
+        @type force bool
+        """
+        if not hasattr(self, 'id') or force:
+            self.get(force=force)
+        if numeric:
+            return int(self.id[1:])
+        return self.id
+
     def latestRevision(self):
         if not hasattr(self, 'lastrevid'):
             self.get()
@@ -2331,7 +2345,7 @@
                 'claims': self.claims
         }
 
-    def get_sitelink(self, site, force=False):
+    def getSitelink(self, site, force=False):
         """
         Returns a page object for the specific site
         site is a pywikibot.Site
@@ -2346,7 +2360,17 @@
         else:
             return self.sitelinks[dbname]
 
+    def addClaim(self, claim, bot=True):
+        """
+        Adds the claim to the item
+        @param claim The claim to add
+        @type claim Claim
+        @param bot Whether to flag as bot (if possible)
+        @type bot bool
+        """
+        self.repo.addClaim(self, claim, bot=bot)
 
+
 class PropertyPage(WikibasePage):
     """
     Any page in the property namespace
@@ -2359,12 +2383,21 @@
         if not self.id.startswith(u'p'):
             raise ValueError(u"'%s' is not a property page!" % self.title())
 
-    def get_type(self):
+    def get(self, force=False, *args):
+        if force or not hasattr(self, '_content'):
+            WikibasePage.get(self, force=force, *args)
+        self.type = self._content['datatype']
+
+    def getType(self):
         """
         Returns the type that this item uses
         Examples: item, commons media file, StringValue, NumericalValue
         """
-        raise NotImplementedError
+        if not hasattr(self, 'type'):
+            self.get()
+        if self.type == 'wikibase-entityid':
+            self.type = 'wikibase-item'
+        return self.type
 
 
 class QueryPage(WikibasePage):
@@ -2404,7 +2437,8 @@
             claim.snak = data['id']
         else:
             claim.isReference = True
-        if data['mainsnak']['datavalue']['type'] == 'wikibase-entityid':
+        claim.type = data['mainsnak']['datavalue']['type']
+        if claim.type == 'wikibase-entityid':
             claim.target = ItemPage(site, 'Q' +
                                           
str(data['mainsnak']['datavalue']['value']['numeric-id']))
         else:
@@ -2427,27 +2461,27 @@
         c.hash = data['hash']
         return c
 
-    def set_target(self, value):
+    def setTarget(self, value):
         """
         Sets the target to the passed value.
         There should be checks to ensure type compliance
         """
         self.target = value
 
-    def get_target(self):
+    def getTarget(self):
         """
         Returns object that the property is associated with.
         None is returned if no target is set
         """
         return self.target
 
-    def get_sources(self):
+    def getSources(self):
         """
         Returns a list of Claims
         """
         return self.sources
 
-    def add_source(self, source):
+    def addSource(self, source):
         """
         source is a Claim.
         adds it as a reference.

Modified: branches/rewrite/pywikibot/site.py
===================================================================
--- branches/rewrite/pywikibot/site.py  2013-03-16 02:47:23 UTC (rev 11212)
+++ branches/rewrite/pywikibot/site.py  2013-03-16 09:43:19 UTC (rev 11213)
@@ -29,6 +29,7 @@
 import threading
 import time
 import urllib
+import json
 
 _logger = "wiki.site"
 
@@ -3333,7 +3334,36 @@
             raise pywikibot.data.api.APIError, data['errors']
         return data['entities']
 
+    def addClaim(self, item, claim, bot=True):
 
+        params = dict(action='wbcreateclaim',
+                      entity=item.getID(),
+                      baserevid=item.latestRevision(),
+                      snaktype='value',
+                      property=claim.getID()
+        )
+        if bot:
+            params['bot'] = 1
+        if claim.getType() == 'wikibase-item':
+            params['value'] = json.dumps({'entity-type': 'item',
+                                          'numeric-id': 
claim.getTarget().getID(numeric=True)})
+        elif claim.getType() == 'string':
+            params['value'] = '"' + claim.getTarget() + '"'
+        else:
+            raise NotImplementedError('%s datatype is not supported yet.' % 
claim.getType())
+        params['token'] = self.token(item, 'edit')
+        req = api.Request(site=self, **params)
+        data = req.submit()
+        claim.snak = data['claim']['id']
+        #Update the item
+        if claim.getID() in item.claims:
+            item.claims[claim.getID()].append(claim)
+        else:
+            item.claims[claim.getID()] = [claim]
+        item.lastrevid = data['pageinfo']['lastrevid']
+
+
+
     # deprecated BaseSite methods
     def fam(self):
         raise NotImplementedError


_______________________________________________
Pywikipedia-svn mailing list
[email protected]
https://lists.wikimedia.org/mailman/listinfo/pywikipedia-svn

Reply via email to