Xqt has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328305?usp=email )
Change subject: wikibase: Reuse claim target during formatting
......................................................................
wikibase: Reuse claim target during formatting
Resolve the claim target once before selecting its Wikibase serialization.
This avoids repeated accessor calls and keeps every formatting branch on
the same target value.
Change-Id: I2018efa03f72e70f9acf24778b1ddf6edcf9c33a
---
M pywikibot/page/_wikibase.py
1 file changed, 10 insertions(+), 8 deletions(-)
Approvals:
Xqt: Verified; Looks good to me, approved
diff --git a/pywikibot/page/_wikibase.py b/pywikibot/page/_wikibase.py
index 4403d57..6d165da 100644
--- a/pywikibot/page/_wikibase.py
+++ b/pywikibot/page/_wikibase.py
@@ -2198,27 +2198,29 @@
:return: JSON value
"""
+ target = self.getTarget()
+
# TODO: eventually unify the following two groups
if self.type in ('wikibase-item', 'wikibase-property'):
- value = {'entity-type': self.getTarget().entity_type,
- 'numeric-id': self.getTarget().getID(numeric=True)}
+ value = {'entity-type': target.entity_type,
+ 'numeric-id': target.getID(numeric=True)}
elif self.type in (
'wikibase-lexeme', 'wikibase-form', 'wikibase-sense'):
- value = {'entity-type': self.getTarget().entity_type,
- 'id': self.getTarget().getID()}
+ value = {'entity-type': target.entity_type,
+ 'id': target.getID()}
elif self.type in ('string', 'url', 'math', 'external-id',
'musical-notation'):
- value = self.getTarget()
+ value = target
elif self.type == 'commonsMedia':
- value = self.getTarget().title(with_ns=False)
+ value = target.title(with_ns=False)
elif self.type in ('globe-coordinate', 'time',
'quantity', 'monolingualtext',
'geo-shape', 'tabular-data'):
- value = self.getTarget().toWikibase()
+ value = target.toWikibase()
else: # WbUnknown
pywikibot.warning(
f'{self.type} datatype is not supported yet.')
- value = self.getTarget().toWikibase()
+ value = target.toWikibase()
return value
def _formatDataValue(self) -> dict:
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328305?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I2018efa03f72e70f9acf24778b1ddf6edcf9c33a
Gerrit-Change-Number: 1328305
Gerrit-PatchSet: 2
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328725?usp=email )
Change subject: page: Do not validate sections in BasePage.get
......................................................................
page: Do not validate sections in BasePage.get
BasePage.get retrieves the complete page text regardless of a title
fragment. Move the existing best-effort raw-wikitext check to the
opt-in strict redirect path so ignore_section=False remains functional.
Bug: T422856
Bug: T422859
Change-Id: Ia86ddae21bb52e4bc8948a7bb984ebb5b15d663c
---
M ROADMAP.rst
M pywikibot/page/_basepage.py
M pywikibot/page/_page.py
M pywikibot/page/_wikibase.py
M pywikibot/site/_apisite.py
M tests/page_tests.py
6 files changed, 134 insertions(+), 32 deletions(-)
Approvals:
JJMC89: Looks good to me, approved
jenkins-bot: Verified
diff --git a/ROADMAP.rst b/ROADMAP.rst
index 941279c..3e7ad59 100644
--- a/ROADMAP.rst
+++ b/ROADMAP.rst
@@ -4,6 +4,9 @@
* Update translations (i18n)
* Add new :class:`family.WikimediaSubdomainFamily`
* Update documentation for :meth:`page.BasePage.exists`. (:phab:`T334341`)
+* :meth:`page.BasePage.get` no longer validates section fragments or raises
+ :exc:`exceptions.SectionError` for them (:phab:`T422856`,
+ :phab:`T422859`).
Deprecations
============
diff --git a/pywikibot/page/_basepage.py b/pywikibot/page/_basepage.py
index d7b4e4a..020c5d1 100644
--- a/pywikibot/page/_basepage.py
+++ b/pywikibot/page/_basepage.py
@@ -379,8 +379,10 @@
pywikibot.exceptions.IsRedirectPageError: ... is a redirect page.
.. version-changed:: 9.2
- :exc:`exceptions.SectionError` is raised if the
- :meth:`section` does not exist
+ Added validation for the section in the page title.
+ .. version-changed:: 11.8
+ A title fragment neither selects nor validates a section; the
+ complete page text is returned.
.. seealso:: :attr:`text` property
:param force: Reload all page attributes, including errors.
@@ -388,8 +390,6 @@
redirect, do not raise an exception.
:raises NoPageError: The page does not exist.
:raises IsRedirectPageError: The page is a redirect.
- :raises SectionError: The section does not exist on a page with
- a # link.
"""
if force:
del self.latest_revision_id
@@ -401,17 +401,7 @@
if not get_redirect:
raise
- text = self.latest_revision.text
-
- # check for valid section in title
- page_section = self.section()
- if page_section:
- content = textlib.extract_sections(text, self.site)
- if page_section not in content.sections:
- raise SectionError(f'{page_section!r} is not a valid section '
- f'of {self.title(with_section=False)}')
-
- return text
+ return self.latest_revision.text
def has_content(self) -> bool:
"""Page has been loaded.
@@ -2026,16 +2016,16 @@
<pywikibot.site._apisite.APISite.getredirtarget>`
* :meth:`moved_target`
- :param ignore_section: Do not include section to the target even
- the link has one
+ :param ignore_section: Skip checking the target section against raw
+ wikitext headings.
:raises CircularRedirectError: Page is a circular redirect
:raises InterwikiRedirectPageError: The redirect target is on
another site
:raises IsNotRedirectPageError: Page is not a redirect
:raises RuntimeError: No redirects found
- :raises SectionError: The section is not found on target page
- and *ignore_section* is not set
+ :raises SectionError: The section does not match a raw wikitext
+ heading on the target page and *ignore_section* is not set
"""
return self.site.getredirtarget(self, ignore_section=ignore_section)
diff --git a/pywikibot/page/_page.py b/pywikibot/page/_page.py
index ea213bc..6c1de70 100644
--- a/pywikibot/page/_page.py
+++ b/pywikibot/page/_page.py
@@ -23,6 +23,7 @@
IsNotRedirectPageError,
IsRedirectPageError,
NoPageError,
+ SectionError,
UnknownExtensionError,
)
from pywikibot.page._basepage import BasePage
@@ -45,6 +46,28 @@
'if source is a Site.')
super().__init__(source, title, ns)
+ def _check_section(self) -> None:
+ """Check the title section against headings in the raw wikitext.
+
+ This best-effort check supports strict redirect-target handling; it
+ does not reproduce MediaWiki's parser-generated anchors.
+
+ :raises SectionError: The section does not match an extracted heading.
+ """
+ page_section = self.section()
+ if not page_section:
+ return
+
+ try:
+ text = self.get(get_redirect=True)
+ except NoPageError:
+ return
+
+ content = textlib.extract_sections(text, self.site)
+ if page_section not in content.sections:
+ raise SectionError(f'{page_section!r} is not a valid section '
+ f'of {self.title(with_section=False)}')
+
@property
@cached
def raw_extracted_templates(self):
diff --git a/pywikibot/page/_wikibase.py b/pywikibot/page/_wikibase.py
index 87a0217..4403d57 100644
--- a/pywikibot/page/_wikibase.py
+++ b/pywikibot/page/_wikibase.py
@@ -1165,8 +1165,8 @@
.. seealso:: :meth:`page.BasePage.getRedirectTarget`
- :param ignore_section: Do not include section to the target even
- the link has one
+ :param ignore_section: Skip checking the target section against raw
+ wikitext headings.
:raises CircularRedirectError: Page is a circular redirect
:raises InterwikiRedirectPageError: The redirect target is on
@@ -1174,8 +1174,8 @@
:raises Error: Target page has wrong content model
:raises IsNotRedirectPageError: Page is not a redirect
:raises RuntimeError: No redirects found
- :raises SectionError: The section is not found on target page
- and *ignore_section* is not set
+ :raises SectionError: The section does not match a raw wikitext
+ heading on the target page and *ignore_section* is not set
"""
target = super().getRedirectTarget(ignore_section=ignore_section)
cmodel = target.content_model
diff --git a/pywikibot/site/_apisite.py b/pywikibot/site/_apisite.py
index c2d2303..012e909 100644
--- a/pywikibot/site/_apisite.py
+++ b/pywikibot/site/_apisite.py
@@ -1633,8 +1633,8 @@
.. seealso:: :meth:`page.BasePage.getRedirectTarget`
:param page: Page to search redirects for
- :param ignore_section: Do not include section to the target even
- the link has one
+ :param ignore_section: Skip checking the target section against raw
+ wikitext headings.
:return: Redirect target of page
:raises CircularRedirectError: Page is a circular redirect
@@ -1642,8 +1642,8 @@
another site
:raises IsNotRedirectPageError: Page is not a redirect
:raises RuntimeError: No redirects found
- :raises SectionError: The section is not found on target page
- and *ignore_section* is not set
+ :raises SectionError: The section does not match a raw wikitext
+ heading on the target page and *ignore_section* is not set
"""
if not self.page_isredirect(page):
raise IsNotRedirectPageError(page)
@@ -1726,8 +1726,7 @@
target = pywikibot.Category(target)
if not ignore_section:
- # get the content; this raises SectionError if section is not found
- target.text
+ target._check_section()
page._redirtarget = target
return page._redirtarget
diff --git a/tests/page_tests.py b/tests/page_tests.py
index 3f158cd..b12547f 100755
--- a/tests/page_tests.py
+++ b/tests/page_tests.py
@@ -186,6 +186,95 @@
section.assert_called_once_with()
+class TestPageGet(DefaultSiteTestCase):
+
+ """Test retrieving page text."""
+
+ dry = True
+
+ def _page_with_text(self, title: str, text: str) -> pywikibot.Page:
+ """Return a page with cached *text*."""
+ page = pywikibot.Page(self.site, title)
+ page._revid = 1
+ page._isredir = False
+ page._revisions[1] = pywikibot.page.Revision(
+ revid=1, slots={'main': {'*': text}})
+ return page
+
+ def test_get_does_not_validate_section(self) -> None:
+ """Test that get does not inspect a title section."""
+ text = '== Existing ==\nText'
+ page = self._page_with_text('Test#Missing', text)
+
+ with mock.patch.object(page, 'section') as section:
+ self.assertEqual(page.get(), text)
+ section.assert_not_called()
+
+ def test_text_section_regressions(self) -> None:
+ """Test parser-normalized headings do not affect page text."""
+ cases = (
+ (
+ 'T422856',
+ 'Test#Radio stations in India by state',
+ '==== Radio stations in India by state ====\nContent',
+ ),
+ (
+ 'T411307',
+ 'Test#Japanese superhero films by decade',
+ '==== Japanese superhero films\u200e by decade ====\nContent',
+ ),
+ )
+
+ for task, title, text in cases:
+ with self.subTest(task=task):
+ page = self._page_with_text(title, text)
+ self.assertEqual(page.text, text)
+
+ def test_check_section(self) -> None:
+ """Test explicit section validation."""
+ page = self._page_with_text('Test#Existing', '== Existing ==\nText')
+ page._check_section()
+
+ page = self._page_with_text('Test#Missing', '== Existing ==\nText')
+
+ with self.assertRaisesRegex(SectionError,
+ "'Missing' is not a valid section"):
+ page._check_section()
+
+ def test_check_section_missing_page(self) -> None:
+ """Test strict redirect checking preserves a missing target."""
+ page = pywikibot.Page(self.site, 'Missing#Section')
+ page._getexception = NoPageError(page)
+
+ page._check_section()
+
+ def test_redirect_target_checks_section(self) -> None:
+ """Test explicit redirect section validation is preserved."""
+ page = pywikibot.Page(self.site, 'Redirect')
+ page._isredir = True
+ data = {
+ 'query': {
+ 'redirects': [{
+ 'from': 'Redirect',
+ 'to': 'Target',
+ 'tofragment': 'Section',
+ }],
+ 'pages': {'1': {'title': 'Target'}},
+ },
+ }
+ request = mock.Mock()
+ request.submit.return_value = data
+
+ with mock.patch.object(self.site, 'simple_request',
+ return_value=request):
+ with mock.patch.object(
+ pywikibot.Page, '_check_section') as check_section:
+ target = page.getRedirectTarget(ignore_section=False)
+
+ self.assertEqual(target.title(), 'Target#Section')
+ check_section.assert_called_once_with()
+
+
class TestPageObjectEnglish(TestCase):
"""Test Page Object using English Wikipedia."""
@@ -1052,9 +1141,7 @@
p3.get()
page = pywikibot.Page(site, 'User:Legoktm/R2#Section')
- with self.assertRaisesRegex(SectionError,
- "'Section' is not a valid section"):
- page.get()
+ self.assertEqual(page.get(), text)
site = pywikibot.Site('mediawiki')
page = pywikibot.Page(site, 'Manual:Pywikibot/2.0 #See_also')
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328725?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ia86ddae21bb52e4bc8948a7bb984ebb5b15d663c
Gerrit-Change-Number: 1328725
Gerrit-PatchSet: 3
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: JJMC89 <JJMC89.Wikimedia(a)gmail.com>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328322?usp=email )
Change subject: checkimages: Use search for boolean regex checks
......................................................................
checkimages: Use search for boolean regex checks
Stop regex checks at the first match when only truthiness matters.
Check the site code before running the Italian-only filename regex.
Change-Id: I1ecb23bab97c0b2af681206f995097f8790c4e32
---
M scripts/checkimages.py
1 file changed, 8 insertions(+), 9 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
JJMC89: Looks good to me, approved
diff --git a/scripts/checkimages.py b/scripts/checkimages.py
index 4689414..ee58463 100755
--- a/scripts/checkimages.py
+++ b/scripts/checkimages.py
@@ -839,8 +839,8 @@
# project.
return False
- if re.findall(r'\bstemma\b',
- self.image_name.lower()) and self.site.code == 'it':
+ if self.site.code == 'it' and re.search(
+ r'\bstemma\b', self.image_name.lower()):
pywikibot.info(f"{self.image_name} has 'stemma' inside, means "
f"that it's ok.")
return True
@@ -922,8 +922,8 @@
except NoPageError:
continue
- if not (re.findall(dup_regex, dup_page_text)
- or re.findall(dup_regex, older_page_text)):
+ if not (re.search(dup_regex, dup_page_text)
+ or re.search(dup_regex, older_page_text)):
pywikibot.info(
f'{dup_page} is a duplicate and has to be tagged...')
images_to_tag_list.append(dup_page.title())
@@ -1205,7 +1205,7 @@
if not self.licenses_found and templates_in_the_image_raw:
# {{nameTemplate|something <- this is not a template, be sure
# that we haven't catch something like that.
- licenses_test = regex_are_licenses.findall(
+ licenses_test = regex_are_licenses.search(
self.image_check_text)
if not self.licenses_found and licenses_test:
raise Error(
@@ -1361,8 +1361,7 @@
regex_pattern = re.compile(
r'\{\{(?:template)?%s ?(?:\||\r?\n|\}|<|/) ?'
% i.split('{{')[1].replace(' ', '[ _]'), re.IGNORECASE)
- result = regex_pattern.findall(self.image_check_text)
- if result:
+ if regex_pattern.search(self.image_check_text):
return True
elif i.lower() in self.image_check_text:
return True
@@ -1407,8 +1406,8 @@
self.mex_used = mex_catched
break
elif find_type.lower() == 'find' \
- and re.findall(fr'{k.lower()}',
- image_check_text_lower):
+ and re.search(fr'{k.lower()}',
+ image_check_text_lower):
self.some_problem = True
self.text_used = text
self.head_used = head_2
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1328322?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I1ecb23bab97c0b2af681206f995097f8790c4e32
Gerrit-Change-Number: 1328322
Gerrit-PatchSet: 3
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: JJMC89 <JJMC89.Wikimedia(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1329383?usp=email )
Change subject: docs: Correct examples and script descriptions
......................................................................
docs: Correct examples and script descriptions
Accept varargs in the sample main function so handle_args receives the documented arguments.
Fix a misspelled import, stale script names, and the replace script summary.
Change-Id: Iadad4e0ea2a675c2830724f44cc3e039516d2ad9
---
M README.rst
M docs/recipes.rst
M scripts/README.rst
3 files changed, 6 insertions(+), 8 deletions(-)
Approvals:
JJMC89: Looks good to me, approved
jenkins-bot: Verified
diff --git a/README.rst b/README.rst
index 642df97..81ae5fc 100644
--- a/README.rst
+++ b/README.rst
@@ -115,7 +115,7 @@
text += '\n' + self.opt.text
self.put_current(text, summary=self.opt.summary)
- def main():
+ def main(*args: str) -> None:
"""Parse command line arguments and invoke bot."""
options = {}
gen_factory = pagegenerators.GeneratorFactory()
diff --git a/docs/recipes.rst b/docs/recipes.rst
index cfa3487..9f5b70c 100644
--- a/docs/recipes.rst
+++ b/docs/recipes.rst
@@ -17,7 +17,7 @@
=============================================
>>> import pywikibot
->>> from pwikibot import textlib
+>>> from pywikibot import textlib
>>> site = pywikibot.Site('wikipedia:en') # create a Site object
>>> page = pywikibot.Page(site, 'Deep learning') # create a Page object
>>> sect = textlib.extract_sections(page.text, site) # divide content into sections
diff --git a/scripts/README.rst b/scripts/README.rst
index 6d9a38d..46304c8 100644
--- a/scripts/README.rst
+++ b/scripts/README.rst
@@ -51,7 +51,7 @@
+--------------------------+---------------------------------------------------------+
| basic.py | Is a template from which simple bots can be made. |
+--------------------------+---------------------------------------------------------+
-| blockpagechecker.py | Deletes any protection templates that are on pages |
+| blockpageschecker.py | Deletes any protection templates that are on pages |
| | which aren't actually protected. |
+--------------------------+---------------------------------------------------------+
| category.py | Add a category link to all pages mentioned on a page, |
@@ -145,10 +145,8 @@
| | without title and fetch the html title from the link to |
| | use it as the title of the wiki link in the reference. |
+--------------------------+---------------------------------------------------------+
-| replace.py | Search articles for a text and replace it by another |
-| | text. Both text are set in two configurable |
-| | text files. The bot can either work on a set of given |
-| | pages or crawl an SQL dump. |
+| replace.py | Replaces text on pages using command-line pairs, |
+| | a pairs file, or predefined fixes. |
+--------------------------+---------------------------------------------------------+
| replicate_wiki.py | Replicates pages in wiki to a second wiki within family |
+--------------------------+---------------------------------------------------------+
@@ -179,7 +177,7 @@
+--------------------------+---------------------------------------------------------+
| upload.py | Upload an image to a wiki. |
+--------------------------+---------------------------------------------------------+
-| watchlists.py | Allows access to the account's watchlist. |
+| watchlist.py | Allows access to the account's watchlist. |
+--------------------------+---------------------------------------------------------+
| weblinkchecker.py | Check if external links are still working. |
+--------------------------+---------------------------------------------------------+
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1329383?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Iadad4e0ea2a675c2830724f44cc3e039516d2ad9
Gerrit-Change-Number: 1329383
Gerrit-PatchSet: 1
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: JJMC89 <JJMC89.Wikimedia(a)gmail.com>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1326320?usp=email )
Change subject: pagegenerators: Reuse page title in ignore filter
......................................................................
pagegenerators: Reuse page title in ignore filter
Read each page title once while applying configured ignore patterns.
Reuse the same value for every regex and the optional verbose message.
Change-Id: I2aec1be49da31e420cf3c234234edce2c97273ed
---
M pywikibot/pagegenerators/_filters.py
1 file changed, 6 insertions(+), 6 deletions(-)
Approvals:
Xqt: Looks good to me, approved
jenkins-bot: Verified
diff --git a/pywikibot/pagegenerators/_filters.py b/pywikibot/pagegenerators/_filters.py
index 190bb13..32aa660 100644
--- a/pywikibot/pagegenerators/_filters.py
+++ b/pywikibot/pagegenerators/_filters.py
@@ -94,20 +94,20 @@
language codes are mapped to lists of page titles. Each title must
be a valid regex as they are compared using :py:obj:`re.search`.
"""
- def is_ignored(page: pywikibot.page.BasePage) -> bool:
+ for page in generator:
try:
site_ig_list = ignore_list[page.site.family.name][page.site.code]
except KeyError:
- return False
- return any(re.search(ig, page.title()) for ig in site_ig_list)
+ yield page
+ continue
- for page in generator:
- if not is_ignored(page):
+ page_title = page.title()
+ if not any(re.search(ig, page_title) for ig in site_ig_list):
yield page
continue
if config.verbose_output:
- pywikibot.info(f'Ignoring page {page.title()}')
+ pywikibot.info(f'Ignoring page {page_title}')
def RedirectFilterPageGenerator(
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1326320?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I2aec1be49da31e420cf3c234234edce2c97273ed
Gerrit-Change-Number: 1326320
Gerrit-PatchSet: 2
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot
jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1326315?usp=email )
Change subject: api: Keep encoded parameter values distinct
......................................................................
api: Keep encoded parameter values distinct
Use separate names for singleton, formatted, and encoded request values.
This makes each transformation explicit without changing serialization.
Change-Id: I026c39e6204fa8e0af1f874cb1f7b784f995791a
---
M pywikibot/data/api/_requests.py
1 file changed, 11 insertions(+), 9 deletions(-)
Approvals:
jenkins-bot: Verified
Xqt: Looks good to me, approved
diff --git a/pywikibot/data/api/_requests.py b/pywikibot/data/api/_requests.py
index e0b263e..e1ed5cf 100644
--- a/pywikibot/data/api/_requests.py
+++ b/pywikibot/data/api/_requests.py
@@ -475,36 +475,38 @@
:return: Parameters either in the site encoding, or ASCII
strings
"""
- params = {}
+ params: dict[str, str | bytes] = {}
for key, values in self._params.items():
try:
iterator = values.api_iter()
except AttributeError:
if len(values) == 1:
- value = values[0]
- if value is True:
+ single_value = values[0]
+ if single_value is True:
values = ['']
- elif value is False or value is None:
+ elif single_value is False or single_value is None:
# False and None are not included in the http URI
continue
iterator = iter(values)
- value = '|'.join(self._format_value(value) for value in iterator)
+ formatted_value = '|'.join(
+ self._format_value(item) for item in iterator)
+ param_value: str | bytes = formatted_value
# If the value is encodable as ascii, do not encode it.
# This means that any value which can be encoded as ascii
# is presumed to be ascii, and servers using a site encoding
# which is not a superset of ascii may be problematic.
try:
- value.encode('ascii')
+ formatted_value.encode('ascii')
except UnicodeError:
try:
- value = value.encode(self.site.encoding())
+ param_value = formatted_value.encode(self.site.encoding())
except Exception:
pywikibot.error(
f'_encoded_items: {key!r} could not be encoded as '
- f'{self.site.encoding()!r}: {value!r}')
+ f'{self.site.encoding()!r}: {formatted_value!r}')
assert key.encode('ascii')
assert isinstance(key, str)
- params[key] = value
+ params[key] = param_value
return params
def _http_param_string(self):
--
To view, visit https://gerrit.wikimedia.org/r/c/pywikibot/core/+/1326315?usp=email
To unsubscribe, or for help writing mail filters, visit https://gerrit.wikimedia.org/r/settings?usp=email
Gerrit-MessageType: merged
Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: I026c39e6204fa8e0af1f874cb1f7b784f995791a
Gerrit-Change-Number: 1326315
Gerrit-PatchSet: 2
Gerrit-Owner: Mahveotm <mahveotm(a)gmail.com>
Gerrit-Reviewer: Xqt <info(a)gno.de>
Gerrit-Reviewer: jenkins-bot