jenkins-bot has submitted this change and it was merged.
Change subject: [FEAT] UploadWarning uses the warning code ......................................................................
[FEAT] UploadWarning uses the warning code
To allow scripts easier to determine what the warning is about the UploadWarning contains an attribute 'code' which is the warning code recieved from the API.
The UploadWarning is now a subclass of APIError. This may break scripts which already parse the warning message but use 'str(exception)' instead of 'exception.message'.
The upload.py script uses this feature to allow abortion only because of specific warnings.
Bug: 69852 Change-Id: I78e572ce5e40e7cfcdfdf67138c8aa2e41bfebdb --- M pywikibot/__init__.py M pywikibot/data/api.py M pywikibot/exceptions.py M pywikibot/site.py M scripts/upload.py 5 files changed, 44 insertions(+), 20 deletions(-)
Approvals: John Vandenberg: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/__init__.py b/pywikibot/__init__.py index 59bb683..0d13cdf 100644 --- a/pywikibot/__init__.py +++ b/pywikibot/__init__.py @@ -36,7 +36,7 @@ Error, InvalidTitle, BadTitle, NoPage, SectionError, NoSuchSite, NoUsername, UserBlocked, PageRelatedError, IsRedirectPage, IsNotRedirectPage, - PageNotSaved, UploadWarning, LockedPage, EditConflict, + PageNotSaved, LockedPage, EditConflict, ServerError, FatalServerError, Server504Error, CaptchaError, SpamfilterError, CircularRedirect, WikiBaseError, CoordinateGlobeUnknownException, @@ -52,6 +52,7 @@ ) from pywikibot.tools import UnicodeMixin, deprecated, deprecate_arg from pywikibot.i18n import translate +from pywikibot.data.api import UploadWarning
__all__ = ( 'config', 'ui', 'UnicodeMixin', 'translate', 'deprecated', 'deprecate_arg', diff --git a/pywikibot/data/api.py b/pywikibot/data/api.py index 643369c..f295cde 100644 --- a/pywikibot/data/api.py +++ b/pywikibot/data/api.py @@ -46,7 +46,7 @@ lagpattern = re.compile(r"Waiting for [\d.]+: (?P<lag>\d+) seconds? lagged")
-class APIError(pywikibot.Error): +class APIError(Error):
"""The wiki site returned an error message."""
@@ -58,13 +58,26 @@ self.unicode = unicode(self.__str__())
def __repr__(self): - return 'APIError("%(code)s", "%(info)s", %(other)s)' % self.__dict__ + return '{name}("{code}", "{info}", {other})'.format( + name=self.__class__.__name__, **self.__dict__)
def __str__(self): return "%(code)s: %(info)s" % self.__dict__
-class TimeoutError(pywikibot.Error): +class UploadWarning(APIError): + + """Upload failed with a warning message (passed as the argument).""" + + def __init__(self, code, message): + super(UploadWarning, self).__init__(code, message) + + @property + def message(self): + return self.info + + +class TimeoutError(Error): pass
diff --git a/pywikibot/exceptions.py b/pywikibot/exceptions.py index 7f9a06d..35f7d2d 100644 --- a/pywikibot/exceptions.py +++ b/pywikibot/exceptions.py @@ -168,11 +168,6 @@ """Captcha is asked and config.solve_captcha == False."""
-class UploadWarning(Error): - - """Upload failed with a warning message (passed as the argument).""" - - class AutoblockUser(Error):
""" @@ -193,3 +188,7 @@ class CoordinateGlobeUnknownException(WikiBaseError, NotImplementedError):
""" This globe is not implemented yet in either WikiBase or pywikibot """ + +# TODO: Warn about the deprecated usage +import pywikibot.data.api +UploadWarning = pywikibot.data.api.UploadWarning diff --git a/pywikibot/site.py b/pywikibot/site.py index befcf3a..565389d 100644 --- a/pywikibot/site.py +++ b/pywikibot/site.py @@ -3944,7 +3944,7 @@ if "warnings" in result: warning = list(result["warnings"].keys())[0] message = result["warnings"][warning] - raise pywikibot.UploadWarning(upload_warnings[warning] + raise pywikibot.UploadWarning(warning, upload_warnings[warning] % {'msg': message}) elif "result" not in result: pywikibot.output(u"Upload: unrecognized response: %s" % result) diff --git a/scripts/upload.py b/scripts/upload.py index ba59729..8a9a44d 100755 --- a/scripts/upload.py +++ b/scripts/upload.py @@ -9,7 +9,8 @@ -filename Target filename -noverify Do not ask for verification of the upload description if one is given - -abortonwarn Abort upload on warning + -abortonwarn: Abort upload on the specified warning type. If no warning type + is specified abort on all warnings.
If any other arguments are given, the first is the URL or filename to upload, and the rest is a proposed description to go with the upload. If none of these @@ -34,6 +35,7 @@ import urlparse import tempfile import pywikibot +import pywikibot.data.api from pywikibot import config
@@ -41,7 +43,7 @@ def __init__(self, url, urlEncoding=None, description=u'', useFilename=None, keepFilename=False, verifyDescription=True, ignoreWarning=False, - targetSite=None, uploadByUrl=False, abortOnWarn=False): + targetSite=None, uploadByUrl=False, aborts=[]): """ @param ignoreWarning: Set this to True if you want to upload even if another file would be overwritten or another mistake would be @@ -55,7 +57,7 @@ self.keepFilename = keepFilename self.verifyDescription = verifyDescription self.ignoreWarning = ignoreWarning - self.abortOnWarn = abortOnWarn + self.aborts = aborts if config.upload_to_commons: self.targetSite = targetSite or pywikibot.Site('commons', 'commons') @@ -189,6 +191,13 @@ self.description = newDescription return filename
+ def abort_on_warn(self, warn_code): + """Determine if the warning message should cause an abort.""" + if self.aborts is True: + return True + else: + return warn_code in self.aborts + def upload_image(self, debug=False): """Upload the image at self.url to the target wiki.
@@ -217,10 +226,9 @@ site.upload(imagepage, source_filename=temp, ignore_warnings=self.ignoreWarning)
- except pywikibot.UploadWarning as warn: - pywikibot.output(u"We got a warning message: ", newline=False) - pywikibot.output(str(warn)) - if self.abortOnWarn: + except pywikibot.data.api.UploadWarning as warn: + pywikibot.output(u"We got a warning message: {0}".format(warn.message)) + if self.abort_on_warn(warn.code): answer = "N" else: answer = pywikibot.inputChoice(u"Do you want to ignore?", @@ -257,7 +265,7 @@ keepFilename = False useFilename = None verifyDescription = True - abortOnWarn = False + aborts = set()
# process all global bot args # returns a list of non-global args, i.e. args for upload.py @@ -270,7 +278,10 @@ elif arg.startswith('-noverify'): verifyDescription = False elif arg.startswith('-abortonwarn'): - abortOnWarn = True + if len(arg) > len('-abortonwarn:') and aborts is not True: + aborts.add(arg[len('-abortonwarn:'):]) + else: + aborts = True elif url == u'': url = arg else: @@ -279,7 +290,7 @@ bot = UploadRobot(url, description=description, useFilename=useFilename, keepFilename=keepFilename, verifyDescription=verifyDescription, - abortOnWarn=abortOnWarn) + aborts=aborts) bot.run()
if __name__ == "__main__":