From 6fbe20caaa11c4cf4ae3b56b66f54bf7957a6e6e Mon Sep 17 00:00:00 2001 From: tundebabzy Date: Thu, 11 May 2017 06:21:59 +0100 Subject: [PATCH] Except and raise statement python 3 compatible style (#3216) * changes exception and raise statements to python 3 style * changes except statement to python 3 style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * changes except and raise statement to python 3 compatible style * adds six.reraise to fix python 3 style raise statements with traceback * fixes indentation --- frappe/app.py | 10 ++++----- frappe/build.py | 2 +- frappe/core/doctype/communication/comment.py | 4 ++-- frappe/core/doctype/communication/email.py | 2 +- frappe/core/doctype/doctype/doctype.py | 6 +++--- frappe/core/doctype/file/file.py | 4 ++-- frappe/core/page/data_import_tool/importer.py | 2 +- .../doctype/customize_form/customize_form.py | 2 +- frappe/database.py | 6 +++--- .../desk/doctype/bulk_update/bulk_update.py | 2 +- .../desk/doctype/desktop_icon/desktop_icon.py | 4 ++-- frappe/desk/doctype/todo/todo.py | 2 +- frappe/desk/form/save.py | 2 +- frappe/desk/like.py | 2 +- frappe/desk/moduleview.py | 2 +- frappe/desk/notifications.py | 2 +- frappe/desk/tags.py | 6 +++--- frappe/email/__init__.py | 2 +- .../doctype/email_account/email_account.py | 4 ++-- .../doctype/email_domain/email_domain.py | 2 +- frappe/email/queue.py | 2 +- frappe/email/receive.py | 10 ++++----- frappe/email/smtp.py | 18 +++++++--------- .../dropbox_settings/dropbox_settings.py | 8 +++---- frappe/integrations/utils.py | 4 ++-- frappe/model/base_document.py | 21 +++++++++++-------- frappe/model/db_schema.py | 10 ++++----- frappe/model/document.py | 12 +++++------ frappe/model/meta.py | 4 ++-- frappe/model/rename_doc.py | 4 ++-- frappe/oauth.py | 2 +- .../patches/v4_0/rename_sitemap_to_route.py | 2 +- frappe/patches/v4_2/set_assign_in_doc.py | 2 +- .../patches/v5_0/fix_text_editor_file_urls.py | 2 +- .../v5_0/rename_ref_type_fieldnames.py | 4 ++-- .../v6_19/comment_feed_communication.py | 2 +- frappe/patches/v7_0/re_route.py | 2 +- .../v7_2/set_in_standard_filter_property.py | 2 +- frappe/test_runner.py | 2 +- frappe/utils/__init__.py | 2 +- frappe/utils/background_jobs.py | 2 +- frappe/utils/dateutils.py | 12 +++++------ frappe/utils/error.py | 2 +- frappe/utils/file_manager.py | 2 +- frappe/utils/help.py | 2 +- frappe/utils/jinja.py | 2 +- frappe/utils/password.py | 2 +- frappe/utils/pdf.py | 2 +- frappe/utils/scheduler.py | 2 +- frappe/utils/user.py | 2 +- frappe/website/render.py | 8 +++---- frappe/website/router.py | 2 +- 52 files changed, 112 insertions(+), 111 deletions(-) diff --git a/frappe/app.py b/frappe/app.py index 4536bdaf51..2042bfecb6 100644 --- a/frappe/app.py +++ b/frappe/app.py @@ -55,8 +55,8 @@ def application(request): response = frappe.handler.handle() elif frappe.request.path.startswith("/api/"): - if frappe.local.form_dict.data is None: - frappe.local.form_dict.data = request.get_data() + if frappe.local.form_dict.data is None: + frappe.local.form_dict.data = request.get_data() response = frappe.api.handle() elif frappe.request.path.startswith('/backups'): @@ -71,13 +71,13 @@ def application(request): else: raise NotFound - except HTTPException, e: + except HTTPException as e: return e - except frappe.SessionStopped, e: + except frappe.SessionStopped as e: response = frappe.utils.response.handle_session_stopped() - except Exception, e: + except Exception as e: response = handle_exception(e) else: diff --git a/frappe/build.py b/frappe/build.py index be43ce1d88..ddc7e799bb 100644 --- a/frappe/build.py +++ b/frappe/build.py @@ -113,7 +113,7 @@ def get_build_maps(): source_paths.append(s) build_maps[target] = source_paths - except ValueError, e: + except ValueError as e: print(path) print('JSON syntax error {0}'.format(str(e))) return build_maps diff --git a/frappe/core/doctype/communication/comment.py b/frappe/core/doctype/communication/comment.py index 12c31a3e6b..96c3e59d84 100644 --- a/frappe/core/doctype/communication/comment.py +++ b/frappe/core/doctype/communication/comment.py @@ -103,7 +103,7 @@ def get_comments_from_parent(doc): try: _comments = frappe.db.get_value(doc.reference_doctype, doc.reference_name, "_comments") or "[]" - except Exception, e: + except Exception as e: if e.args[0] in (1146, 1054): # 1146 = no table # 1054 = missing column @@ -129,7 +129,7 @@ def update_comments_in_parent(reference_doctype, reference_name, _comments): frappe.db.sql("""update `tab%s` set `_comments`=%s where name=%s""" % (reference_doctype, "%s", "%s"), (json.dumps(_comments), reference_name)) - except Exception, e: + except Exception as e: if e.args[0] == 1054 and getattr(frappe.local, 'request', None): # missing column and in request, add column and update after commit frappe.local._comments = (getattr(frappe.local, "_comments", []) diff --git a/frappe/core/doctype/communication/email.py b/frappe/core/doctype/communication/email.py index ecbf2bdb6a..9751b0967f 100755 --- a/frappe/core/doctype/communication/email.py +++ b/frappe/core/doctype/communication/email.py @@ -423,7 +423,7 @@ def sendmail(communication_name, print_html=None, print_format=None, attachments communication._notify(print_html=print_html, print_format=print_format, attachments=attachments, recipients=recipients, cc=cc) - except MySQLdb.OperationalError, e: + except MySQLdb.OperationalError as e: # deadlock, try again if e.args[0]==1213: frappe.db.rollback() diff --git a/frappe/core/doctype/doctype/doctype.py b/frappe/core/doctype/doctype/doctype.py index 89a4bbb4e5..37298b07f1 100644 --- a/frappe/core/doctype/doctype/doctype.py +++ b/frappe/core/doctype/doctype/doctype.py @@ -458,7 +458,7 @@ def validate_fields(meta): group by `{fieldname}` having count(*) > 1 limit 1""".format( doctype=d.parent, fieldname=d.fieldname)) - except MySQLdb.OperationalError, e: + except MySQLdb.OperationalError as e: if e.args and e.args[0]==1054: # ignore if missing column, else raise # this happens in case of Custom Field @@ -723,9 +723,9 @@ def make_module_and_roles(doc, perm_fieldname="permissions"): r = frappe.get_doc(dict(doctype= "Role", role_name=role, desk_access=1)) r.flags.ignore_mandatory = r.flags.ignore_permissions = True r.insert() - except frappe.DoesNotExistError, e: + except frappe.DoesNotExistError as e: pass - except frappe.SQLError, e: + except frappe.SQLError as e: if e.args[0]==1146: pass else: diff --git a/frappe/core/doctype/file/file.py b/frappe/core/doctype/file/file.py index cd7c09ca3b..fa1c79eb3c 100755 --- a/frappe/core/doctype/file/file.py +++ b/frappe/core/doctype/file/file.py @@ -363,12 +363,12 @@ def get_local_image(file_url): return image, filename, extn def get_web_image(file_url): - # downlaod + # download file_url = frappe.utils.get_url(file_url) r = requests.get(file_url, stream=True) try: r.raise_for_status() - except requests.exceptions.HTTPError, e: + except requests.exceptions.HTTPError as e: if "404" in e.args[0]: frappe.msgprint(_("File '{0}' not found").format(file_url)) else: diff --git a/frappe/core/page/data_import_tool/importer.py b/frappe/core/page/data_import_tool/importer.py index 372d8dd66f..a57bf1543f 100644 --- a/frappe/core/page/data_import_tool/importer.py +++ b/frappe/core/page/data_import_tool/importer.py @@ -313,7 +313,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False, if submit_after_import: doc.submit() log('Submitted row (#%d) %s' % (row_idx + 1, as_link(doc.doctype, doc.name))) - except Exception, e: + except Exception as e: error = True if doc: frappe.errprint(doc if isinstance(doc, dict) else doc.as_dict()) diff --git a/frappe/custom/doctype/customize_form/customize_form.py b/frappe/custom/doctype/customize_form/customize_form.py index 7e987b36ac..e42f617a39 100644 --- a/frappe/custom/doctype/customize_form/customize_form.py +++ b/frappe/custom/doctype/customize_form/customize_form.py @@ -301,7 +301,7 @@ class CustomizeForm(Document): else: try: property_value = frappe.db.get_value("DocType", self.doc_type, property_name) - except Exception, e: + except Exception as e: if e.args[0]==1054: property_value = None else: diff --git a/frappe/database.py b/frappe/database.py index da360478c0..5a960b6998 100644 --- a/frappe/database.py +++ b/frappe/database.py @@ -148,7 +148,7 @@ class Database: self._cursor.execute(query) - except Exception, e: + except Exception as e: # ignore data definition errors if ignore_ddl and e.args[0] in (1146,1054,1091): pass @@ -217,7 +217,7 @@ class Database: could cause the system to hang.""" if self.transaction_writes and \ query and query.strip().split()[0].lower() in ['start', 'alter', 'drop', 'create', "begin", "truncate"]: - raise Exception, 'This statement can cause implicit commit' + raise Exception('This statement can cause implicit commit') if query and query.strip().lower() in ('commit', 'rollback'): self.transaction_writes = 0 @@ -455,7 +455,7 @@ class Database: if (filters is not None) and (filters!=doctype or doctype=="DocType"): try: out = self._get_values_from_table(fields, filters, doctype, as_dict, debug, order_by, update) - except Exception, e: + except Exception as e: if ignore and e.args[0] in (1146, 1054): # table or column not found, return None out = None diff --git a/frappe/desk/doctype/bulk_update/bulk_update.py b/frappe/desk/doctype/bulk_update/bulk_update.py index 0bb7d60eff..e5c0be1d55 100644 --- a/frappe/desk/doctype/bulk_update/bulk_update.py +++ b/frappe/desk/doctype/bulk_update/bulk_update.py @@ -32,7 +32,7 @@ def update(doctype, field, value, condition='', limit=500): try: doc.save() - except Exception, e: + except Exception as e: frappe.msgprint(_("Validation failed for {0}").format(frappe.bold(doc.name))) raise e diff --git a/frappe/desk/doctype/desktop_icon/desktop_icon.py b/frappe/desk/doctype/desktop_icon/desktop_icon.py index c5397f2763..a2d5ae5676 100644 --- a/frappe/desk/doctype/desktop_icon/desktop_icon.py +++ b/frappe/desk/doctype/desktop_icon/desktop_icon.py @@ -145,7 +145,7 @@ def add_user_icon(_doctype, _report=None, label=None, link=None, type='link', st icon_name = new_icon.name - except Exception, e: + except Exception as e: raise e return icon_name @@ -194,7 +194,7 @@ def set_desktop_icons(visible_list, ignore_duplicate=True): if frappe.db.exists('DocType', module_name): try: add_user_icon(module_name, standard=1) - except frappe.UniqueValidationError, e: + except frappe.UniqueValidationError as e: if not ignore_duplicate: raise e else: diff --git a/frappe/desk/doctype/todo/todo.py b/frappe/desk/doctype/todo/todo.py index 6703dfa785..546755d6a6 100644 --- a/frappe/desk/doctype/todo/todo.py +++ b/frappe/desk/doctype/todo/todo.py @@ -65,7 +65,7 @@ class ToDo(Document): frappe.db.set_value(self.reference_type, self.reference_name, "_assign", json.dumps(assignments), update_modified=False) - except Exception, e: + except Exception as e: if e.args[0] == 1146 and frappe.flags.in_install: # no table return diff --git a/frappe/desk/form/save.py b/frappe/desk/form/save.py index 945960e62b..b2f2ea4482 100644 --- a/frappe/desk/form/save.py +++ b/frappe/desk/form/save.py @@ -20,7 +20,7 @@ def savedocs(doc, action): else: try: doc.save() - except frappe.NameError, e: + except frappe.NameError as e: doctype, name, original_exception = e if isinstance(e, tuple) else (doc.doctype or "", doc.name or "", None) frappe.msgprint(frappe._("{0} {1} already exists").format(doctype, name)) raise diff --git a/frappe/desk/like.py b/frappe/desk/like.py index 57c750fcfc..769fb63bcc 100644 --- a/frappe/desk/like.py +++ b/frappe/desk/like.py @@ -54,7 +54,7 @@ def _toggle_like(doctype, name, add, user=None): frappe.db.set_value(doctype, name, "_liked_by", json.dumps(liked_by), update_modified=False) - except Exception, e: + except Exception as e: if isinstance(e.args, (tuple, list)) and e.args and e.args[0]==1054: add_column(doctype, "_liked_by", "Text") _toggle_like(doctype, name, add, user) diff --git a/frappe/desk/moduleview.py b/frappe/desk/moduleview.py index 5fa6b01af4..7a15b14597 100644 --- a/frappe/desk/moduleview.py +++ b/frappe/desk/moduleview.py @@ -196,7 +196,7 @@ def get_last_modified(doctype): def _get(): try: last_modified = frappe.get_all(doctype, fields=["max(modified)"], as_list=True, limit_page_length=1)[0][0] - except Exception, e: + except Exception as e: if e.args[0]==1146: last_modified = None else: diff --git a/frappe/desk/notifications.py b/frappe/desk/notifications.py index 1113a26db4..3924afd7a4 100644 --- a/frappe/desk/notifications.py +++ b/frappe/desk/notifications.py @@ -100,7 +100,7 @@ def get_notifications_for_doctypes(config, notification_count): pass # frappe.msgprint("Permission Error in notifications for {0}".format(d)) - except Exception, e: + except Exception as e: # OperationalError: (1412, 'Table definition has changed, please retry transaction') if e.args[0]!=1412: raise diff --git a/frappe/desk/tags.py b/frappe/desk/tags.py index c488c5cf64..e6af49f90d 100644 --- a/frappe/desk/tags.py +++ b/frappe/desk/tags.py @@ -31,7 +31,7 @@ def check_user_tags(dt): "if the user does not have a tags column, then it creates one" try: frappe.db.sql("select `_user_tags` from `tab%s` limit 1" % dt) - except Exception, e: + except Exception as e: if e.args[0] == 1054: DocTags(dt).setup() @@ -57,7 +57,7 @@ def get_tags(doctype, txt, cat_tags): where _user_tags like '%{1}%' limit 50""".format(frappe.db.escape(doctype), frappe.db.escape(txt))): tags.extend(_user_tags[1:].split(",")) - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise return sorted(filter(lambda t: t and txt.lower() in t.lower(), list(set(tags)))) @@ -102,7 +102,7 @@ class DocTags: try: frappe.db.sql("update `tab%s` set _user_tags=%s where name=%s" % \ (self.dt,'%s','%s'), (tags , dn)) - except Exception, e: + except Exception as e: if e.args[0]==1054: if not tags: # no tags, nothing to do diff --git a/frappe/email/__init__.py b/frappe/email/__init__.py index c0388d7e68..8c1fab4822 100644 --- a/frappe/email/__init__.py +++ b/frappe/email/__init__.py @@ -26,7 +26,7 @@ def get_contact_list(txt): ) if not out: out = get_users() - except Exception, e: + except Exception as e: if e.args[0]==1146: # no Contact, use User out = get_users() diff --git a/frappe/email/doctype/email_account/email_account.py b/frappe/email/doctype/email_account/email_account.py index 9724695459..dd907468b3 100755 --- a/frappe/email/doctype/email_account/email_account.py +++ b/frappe/email/doctype/email_account/email_account.py @@ -161,7 +161,7 @@ class EmailAccount(Document): email_server = EmailServer(frappe._dict(args)) try: email_server.connect() - except (error_proto, imaplib.IMAP4.error), e: + except (error_proto, imaplib.IMAP4.error) as e: message = e.message.lower().replace(" ","") if in_receive and any(map(lambda t: t in message, ['authenticationfail', 'loginviayourwebbrowser', #abbreviated to work with both failure and failed 'loginfailed', 'err[auth]', 'errtemporaryerror'])): #temporary error to deal with godaddy @@ -291,7 +291,7 @@ class EmailAccount(Document): frappe.publish_realtime('new_email', {"account":self.email_account_name, "number":len(incoming_mails)}) if exceptions: - raise Exception, frappe.as_json(exceptions) + raise Exception(frappe.as_json(exceptions)) def handle_bad_emails(self, email_server, uid, raw, reason): if cint(email_server.settings.use_imap): diff --git a/frappe/email/doctype/email_domain/email_domain.py b/frappe/email/doctype/email_domain/email_domain.py index baca02ade9..cb8aeaf2ab 100644 --- a/frappe/email/doctype/email_domain/email_domain.py +++ b/frappe/email/doctype/email_domain/email_domain.py @@ -73,7 +73,7 @@ class EmailDomain(Document): email_account.set("smtp_server",self.smtp_server) email_account.set("smtp_port",self.smtp_port) email_account.save() - except Exception, e: + except Exception as e: frappe.msgprint(email_account.name) frappe.throw(e) return None diff --git a/frappe/email/queue.py b/frappe/email/queue.py index 6d33f0c6a5..06efb58e3e 100755 --- a/frappe/email/queue.py +++ b/frappe/email/queue.py @@ -406,7 +406,7 @@ def send_one(email, smtpserver=None, auto_commit=True, now=False, from_test=Fals # no need to attempt further return - except Exception, e: + except Exception as e: frappe.db.rollback() if any("Sent" == s.status for s in recipients_list): diff --git a/frappe/email/receive.py b/frappe/email/receive.py index 2bb09b54e0..ea1c191bf3 100644 --- a/frappe/email/receive.py +++ b/frappe/email/receive.py @@ -58,7 +58,7 @@ class EmailServer: frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) raise - except Exception, e: + except Exception as e: frappe.msgprint(_('Cannot connect: {0}').format(str(e))) raise @@ -84,7 +84,7 @@ class EmailServer: frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) raise - except poplib.error_proto, e: + except poplib.error_proto as e: if self.is_temporary_system_problem(e): return False @@ -143,7 +143,7 @@ class EmailServer: for m in xrange(101, num+1): self.pop.dele(m) - except Exception, e: + except Exception as e: if self.has_login_limit_exceeded(e): pass @@ -246,10 +246,10 @@ class EmailServer: self.errors = True raise - except Exception, e: + except Exception as e: if self.has_login_limit_exceeded(e): self.errors = True - raise LoginLimitExceeded, e + raise LoginLimitExceeded(e) else: # log performs rollback and logs error in Error Log diff --git a/frappe/email/smtp.py b/frappe/email/smtp.py index 4e58beeebc..1803dfb730 100644 --- a/frappe/email/smtp.py +++ b/frappe/email/smtp.py @@ -2,7 +2,7 @@ # MIT License. See license.txt from __future__ import unicode_literals - +from six import reraise as raise_ import frappe import smtplib import email.utils @@ -183,22 +183,20 @@ class SMTPServer: # check if logged correctly if ret[0]!=235: frappe.msgprint(ret[1]) - raise frappe.OutgoingEmailError, ret[1] + raise frappe.OutgoingEmailError(ret[1]) return self._sess - except _socket.error, e: + except _socket.error as e: # Invalid mail server -- due to refusing connection frappe.msgprint(_('Invalid Outgoing Mail Server or Port')) + traceback = sys.exc_info()[2] + raise_(frappe.ValidationError, e, traceback) - type, value, traceback = sys.exc_info() - raise frappe.ValidationError, e, traceback - - except smtplib.SMTPAuthenticationError, e: + except smtplib.SMTPAuthenticationError as e: frappe.msgprint(_("Invalid login or password")) - - type, value, traceback = sys.exc_info() - raise frappe.ValidationError, e, traceback + traceback = sys.exc_info()[2] + raise_(frappe.ValidationError, e, traceback) except smtplib.SMTPException: frappe.msgprint(_('Unable to send emails at this time')) diff --git a/frappe/integrations/doctype/dropbox_settings/dropbox_settings.py b/frappe/integrations/doctype/dropbox_settings/dropbox_settings.py index 38d094544a..fea422c1c1 100644 --- a/frappe/integrations/doctype/dropbox_settings/dropbox_settings.py +++ b/frappe/integrations/doctype/dropbox_settings/dropbox_settings.py @@ -26,7 +26,7 @@ class DropboxSettings(Document): def validate_dropbox_credentails(self): try: self.get_dropbox_session() - except Exception, e: + except Exception as e: frappe.throw(e.message) def get_dropbox_session(self): @@ -213,7 +213,7 @@ def upload_file_to_dropbox(filename, folder, dropbox_client): uploader.upload_chunked() uploader.finish(folder + "/" + os.path.basename(filename), overwrite=True) - except rest.ErrorResponse, e: + except rest.ErrorResponse as e: # if "[401] u'Access token not found.'", # it means that the user needs to again allow dropbox backup from the UI # so re-raise @@ -242,9 +242,9 @@ def upload_from_folder(path, dropbox_folder, dropbox_client, did_not_upload, err try: response = dropbox_client.metadata(dropbox_folder) - except dropbox.rest.ErrorResponse, e: + except dropbox.rest.ErrorResponse as e: # folder not found - if e.status==404: + if e.status == 404: response = {"contents": []} else: raise diff --git a/frappe/integrations/utils.py b/frappe/integrations/utils.py index 0870222202..4d6d6c0ec4 100644 --- a/frappe/integrations/utils.py +++ b/frappe/integrations/utils.py @@ -22,7 +22,7 @@ def make_get_request(url, auth=None, headers=None, data=None): frappe.flags.integration_request.raise_for_status() return frappe.flags.integration_request.json() - except Exception, exc: + except Exception as exc: frappe.log_error(frappe.get_traceback()) raise exc @@ -43,7 +43,7 @@ def make_post_request(url, auth=None, headers=None, data=None): return urlparse.parse_qs(frappe.flags.integration_request.text) return frappe.flags.integration_request.json() - except Exception, exc: + except Exception as exc: frappe.log_error() raise exc diff --git a/frappe/model/base_document.py b/frappe/model/base_document.py index 30c9ab2a0b..ce834dc730 100644 --- a/frappe/model/base_document.py +++ b/frappe/model/base_document.py @@ -2,6 +2,7 @@ # MIT License. See license.txt from __future__ import unicode_literals +from six import reraise as raise_ import frappe, sys from frappe import _ from frappe.utils import (cint, flt, now, cstr, strip_html, getdate, get_datetime, to_timedelta, @@ -38,9 +39,9 @@ def get_controller(doctype): if issubclass(_class, BaseDocument): _class = getattr(module, classname) else: - raise ImportError, doctype + raise ImportError(doctype) else: - raise ImportError, doctype + raise ImportError(doctype) _classes[doctype] = _class return _classes[doctype] @@ -140,7 +141,9 @@ class BaseDocument(object): value.parent_doc = self return value else: - raise ValueError, "Document attached to child table must be a dict or BaseDocument, not " + str(type(value))[1:-1] + raise ValueError( + "Document attached to child table must be a dict or BaseDocument, not " + str(type(value))[1:-1] + ) def extend(self, key, value): if isinstance(value, list): @@ -159,7 +162,7 @@ class BaseDocument(object): if "doctype" not in value: value["doctype"] = self.get_table_field_doctype(key) if not value["doctype"]: - raise AttributeError, key + raise AttributeError(key) value = get_controller(value["doctype"])(value) value.init_valid_columns() @@ -294,7 +297,7 @@ class BaseDocument(object): columns = ", ".join(["`"+c+"`" for c in columns]), values = ", ".join(["%s"] * len(columns)) ), d.values()) - except Exception, e: + except Exception as e: if e.args[0]==1062: if "PRIMARY" in cstr(e.args[1]): if self.meta.autoname=="hash": @@ -303,9 +306,9 @@ class BaseDocument(object): self.db_insert() return - type, value, traceback = sys.exc_info() frappe.msgprint(_("Duplicate name {0} {1}").format(self.doctype, self.name)) - raise frappe.DuplicateEntryError, (self.doctype, self.name, e), traceback + traceback = sys.exc_info()[2] + raise_(frappe.DuplicateEntryError, (self.doctype, self.name, e), traceback) elif "Duplicate" in cstr(e.args[1]): # unique constraint @@ -336,7 +339,7 @@ class BaseDocument(object): doctype = self.doctype, values = ", ".join(["`"+c+"`=%s" for c in columns]) ), d.values() + [name]) - except Exception, e: + except Exception as e: if e.args[0]==1062 and "Duplicate" in cstr(e.args[1]): self.show_unique_validation_message(e) else: @@ -358,7 +361,7 @@ class BaseDocument(object): frappe.msgprint(_("{0} must be unique".format(label or fieldname))) # this is used to preserve traceback - raise frappe.UniqueValidationError, (self.doctype, self.name, e), traceback + raise_(frappe.UniqueValidationError, (self.doctype, self.name, e), traceback) def db_set(self, fieldname, value=None, update_modified=True): '''Set a value in the document object, update the timestamp and update the database. diff --git a/frappe/model/db_schema.py b/frappe/model/db_schema.py index 400b873b96..b5d76aead6 100644 --- a/frappe/model/db_schema.py +++ b/frappe/model/db_schema.py @@ -60,7 +60,7 @@ def updatedb(dt, meta=None): """ res = frappe.db.sql("select issingle from tabDocType where name=%s", (dt,)) if not res: - raise Exception, 'Wrong doctype "%s" in updatedb' % dt + raise Exception('Wrong doctype "%s" in updatedb' % dt) if not res[0][0]: tab = DbTable(dt, 'tab', meta) @@ -118,7 +118,7 @@ class DbTable: max_length = frappe.db.sql("""select max(char_length(`{fieldname}`)) from `tab{doctype}`"""\ .format(fieldname=col.fieldname, doctype=self.doctype)) - except MySQLdb.OperationalError, e: + except MySQLdb.OperationalError as e: if e.args[0]==1054: # Unknown column 'column_name' in 'field list' continue @@ -337,7 +337,7 @@ class DbTable: if query: try: frappe.db.sql("alter table `{}` {}".format(self.name, ", ".join(query))) - except Exception, e: + except Exception as e: # sanitize if e.args[0]==1060: frappe.throw(str(e)) @@ -504,7 +504,7 @@ class DbManager: host = self.get_current_host() try: self.db.sql("DROP USER '%s'@'%s';" % (target, host)) - except Exception, e: + except Exception as e: if e.args[0]==1396: pass else: @@ -570,7 +570,7 @@ def remove_all_foreign_keys(): dbtab = DbTable(t[0]) try: fklist = dbtab.get_foreign_keys() - except Exception, e: + except Exception as e: if e.args[0]==1146: fklist = [] else: diff --git a/frappe/model/document.py b/frappe/model/document.py index e68d6e2f2b..f55e4891ea 100644 --- a/frappe/model/document.py +++ b/frappe/model/document.py @@ -50,7 +50,7 @@ def get_doc(arg1, arg2=None): if controller: return controller(arg1, arg2) - raise ImportError, arg1 + raise ImportError(arg1) class Document(BaseDocument): """All controllers inherit from `Document`.""" @@ -203,9 +203,9 @@ class Document(BaseDocument): else: try: self.db_insert() - except frappe.DuplicateEntryError, e: + except frappe.DuplicateEntryError as e: if not ignore_if_duplicate: - raise e + raise e # children for d in self.get_all_children(): @@ -562,7 +562,7 @@ class Document(BaseDocument): self._action = "submit" self.check_permission("submit") else: - raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 0 to 2") + raise frappe.DocstatusTransitionError(_("Cannot change docstatus from 0 to 2")) elif docstatus==1: if self.docstatus==1: @@ -572,10 +572,10 @@ class Document(BaseDocument): self._action = "cancel" self.check_permission("cancel") else: - raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 1 to 0") + raise frappe.DocstatusTransitionError(_("Cannot change docstatus from 1 to 0")) elif docstatus==2: - raise frappe.ValidationError, _("Cannot edit cancelled document") + raise frappe.ValidationError(_("Cannot edit cancelled document")) def set_parent_in_children(self): """Updates `parent` and `parenttype` property in all children.""" diff --git a/frappe/model/meta.py b/frappe/model/meta.py index ae84ccd2c9..9e5420e905 100644 --- a/frappe/model/meta.py +++ b/frappe/model/meta.py @@ -230,7 +230,7 @@ class Meta(Document): self.extend("fields", frappe.db.sql("""SELECT * FROM `tabCustom Field` WHERE dt = %s AND docstatus < 2""", (self.name,), as_dict=1, update={"is_custom_field": 1})) - except Exception, e: + except Exception as e: if e.args[0]==1146: return else: @@ -385,7 +385,7 @@ def is_single(doctype): try: return frappe.db.get_value("DocType", doctype, "issingle") except IndexError: - raise Exception, 'Cannot determine whether %s is single' % doctype + raise Exception('Cannot determine whether %s is single' % doctype) def get_parent_dt(dt): parent_dt = frappe.db.sql("""select parent from tabDocField diff --git a/frappe/model/rename_doc.py b/frappe/model/rename_doc.py index 1bb9e5bcfd..e9082703cd 100644 --- a/frappe/model/rename_doc.py +++ b/frappe/model/rename_doc.py @@ -85,7 +85,7 @@ def update_attachments(doctype, old, new): if old != "File Data" and doctype != "DocType": frappe.db.sql("""update `tabFile` set attached_to_name=%s where attached_to_name=%s and attached_to_doctype=%s""", (new, old, doctype)) - except Exception, e: + except Exception as e: if e.args[0]!=1054: # in patch? raise @@ -373,7 +373,7 @@ def bulk_rename(doctype, rows=None, via_console = False): frappe.db.commit() else: msg = _("Ignored: {0} to {1}").format(row[0], row[1]) - except Exception, e: + except Exception as e: msg = _("** Failed: {0} to {1}: {2}").format(row[0], row[1], repr(e)) frappe.db.rollback() diff --git a/frappe/oauth.py b/frappe/oauth.py index 3e77a36965..bf7a35af3c 100644 --- a/frappe/oauth.py +++ b/frappe/oauth.py @@ -155,7 +155,7 @@ class OAuthWebRequestValidator(RequestValidator): oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ")[1], 'client')) try: request.client = request.client or oc.as_dict() - except Exception, e: + except Exception as e: print("Failed body authentication: Application %s does not exist".format(cid=request.client_id)) return frappe.session.user == urllib.unquote(cookie_dict.get('user_id', "Guest")) diff --git a/frappe/patches/v4_0/rename_sitemap_to_route.py b/frappe/patches/v4_0/rename_sitemap_to_route.py index 4deca2f052..2c8ed3c2d1 100644 --- a/frappe/patches/v4_0/rename_sitemap_to_route.py +++ b/frappe/patches/v4_0/rename_sitemap_to_route.py @@ -20,6 +20,6 @@ def execute(): def rename_field_if_exists(doctype, old_fieldname, new_fieldname): try: rename_field(doctype, old_fieldname, new_fieldname) - except Exception, e: + except Exception as e: if e.args[0] != 1054: raise diff --git a/frappe/patches/v4_2/set_assign_in_doc.py b/frappe/patches/v4_2/set_assign_in_doc.py index ff20d71432..a7de3c6dec 100644 --- a/frappe/patches/v4_2/set_assign_in_doc.py +++ b/frappe/patches/v4_2/set_assign_in_doc.py @@ -6,6 +6,6 @@ def execute(): where ifnull(reference_type, '')!='' and ifnull(reference_name, '')!=''"""): try: frappe.get_doc("ToDo", name).on_update() - except Exception, e: + except Exception as e: if e.args[0]!=1146: raise diff --git a/frappe/patches/v5_0/fix_text_editor_file_urls.py b/frappe/patches/v5_0/fix_text_editor_file_urls.py index bbcd1aa545..a4b92803da 100644 --- a/frappe/patches/v5_0/fix_text_editor_file_urls.py +++ b/frappe/patches/v5_0/fix_text_editor_file_urls.py @@ -14,7 +14,7 @@ def execute(): try: result = frappe.get_all(opts.parent, fields=["name", opts.fieldname]) - except frappe.SQLError, e: + except frappe.SQLError as e: # bypass single tables continue diff --git a/frappe/patches/v5_0/rename_ref_type_fieldnames.py b/frappe/patches/v5_0/rename_ref_type_fieldnames.py index d0c4d71fca..6276b9b395 100644 --- a/frappe/patches/v5_0/rename_ref_type_fieldnames.py +++ b/frappe/patches/v5_0/rename_ref_type_fieldnames.py @@ -7,13 +7,13 @@ import frappe def execute(): try: frappe.db.sql("alter table `tabEmail Queue` change `ref_docname` `reference_name` varchar(255)") - except Exception, e: + except Exception as e: if e.args[0] not in (1054, 1060): raise try: frappe.db.sql("alter table `tabEmail Queue` change `ref_doctype` `reference_doctype` varchar(255)") - except Exception, e: + except Exception as e: if e.args[0] not in (1054, 1060): raise frappe.reload_doctype("Email Queue") diff --git a/frappe/patches/v6_19/comment_feed_communication.py b/frappe/patches/v6_19/comment_feed_communication.py index aa8d5d4e08..7a44f2e2ae 100644 --- a/frappe/patches/v6_19/comment_feed_communication.py +++ b/frappe/patches/v6_19/comment_feed_communication.py @@ -260,7 +260,7 @@ def update_for_dynamically_linked_docs(timeline_doctype): try: docs = frappe.get_all(reference_doctype, fields=["name", df.fieldname], filters={ df.options: timeline_doctype }) - except frappe.SQLError, e: + except frappe.SQLError as e: if e.args and e.args[0]==1146: # single continue diff --git a/frappe/patches/v7_0/re_route.py b/frappe/patches/v7_0/re_route.py index 9720b6618a..909838a692 100644 --- a/frappe/patches/v7_0/re_route.py +++ b/frappe/patches/v7_0/re_route.py @@ -18,5 +18,5 @@ def update_routes(doctypes): frappe.db.sql("""update ignore `tab{0}` set route = concat(ifnull(parent_website_route, ""), if(ifnull(parent_website_route, "")="", "", "/"), page_name) {1}""".format(d, condition)) - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise diff --git a/frappe/patches/v7_2/set_in_standard_filter_property.py b/frappe/patches/v7_2/set_in_standard_filter_property.py index 421861cd69..554a505b4c 100644 --- a/frappe/patches/v7_2/set_in_standard_filter_property.py +++ b/frappe/patches/v7_2/set_in_standard_filter_property.py @@ -5,7 +5,7 @@ def execute(): try: frappe.db.sql('update `tabCustom Field` set in_standard_filter = in_filter_dash') - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise e for doctype in frappe.get_all("DocType", {"istable": 0, "issingle": 0, "custom": 0}): diff --git a/frappe/test_runner.py b/frappe/test_runner.py index 7337cd1756..0d22008116 100644 --- a/frappe/test_runner.py +++ b/frappe/test_runner.py @@ -303,7 +303,7 @@ def make_test_objects(doctype, test_records=None, verbose=None, reset=False): except frappe.NameError: pass - except Exception, e: + except Exception as e: if d.flags.ignore_these_exceptions_in_test and e.__class__ in d.flags.ignore_these_exceptions_in_test: pass diff --git a/frappe/utils/__init__.py b/frappe/utils/__init__.py index 0464705a19..6522773093 100644 --- a/frappe/utils/__init__.py +++ b/frappe/utils/__init__.py @@ -227,7 +227,7 @@ def get_file_timestamp(fn): try: return str(cint(os.stat(fn).st_mtime)) - except OSError, e: + except OSError as e: if e.args[0]!=2: raise else: diff --git a/frappe/utils/background_jobs.py b/frappe/utils/background_jobs.py index f6f35f3c82..f7c29ab75d 100755 --- a/frappe/utils/background_jobs.py +++ b/frappe/utils/background_jobs.py @@ -64,7 +64,7 @@ def execute_job(site, method, event, job_name, kwargs, user=None, async=True, re try: method(**kwargs) - except (MySQLdb.OperationalError, frappe.RetryBackgroundJobError), e: + except (MySQLdb.OperationalError, frappe.RetryBackgroundJobError) as e: frappe.db.rollback() if (retry < 5 and diff --git a/frappe/utils/dateutils.py b/frappe/utils/dateutils.py index 31f2a92631..a9b5818efa 100644 --- a/frappe/utils/dateutils.py +++ b/frappe/utils/dateutils.py @@ -29,8 +29,8 @@ def user_to_str(date, date_format=None): try: return datetime.datetime.strptime(date, dateformats[date_format]).strftime('%Y-%m-%d') - except ValueError, e: - raise ValueError, "Date %s must be in format %s" % (date, date_format) + except ValueError as e: + raise ValueError("Date %s must be in format %s" % (date, date_format)) def parse_date(date): """tries to parse given date to system's format i.e. yyyy-mm-dd. returns a string""" @@ -49,13 +49,13 @@ def parse_date(date): parsed_date = user_to_str(date, f) if parsed_date: break - except ValueError, e: + except ValueError as e: pass if not parsed_date: - raise Exception, """Cannot understand date - '%s'. - Try formatting it like your default format - '%s'""" % \ - (date, get_user_date_format()) + raise Exception("""Cannot understand date - '%s'. + Try formatting it like your default format - '%s'""" % (date, get_user_date_format()) + ) return parsed_date diff --git a/frappe/utils/error.py b/frappe/utils/error.py index 3b13f2e7fc..b117c4ad21 100644 --- a/frappe/utils/error.py +++ b/frappe/utils/error.py @@ -40,7 +40,7 @@ def make_error_snapshot(exception): logger.error('New Exception collected with id: {}'.format(error_id)) - except Exception, e: + except Exception as e: logger.error('Could not take error snapshot: {0}'.format(e), exc_info=True) def get_snapshot(exception, context=10): diff --git a/frappe/utils/file_manager.py b/frappe/utils/file_manager.py index e0f3a02e19..4e011c5291 100644 --- a/frappe/utils/file_manager.py +++ b/frappe/utils/file_manager.py @@ -236,7 +236,7 @@ def remove_all(dt, dn, from_delete=False): for fid in frappe.db.sql_list("""select name from `tabFile` where attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)): remove_file(fid, dt, dn, from_delete) - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise # (temp till for patched) def remove_file_by_url(file_url, doctype=None, name=None): diff --git a/frappe/utils/help.py b/frappe/utils/help.py index ebc6718e8e..0cbe294ce5 100644 --- a/frappe/utils/help.py +++ b/frappe/utils/help.py @@ -51,7 +51,7 @@ class HelpDatabase(object): if not self.help_db_name in dbman.get_database_list(): try: dbman.create_user(self.help_db_name, self.help_db_name) - except Exception, e: + except Exception as e: # user already exists if e.args[0] != 1396: raise dbman.create_database(self.help_db_name) diff --git a/frappe/utils/jinja.py b/frappe/utils/jinja.py index 09343e2b03..3336bb8250 100644 --- a/frappe/utils/jinja.py +++ b/frappe/utils/jinja.py @@ -30,7 +30,7 @@ def validate_template(html): jenv = get_jenv() try: jenv.from_string(html) - except TemplateSyntaxError, e: + except TemplateSyntaxError as e: frappe.msgprint('Line {}: {}'.format(e.lineno, e.message)) frappe.throw(frappe._("Syntax error in template")) diff --git a/frappe/utils/password.py b/frappe/utils/password.py index d151114f7e..5f813d9e7b 100644 --- a/frappe/utils/password.py +++ b/frappe/utils/password.py @@ -60,7 +60,7 @@ def delete_all_passwords_for(doctype, name): try: frappe.db.sql("""delete from __Auth where doctype=%(doctype)s and name=%(name)s""", { 'doctype': doctype, 'name': name }) - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise diff --git a/frappe/utils/pdf.py b/frappe/utils/pdf.py index c56ea8e483..4924fbaa9d 100644 --- a/frappe/utils/pdf.py +++ b/frappe/utils/pdf.py @@ -21,7 +21,7 @@ def get_pdf(html, options=None, output = None): with open(fname, "rb") as fileobj: filedata = fileobj.read() - except IOError, e: + except IOError as e: if ("ContentNotFoundError" in e.message or "ContentOperationNotPermittedError" in e.message or "UnknownContentError" in e.message diff --git a/frappe/utils/scheduler.py b/frappe/utils/scheduler.py index fdf9ee3a96..afd56a9933 100755 --- a/frappe/utils/scheduler.py +++ b/frappe/utils/scheduler.py @@ -270,7 +270,7 @@ def reset_enabled_scheduler_events(login_manager): if login_manager.info.user_type == "System User": try: frappe.db.set_global('enabled_scheduler_events', None) - except MySQLdb.OperationalError, e: + except MySQLdb.OperationalError as e: if e.args[0]==1205: frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events") else: diff --git a/frappe/utils/user.py b/frappe/utils/user.py index 1da90ea383..ef2869db76 100755 --- a/frappe/utils/user.py +++ b/frappe/utils/user.py @@ -43,7 +43,7 @@ class UserPermissions: user = frappe.get_doc("User", self.name).as_dict() except frappe.DoesNotExistError: pass - except Exception, e: + except Exception as e: # install boo-boo if e.args[0] != 1146: raise diff --git a/frappe/website/render.py b/frappe/website/render.py index dda400c965..ade7ee184c 100644 --- a/frappe/website/render.py +++ b/frappe/website/render.py @@ -30,7 +30,7 @@ def render(path=None, http_status_code=None): else: try: data = render_page_by_language(path) - except frappe.DoesNotExistError, e: + except frappe.DoesNotExistError as e: doctype, name = get_doctype_from_path(path) if doctype and name: path = "print" @@ -48,13 +48,13 @@ def render(path=None, http_status_code=None): if not data: try: data = render_page(path) - except frappe.PermissionError, e: + except frappe.PermissionError as e: data, http_status_code = render_403(e, path) - except frappe.PermissionError, e: + except frappe.PermissionError as e: data, http_status_code = render_403(e, path) - except frappe.Redirect, e: + except frappe.Redirect as e: return build_response(path, "", 301, { "Location": frappe.flags.redirect_location or (frappe.local.response or {}).get('location'), "Cache-Control": "no-store, no-cache, must-revalidate" diff --git a/frappe/website/router.py b/frappe/website/router.py index 460cd6c6ec..8c8d8bdecb 100644 --- a/frappe/website/router.py +++ b/frappe/website/router.py @@ -112,7 +112,7 @@ def get_page_info_from_doctypes(path=None): # just want one path, return it! if path: return routes[r.route] - except Exception, e: + except Exception as e: if e.args[0]!=1054: raise e return routes