jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508072 )
Change subject: [bugfix] add CSRF token in sitelogout() api call
......................................................................
[bugfix] add CSRF token in sitelogout() api call
- Add missing CSRF token since {T25227: Use token when logging out}
is closed upstream, and tests that correspond to.
- site._relogin() was calling site.login() with self._loginstatus, but
this last one is an integer and login() excepts a bool. When login fails
(_relogin() usage), _loginstatus equals to -1 that is interpreted as
True, resulting in the usage of systop account even when it's not wanted.
- Using site.getuserinfo(force=True) at the end of logout() results of an
automatic re-login, since it is detected that the user has logged out
during that API call. So removing _userinfo attribute cleans the previous
login state.
Bug: T222508
Change-Id: Ia94254b0bfe95c4c13ca71211128f7a0b0fe78d6
---
M pywikibot/site.py
M tests/site_tests.py
2 files changed, 31 insertions(+), 4 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 6729954..9ea655c 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -2118,9 +2118,8 @@
from the site.
"""
del self._userinfo
- old_status = self._loginstatus
self._loginstatus = LoginStatus.NOT_LOGGED_IN
- self.login(old_status)
+ self.login()
def logout(self):
"""
@@ -2133,10 +2132,11 @@
"""
if self.is_oauth_token_available():
pywikibot.warning('Using OAuth suppresses logout function')
- uirequest = self._simple_request(action='logout')
+ uirequest = self._simple_request(action='logout',
+ token=self.tokens['csrf'])
uirequest.submit()
self._loginstatus = LoginStatus.NOT_LOGGED_IN
- self.getuserinfo(force=True)
+ del self._userinfo
def getuserinfo(self, force=False):
"""Retrieve userinfo from site and store in _userinfo attribute.
diff --git a/tests/site_tests.py b/tests/site_tests.py
index 705d194..d157f48 100644
--- a/tests/site_tests.py
+++ b/tests/site_tests.py
@@ -3703,6 +3703,33 @@
self.assertIsNone(page)
+class TestLoginLogout(DefaultSiteTestCase):
+
+ """Test for login and logout methods."""
+
+ def test_login_logout(self):
+ """Validate login and logout methods by toggling the state."""
+ site = self.get_site()
+ loginstatus = pywikibot.site.LoginStatus
+
+ self.assertFalse(site.logged_in())
+
+ site.login()
+ self.assertTrue(site.logged_in())
+ self.assertGreaterEqual(site._loginstatus, loginstatus.AS_USER)
+ self.assertIn('_userinfo', site.__dict__.keys())
+
+ self.assertIsNone(site.login())
+
+ site.logout()
+ self.assertFalse(site.logged_in())
+ self.assertEqual(site._loginstatus, loginstatus.NOT_LOGGED_IN)
+ self.assertNotIn('_userinfo', site.__dict__.keys())
+
+ self.assertRaisesRegexp(AssertionError,
+ 'User must login in this site', site.logout)
+
+
if __name__ == '__main__': # pragma: no cover
try:
unittest.main()
--
To view, visit https://gerrit.wikimedia.org/r/508072
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: Ia94254b0bfe95c4c13ca71211128f7a0b0fe78d6
Gerrit-Change-Number: 508072
Gerrit-PatchSet: 8
Gerrit-Owner: Framawiki <framawiki(a)tools.wmflabs.org>
Gerrit-Reviewer: Dvorapa <dvorapa(a)seznam.cz>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot (75)
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508076 )
Change subject: Simplify comparison code in date.py
......................................................................
Simplify comparison code in date.py
instead of "x < value and value < y" just use "x < value < y"
Change-Id: Ib999cbd86d3405fbeee9300ff1e7e661081c220b
---
M pywikibot/date.py
1 file changed, 20 insertions(+), 20 deletions(-)
Approvals:
Dvorapa: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/date.py b/pywikibot/date.py
index aecefd1..e54624f 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -1113,7 +1113,7 @@
(lambda v: dh(v, 'שנות ה־%d',
lambda i: encDec0(i) % 100,
lambda ii: 1900 + ii[0]),
- lambda p: p >= 1900 and p < 2000),
+ lambda p: 1900 <= p < 2000),
# This is a dummy value, just to avoid validation testing.
(lambda v: dh_decAD(v, '%dth decade'),
alwaysTrue)]), # ********** ERROR!!!
@@ -1176,7 +1176,7 @@
'pl': lambda m: multi(m, [
(lambda v: dh(v, 'Lata %d-%d',
lambda i: (encDec0(i), encDec0(i) + 9), decSinglVal),
- lambda p: p % 100 >= 0 and p % 100 < 20),
+ lambda p: 0 <= p % 100 < 20),
(lambda v: dh(v, 'Lata %d. %R wieku',
lambda i: (encDec0(i) % 100, encDec0(i) // 100 + 1),
lambda ii: (ii[1] - 1) * 100 + ii[0]),
@@ -2226,32 +2226,32 @@
# used exclusively by DecadeAD and DecadeBC to increment by 10 years.
# "and v%10==0" should be added to the limitation predicate for those two.
formatLimits = {
- 'MonthName': (lambda v: 1 <= v and v < 13, 1, 13),
- 'Number': (lambda v: 0 <= v and v < 1000000, 0, 1001),
- 'YearAD': (lambda v: 0 <= v and v < 2501, 0, 2501),
+ 'MonthName': (lambda v: 1 <= v < 13, 1, 13),
+ 'Number': (lambda v: 0 <= v < 1000000, 0, 1001),
+ 'YearAD': (lambda v: 0 <= v < 2501, 0, 2501),
# zh: has years as old as 前1700年
- 'YearBC': (lambda v: 0 <= v and v < 4001, 0, 501),
- 'DecadeAD': (lambda v: 0 <= v and v < 2501, 0, 2501),
+ 'YearBC': (lambda v: 0 <= v < 4001, 0, 501),
+ 'DecadeAD': (lambda v: 0 <= v < 2501, 0, 2501),
# zh: has decades as old as 前1700年代
- 'DecadeBC': (lambda v: 0 <= v and v < 4001, 0, 501),
+ 'DecadeBC': (lambda v: 0 <= v < 4001, 0, 501),
# Some centuries use Roman numerals or a given list
# do not exceed them in testing
- 'CenturyAD': (lambda v: 1 <= v and v < 41, 1, 23),
- 'CenturyBC': (lambda v: 1 <= v and v < 91, 1, 23),
- 'CenturyAD_Cat': (lambda v: 1 <= v and v < 41, 1, 23),
- 'CenturyBC_Cat': (lambda v: 1 <= v and v < 41, 1, 23),
+ 'CenturyAD': (lambda v: 1 <= v < 41, 1, 23),
+ 'CenturyBC': (lambda v: 1 <= v < 91, 1, 23),
+ 'CenturyAD_Cat': (lambda v: 1 <= v < 41, 1, 23),
+ 'CenturyBC_Cat': (lambda v: 1 <= v < 41, 1, 23),
# For millenniums, only test first 3 AD Millenniums and 1 BC Millennium
- 'MillenniumAD': (lambda v: 1 <= v and v < 6, 1, 4),
- 'MillenniumBC': (lambda v: 1 <= v and v < 20, 1, 2),
+ 'MillenniumAD': (lambda v: 1 <= v < 6, 1, 4),
+ 'MillenniumBC': (lambda v: 1 <= v < 20, 1, 2),
- 'Cat_Year_MusicAlbums': (lambda v: 1950 <= v and v < 2021, 1950, 2021),
- 'Cat_BirthsAD': (lambda v: 0 <= v and v < 2501, 0, 2501),
- 'Cat_DeathsAD': (lambda v: 0 <= v and v < 2501, 0, 2501),
- 'Cat_BirthsBC': (lambda v: 0 <= v and v < 4001, 0, 501),
- 'Cat_DeathsBC': (lambda v: 0 <= v and v < 4001, 0, 501),
- 'CurrEvents': (lambda v: 0 <= v and v < 1, 0, 1),
+ 'Cat_Year_MusicAlbums': (lambda v: 1950 <= v < 2021, 1950, 2021),
+ 'Cat_BirthsAD': (lambda v: 0 <= v < 2501, 0, 2501),
+ 'Cat_DeathsAD': (lambda v: 0 <= v < 2501, 0, 2501),
+ 'Cat_BirthsBC': (lambda v: 0 <= v < 4001, 0, 501),
+ 'Cat_DeathsBC': (lambda v: 0 <= v < 4001, 0, 501),
+ 'CurrEvents': (lambda v: 0 <= v < 1, 0, 1),
}
# All month of year articles are in the same format
--
To view, visit https://gerrit.wikimedia.org/r/508076
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: Ib999cbd86d3405fbeee9300ff1e7e661081c220b
Gerrit-Change-Number: 508076
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Dvorapa <dvorapa(a)seznam.cz>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: jenkins-bot (75)
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508075 )
Change subject: [cleanup] Replace similar codes with a function
......................................................................
[cleanup] Replace similar codes with a function
- delete _formatLimit_DayOfMonthXX and replace its behavior with
the _format_limit_dom function
Change-Id: I71ee1ddbc2d80d6e06fd2cc00a3386453060c876
---
M pywikibot/date.py
1 file changed, 10 insertions(+), 6 deletions(-)
Approvals:
Dvorapa: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/date.py b/pywikibot/date.py
index aecefd1..9ee9d21 100644
--- a/pywikibot/date.py
+++ b/pywikibot/date.py
@@ -2259,19 +2259,23 @@
for month in yrMnthFmts:
formatLimits[month] = _formatLimit_MonthOfYear
-_formatLimit_DayOfMonth31 = (lambda v: 1 <= v and v < 32, 1, 32)
-_formatLimit_DayOfMonth30 = (lambda v: 1 <= v and v < 31, 1, 31)
-_formatLimit_DayOfMonth29 = (lambda v: 1 <= v and v < 30, 1, 30)
+
+def _format_limit_dom(days):
+ """Return day of month format limit."""
+ assert days in range(29, 32)
+ return lambda v: 1 <= v <= days, 1, days + 1
+
+
for monthId in range(12):
if (monthId + 1) in (1, 3, 5, 7, 8, 10, 12):
# 31 days a month
- formatLimits[dayMnthFmts[monthId]] = _formatLimit_DayOfMonth31
+ formatLimits[dayMnthFmts[monthId]] = _format_limit_dom(31)
elif (monthId + 1) == 2: # February
# 29 days a month
- formatLimits[dayMnthFmts[monthId]] = _formatLimit_DayOfMonth29
+ formatLimits[dayMnthFmts[monthId]] = _format_limit_dom(29)
else:
# 30 days a month
- formatLimits[dayMnthFmts[monthId]] = _formatLimit_DayOfMonth30
+ formatLimits[dayMnthFmts[monthId]] = _format_limit_dom(30)
@deprecated('calendar.monthrange', since='20150707')
--
To view, visit https://gerrit.wikimedia.org/r/508075
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: I71ee1ddbc2d80d6e06fd2cc00a3386453060c876
Gerrit-Change-Number: 508075
Gerrit-PatchSet: 2
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: Dvorapa <dvorapa(a)seznam.cz>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: jenkins-bot (75)
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508074 )
Change subject: [doc] Fix doc warnings introduced in e235c320488f
......................................................................
[doc] Fix doc warnings introduced in e235c320488f
Change-Id: I8ab85e7a1672e771e830c3f2cd4ccd57c39e0ec3
---
M pywikibot/site.py
1 file changed, 3 insertions(+), 2 deletions(-)
Approvals:
Framawiki: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/site.py b/pywikibot/site.py
index 6729954..59da8df 100644
--- a/pywikibot/site.py
+++ b/pywikibot/site.py
@@ -7808,9 +7808,10 @@
Edit entity.
Note: This method is unable to create entities other than 'item'
- if dict with API parameters was passed to 'entity' parameter.
+ if dict with API parameters was passed to 'entity' parameter.
+
@param entity: Page to edit, or dict with API parameters
- to use for entity identification
+ to use for entity identification
@type entity: WikibasePage or dict
@param data: data updates
@type data: dict
--
To view, visit https://gerrit.wikimedia.org/r/508074
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: I8ab85e7a1672e771e830c3f2cd4ccd57c39e0ec3
Gerrit-Change-Number: 508074
Gerrit-PatchSet: 2
Gerrit-Owner: Dvorapa <dvorapa(a)seznam.cz>
Gerrit-Reviewer: 813gan <813gan(a)protonmail.com>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki(a)aol.com>
Gerrit-Reviewer: Framawiki <framawiki(a)tools.wmflabs.org>
Gerrit-Reviewer: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: Zoranzoki21 <zorandori4444(a)gmail.com>
Gerrit-Reviewer: jenkins-bot (75)
Xqt has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/337288 )
Change subject: Make code flat
......................................................................
Make code flat
Change-Id: I843c91fc18efc29947a98e35a6f2d537e86567c8
---
M pywikibot/cosmetic_changes.py
1 file changed, 99 insertions(+), 101 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/cosmetic_changes.py b/pywikibot/cosmetic_changes.py
index 7d35834..90847d1 100755
--- a/pywikibot/cosmetic_changes.py
+++ b/pywikibot/cosmetic_changes.py
@@ -53,7 +53,7 @@
"""
#
# (C) xqt, 2009-2018
-# (C) Pywikibot team, 2006-2018
+# (C) Pywikibot team, 2006-2019
#
# Distributed under the terms of the MIT license.
#
@@ -71,6 +71,7 @@
import pywikibot
from pywikibot import config, textlib
+from pywikibot.page import url2unicode
from pywikibot.textlib import (_MultiTemplateMatchBuilder, FILE_LINK_REGEX,
_get_regexes)
from pywikibot.tools import deprecated_args, first_lower, first_upper
@@ -511,112 +512,109 @@
except ValueError: # T111513
is_interwiki = True
- if not is_interwiki:
- # The link looks like this:
- # [[page_title|link_text]]trailing_chars
- # We only work on namespace 0 because pipes and linktrails work
- # differently for images and categories.
- page = pywikibot.Page(pywikibot.Link(titleWithSection,
- self.site))
- try:
- namespace = page.namespace()
- except pywikibot.InvalidTitle:
- return match.group()
- if namespace == 0:
- # Replace underlines by spaces, also multiple underlines
- titleWithSection = re.sub('_+', ' ', titleWithSection)
- # Remove double spaces
- titleWithSection = re.sub(' +', ' ', titleWithSection)
- # Remove unnecessary leading spaces from title,
- # but remember if we did this because we eventually want
- # to re-add it outside of the link later.
- titleLength = len(titleWithSection)
- titleWithSection = titleWithSection.lstrip()
- hadLeadingSpaces = (len(titleWithSection) != titleLength)
- hadTrailingSpaces = False
- # Remove unnecessary trailing spaces from title,
- # but remember if we did this because it may affect
- # the linktrail and because we eventually want to
- # re-add it outside of the link later.
- if not trailingChars:
- titleLength = len(titleWithSection)
- titleWithSection = titleWithSection.rstrip()
- hadTrailingSpaces = (len(titleWithSection)
- != titleLength)
+ if is_interwiki:
+ return match.group()
- # Convert URL-encoded characters to unicode
- from pywikibot.page import url2unicode
- titleWithSection = url2unicode(titleWithSection,
- encodings=self.site)
+ # The link looks like this:
+ # [[page_title|link_text]]trailing_chars
+ # We only work on namespace 0 because pipes and linktrails work
+ # differently for images and categories.
+ page = pywikibot.Page(pywikibot.Link(titleWithSection, self.site))
+ try:
+ in_main_namespace = page.namespace() == 0
+ except pywikibot.InvalidTitle:
+ in_main_namespace = False
+ if not in_main_namespace:
+ return match.group()
- if titleWithSection == '':
- # just skip empty links.
- return match.group()
+ # Replace underlines by spaces, also multiple underlines
+ titleWithSection = re.sub('_+', ' ', titleWithSection)
+ # Remove double spaces
+ titleWithSection = re.sub(' +', ' ', titleWithSection)
+ # Remove unnecessary leading spaces from title,
+ # but remember if we did this because we eventually want
+ # to re-add it outside of the link later.
+ titleLength = len(titleWithSection)
+ titleWithSection = titleWithSection.lstrip()
+ hadLeadingSpaces = len(titleWithSection) != titleLength
+ hadTrailingSpaces = False
+ # Remove unnecessary trailing spaces from title,
+ # but remember if we did this because it may affect
+ # the linktrail and because we eventually want to
+ # re-add it outside of the link later.
+ if not trailingChars:
+ titleLength = len(titleWithSection)
+ titleWithSection = titleWithSection.rstrip()
+ hadTrailingSpaces = len(titleWithSection) != titleLength
- # Remove unnecessary initial and final spaces from label.
- # Please note that some editors prefer spaces around pipes.
- # (See [[en:Wikipedia:Semi-bots]]). We remove them anyway.
- if label is not None:
- # Remove unnecessary leading spaces from label,
- # but remember if we did this because we want
- # to re-add it outside of the link later.
- labelLength = len(label)
- label = label.lstrip()
- hadLeadingSpaces = (len(label) != labelLength)
- # Remove unnecessary trailing spaces from label,
- # but remember if we did this because it affects
- # the linktrail.
- if not trailingChars:
- labelLength = len(label)
- label = label.rstrip()
- hadTrailingSpaces = (len(label) != labelLength)
- else:
- label = titleWithSection
- if trailingChars:
- label += trailingChars
+ # Convert URL-encoded characters to unicode
+ titleWithSection = url2unicode(titleWithSection,
+ encodings=self.site)
- if self.site.siteinfo['case'] == 'first-letter':
- firstcase_title = first_lower(titleWithSection)
- firstcase_label = first_lower(label)
- else:
- firstcase_title = titleWithSection
- firstcase_label = label
+ if not titleWithSection:
+ # just skip empty links.
+ return match.group()
- if firstcase_label == firstcase_title:
- newLink = '[[%s]]' % label
- # Check if we can create a link with trailing characters
- # instead of a pipelink
- elif (firstcase_label.startswith(firstcase_title)
- and trailR.sub('',
- label[len(titleWithSection):]) == ''):
- newLink = '[[%s]]%s' % (
- label[:len(titleWithSection)],
- label[len(titleWithSection):])
+ # Remove unnecessary initial and final spaces from label.
+ # Please note that some editors prefer spaces around pipes.
+ # (See [[en:Wikipedia:Semi-bots]]). We remove them anyway.
+ if label is not None:
+ # Remove unnecessary leading spaces from label,
+ # but remember if we did this because we want
+ # to re-add it outside of the link later.
+ labelLength = len(label)
+ label = label.lstrip()
+ hadLeadingSpaces = len(label) != labelLength
+ # Remove unnecessary trailing spaces from label,
+ # but remember if we did this because it affects
+ # the linktrail.
+ if not trailingChars:
+ labelLength = len(label)
+ label = label.rstrip()
+ hadTrailingSpaces = len(label) != labelLength
+ else:
+ label = titleWithSection
+ if trailingChars:
+ label += trailingChars
- else:
- # Try to capitalize the first letter of the title.
- # Not useful for languages that don't capitalize nouns.
- # TODO: Add a configuration variable for each site,
- # which determines if the link target is written in
- # uppercase
- if self.site.sitename == 'wikipedia:de':
- titleWithSection = first_upper(titleWithSection)
- newLink = '[[%s|%s]]' % (titleWithSection, label)
- # re-add spaces that were pulled out of the link.
- # Examples:
- # text[[ title ]]text -> text [[title]] text
- # text[[ title | name ]]text -> text [[title|name]] text
- # text[[ title |name]]text -> text[[title|name]]text
- # text[[title| name]]text -> text [[title|name]]text
- if hadLeadingSpaces and not newline:
- newLink = ' ' + newLink
- if hadTrailingSpaces:
- newLink = newLink + ' '
- if newline:
- newLink = newline + newLink
- return newLink
- # don't change anything
- return match.group()
+ if self.site.siteinfo['case'] == 'first-letter':
+ firstcase_title = first_lower(titleWithSection)
+ firstcase_label = first_lower(label)
+ else:
+ firstcase_title = titleWithSection
+ firstcase_label = label
+
+ if firstcase_label == firstcase_title:
+ newLink = '[[%s]]' % label
+ # Check if we can create a link with trailing characters
+ # instead of a pipelink
+ elif (firstcase_label.startswith(firstcase_title)
+ and trailR.sub('', label[len(titleWithSection):]) == ''):
+ newLink = '[[%s]]%s' % (label[:len(titleWithSection)],
+ label[len(titleWithSection):])
+
+ else:
+ # Try to capitalize the first letter of the title.
+ # Not useful for languages that don't capitalize nouns.
+ # TODO: Add a configuration variable for each site,
+ # which determines if the link target is written in
+ # uppercase
+ if self.site.sitename == 'wikipedia:de':
+ titleWithSection = first_upper(titleWithSection)
+ newLink = '[[%s|%s]]' % (titleWithSection, label)
+ # re-add spaces that were pulled out of the link.
+ # Examples:
+ # text[[ title ]]text -> text [[title]] text
+ # text[[ title | name ]]text -> text [[title|name]] text
+ # text[[ title |name]]text -> text[[title|name]]text
+ # text[[title| name]]text -> text [[title|name]]text
+ if hadLeadingSpaces and not newline:
+ newLink = ' ' + newLink
+ if hadTrailingSpaces:
+ newLink = newLink + ' '
+ if newline:
+ newLink = newline + newLink
+ return newLink
trailR = re.compile(self.site.linktrail())
# The regular expression which finds links. Results consist of four groups:
--
To view, visit https://gerrit.wikimedia.org/r/337288
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: I843c91fc18efc29947a98e35a6f2d537e86567c8
Gerrit-Change-Number: 337288
Gerrit-PatchSet: 6
Gerrit-Owner: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot (75)
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508017 )
Change subject: Refactor WikibasePage.get and overriding methods and improve documentation
......................................................................
Refactor WikibasePage.get and overriding methods and improve documentation
Document return values and add note to the method warning users
that modifying returned data could cause an undesired change
to the live content.
Also make use of dict.get and reorder declarations into
meaningful order (labels, descriptions, aliases, claims...).
Change-Id: I1bdefb6b4ed7789038adfd1b2e32138a56700d28
---
M pywikibot/page.py
1 file changed, 37 insertions(+), 27 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 0c3f1d2..20dbae6 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -3910,6 +3910,11 @@
@param force: override caching
@type force: bool
@raise NotImplementedError: a value in args or kwargs
+ @return: actual data which entity holds
+ @rtype: dict
+ @note: dicts returned by this method are references to content of this
+ entity and their modifying may indirectly cause unwanted change to
+ the live content
"""
if args or kwargs:
raise NotImplementedError(
@@ -3945,37 +3950,33 @@
if 'pageid' in self._content:
self._pageid = self._content['pageid']
- # aliases
- self.aliases = {}
- if 'aliases' in self._content:
- for lang in self._content['aliases']:
- self.aliases[lang] = []
- for value in self._content['aliases'][lang]:
- self.aliases[lang].append(value['value'])
-
# labels
self.labels = {}
- if 'labels' in self._content:
- for lang in self._content['labels']:
- if 'removed' not in self._content['labels'][lang]: # T56767
- self.labels[lang] = self._content['labels'][lang]['value']
+ for lang in self._content.get('labels', {}):
+ if 'removed' not in self._content['labels'][lang]: # T56767
+ self.labels[lang] = self._content['labels'][lang]['value']
# descriptions
self.descriptions = {}
- if 'descriptions' in self._content:
- for lang in self._content['descriptions']:
- self.descriptions[lang] = self._content[
- 'descriptions'][lang]['value']
+ for lang in self._content.get('descriptions', {}):
+ self.descriptions[lang] = self._content[
+ 'descriptions'][lang]['value']
+
+ # aliases
+ self.aliases = {}
+ for lang in self._content.get('aliases', {}):
+ self.aliases[lang] = []
+ for value in self._content['aliases'][lang]:
+ self.aliases[lang].append(value['value'])
# claims
self.claims = {}
- if 'claims' in self._content:
- for pid in self._content['claims']:
- self.claims[pid] = []
- for claim in self._content['claims'][pid]:
- c = Claim.fromJSON(self.repo, claim)
- c.on_item = self
- self.claims[pid].append(c)
+ for pid in self._content.get('claims', {}):
+ self.claims[pid] = []
+ for claim in self._content['claims'][pid]:
+ c = Claim.fromJSON(self.repo, claim)
+ c.on_item = self
+ self.claims[pid].append(c)
return {'aliases': self.aliases,
'labels': self.labels,
@@ -4489,6 +4490,11 @@
redirect, do not raise an exception.
@type get_redirect: bool
@raise NotImplementedError: a value in args or kwargs
+ @return: actual data which entity holds
+ @rtype: dict
+ @note: dicts returned by this method are references to content of this
+ entity and their modifying may indirectly cause unwanted change to
+ the live content
"""
data = super(ItemPage, self).get(force, *args, **kwargs)
@@ -4497,10 +4503,9 @@
# sitelinks
self.sitelinks = {}
- if 'sitelinks' in self._content:
- for dbname in self._content['sitelinks']:
- self.sitelinks[dbname] = self._content[
- 'sitelinks'][dbname]['title']
+ for dbname in self._content.get('sitelinks', {}):
+ self.sitelinks[dbname] = self._content[
+ 'sitelinks'][dbname]['title']
data['sitelinks'] = self.sitelinks
return data
@@ -4833,6 +4838,11 @@
@param force: override caching
@type force: bool
@raise NotImplementedError: a value in args or kwargs
+ @return: actual data which entity holds
+ @rtype: dict
+ @note: dicts returned by this method are references to content of this
+ entity and their modifying may indirectly cause unwanted change to
+ the live content
"""
if args or kwargs:
raise NotImplementedError(
--
To view, visit https://gerrit.wikimedia.org/r/508017
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: I1bdefb6b4ed7789038adfd1b2e32138a56700d28
Gerrit-Change-Number: 508017
Gerrit-PatchSet: 2
Gerrit-Owner: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot (75)
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508034 )
Change subject: Improve title patterns of WikibasePage extensions
......................................................................
Improve title patterns of WikibasePage extensions
Having ^ at the beginning of a pattern a text is
re.match'd against is pointless. Without ^$,
users can use the patterns for arbitrary string
matching (though we need to refactor the -1 title
handling first). Python 3.4 has a dedicated function
for matching without ^ and $ (re.fullmatch) but
we are still Python 2.7 compatible.
Change-Id: Id0a9b2fc74bd27873f100294c20d1aa6b587fe20
---
M pywikibot/page.py
1 file changed, 4 insertions(+), 3 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/page.py b/pywikibot/page.py
index 0c3f1d2..c78f962 100644
--- a/pywikibot/page.py
+++ b/pywikibot/page.py
@@ -4107,7 +4107,8 @@
if not hasattr(cls, 'title_pattern'):
return True
- return bool(re.match(cls.title_pattern, entity_id))
+ # todo: use re.fullmatch when Python 3.4+ required
+ return bool(re.match(cls.title_pattern + '$', entity_id))
@property
def latest_revision_id(self):
@@ -4340,7 +4341,7 @@
_cache_attrs = WikibasePage._cache_attrs + ('sitelinks',)
entity_type = 'item'
- title_pattern = r'^(Q[1-9]\d*|-1)$'
+ title_pattern = r'(Q[1-9]\d*|-1)'
def __init__(self, site, title=None, ns=None):
"""
@@ -4795,7 +4796,7 @@
_cache_attrs = WikibasePage._cache_attrs + ('_type',)
entity_type = 'property'
- title_pattern = r'^(P[1-9]\d*|-1)$'
+ title_pattern = r'(P[1-9]\d*|-1)'
def __init__(self, source, title=None, datatype=None):
"""
--
To view, visit https://gerrit.wikimedia.org/r/508034
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: Id0a9b2fc74bd27873f100294c20d1aa6b587fe20
Gerrit-Change-Number: 508034
Gerrit-PatchSet: 2
Gerrit-Owner: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: Matěj Suchánek <matejsuchanek97(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot (75)
Gerrit-CC: Dvorapa <dvorapa(a)seznam.cz>
jenkins-bot has submitted this change and it was merged. ( https://gerrit.wikimedia.org/r/508023 )
Change subject: [cleanup] check for existing strings directly
......................................................................
[cleanup] check for existing strings directly
- don't use "!=" operator if checking for an empty string
- don't use "elsif" or "else" if condition has a return statemant previously
Change-Id: Iaae83bbc3e98d84c0e2c55e9d9da0222b6919a7e
---
M scripts/commonscat.py
1 file changed, 13 insertions(+), 11 deletions(-)
Approvals:
Dvorapa: Looks good to me, approved
jenkins-bot: Verified
diff --git a/scripts/commonscat.py b/scripts/commonscat.py
index 9f59c0a..473db6a 100755
--- a/scripts/commonscat.py
+++ b/scripts/commonscat.py
@@ -279,34 +279,36 @@
currentCommonscatTarget, LinkText, Note) = commonscatLink
checkedCommonscatTarget = self.checkCommonscatLink(
currentCommonscatTarget)
+
if (currentCommonscatTarget == checkedCommonscatTarget):
# The current commonscat link is good
pywikibot.output('Commonscat link at {} to Category:{} is ok'
.format(page.title(),
currentCommonscatTarget))
return True
- elif checkedCommonscatTarget != '':
+
+ if checkedCommonscatTarget:
# We have a new Commonscat link, replace the old one
self.changeCommonscat(page, currentCommonscatTemplate,
currentCommonscatTarget,
primaryCommonscat,
checkedCommonscatTarget, LinkText, Note)
return True
- else:
- # Commonscat link is wrong
- commonscatLink = self.findCommonscatLink(page)
- if (commonscatLink != ''):
- self.changeCommonscat(page, currentCommonscatTemplate,
- currentCommonscatTarget,
- primaryCommonscat, commonscatLink)
- # TODO: if the commonsLink == '', should it be removed?
+
+ # Commonscat link is wrong
+ commonscatLink = self.findCommonscatLink(page)
+ if commonscatLink:
+ self.changeCommonscat(page, currentCommonscatTemplate,
+ currentCommonscatTarget,
+ primaryCommonscat, commonscatLink)
+ # TODO: if the commonsLink == '', should it be removed?
elif self.skipPage(page):
pywikibot.output('Found a template in the skip list. Skipping '
+ page.title())
else:
commonscatLink = self.findCommonscatLink(page)
- if (commonscatLink != ''):
+ if commonscatLink:
if commonscatLink == page.title():
textToAdd = '{{%s}}' % primaryCommonscat
else:
@@ -379,7 +381,7 @@
possibleCommonscat, linkText, Note) = commonscatLink
checkedCommonscat = self.checkCommonscatLink(
possibleCommonscat)
- if (checkedCommonscat != ''):
+ if checkedCommonscat:
pywikibot.output(
'Found link for {} at [[{}:{}]] to {}.'
.format(page.title(), ipage.site.code, ipage.title(),
--
To view, visit https://gerrit.wikimedia.org/r/508023
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-MessageType: merged
Gerrit-Change-Id: Iaae83bbc3e98d84c0e2c55e9d9da0222b6919a7e
Gerrit-Change-Number: 508023
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info(a)gno.de>
Gerrit-Reviewer: D3r1ck01 <xsavitar.wiki(a)aol.com>
Gerrit-Reviewer: Dvorapa <dvorapa(a)seznam.cz>
Gerrit-Reviewer: John Vandenberg <jayvdb(a)gmail.com>
Gerrit-Reviewer: jenkins-bot (75)