Browse Source

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
version-14
tundebabzy 8 years ago
committed by Rushabh Mehta
parent
commit
6fbe20caaa
52 changed files with 112 additions and 111 deletions
  1. +5
    -5
      frappe/app.py
  2. +1
    -1
      frappe/build.py
  3. +2
    -2
      frappe/core/doctype/communication/comment.py
  4. +1
    -1
      frappe/core/doctype/communication/email.py
  5. +3
    -3
      frappe/core/doctype/doctype/doctype.py
  6. +2
    -2
      frappe/core/doctype/file/file.py
  7. +1
    -1
      frappe/core/page/data_import_tool/importer.py
  8. +1
    -1
      frappe/custom/doctype/customize_form/customize_form.py
  9. +3
    -3
      frappe/database.py
  10. +1
    -1
      frappe/desk/doctype/bulk_update/bulk_update.py
  11. +2
    -2
      frappe/desk/doctype/desktop_icon/desktop_icon.py
  12. +1
    -1
      frappe/desk/doctype/todo/todo.py
  13. +1
    -1
      frappe/desk/form/save.py
  14. +1
    -1
      frappe/desk/like.py
  15. +1
    -1
      frappe/desk/moduleview.py
  16. +1
    -1
      frappe/desk/notifications.py
  17. +3
    -3
      frappe/desk/tags.py
  18. +1
    -1
      frappe/email/__init__.py
  19. +2
    -2
      frappe/email/doctype/email_account/email_account.py
  20. +1
    -1
      frappe/email/doctype/email_domain/email_domain.py
  21. +1
    -1
      frappe/email/queue.py
  22. +5
    -5
      frappe/email/receive.py
  23. +8
    -10
      frappe/email/smtp.py
  24. +4
    -4
      frappe/integrations/doctype/dropbox_settings/dropbox_settings.py
  25. +2
    -2
      frappe/integrations/utils.py
  26. +12
    -9
      frappe/model/base_document.py
  27. +5
    -5
      frappe/model/db_schema.py
  28. +6
    -6
      frappe/model/document.py
  29. +2
    -2
      frappe/model/meta.py
  30. +2
    -2
      frappe/model/rename_doc.py
  31. +1
    -1
      frappe/oauth.py
  32. +1
    -1
      frappe/patches/v4_0/rename_sitemap_to_route.py
  33. +1
    -1
      frappe/patches/v4_2/set_assign_in_doc.py
  34. +1
    -1
      frappe/patches/v5_0/fix_text_editor_file_urls.py
  35. +2
    -2
      frappe/patches/v5_0/rename_ref_type_fieldnames.py
  36. +1
    -1
      frappe/patches/v6_19/comment_feed_communication.py
  37. +1
    -1
      frappe/patches/v7_0/re_route.py
  38. +1
    -1
      frappe/patches/v7_2/set_in_standard_filter_property.py
  39. +1
    -1
      frappe/test_runner.py
  40. +1
    -1
      frappe/utils/__init__.py
  41. +1
    -1
      frappe/utils/background_jobs.py
  42. +6
    -6
      frappe/utils/dateutils.py
  43. +1
    -1
      frappe/utils/error.py
  44. +1
    -1
      frappe/utils/file_manager.py
  45. +1
    -1
      frappe/utils/help.py
  46. +1
    -1
      frappe/utils/jinja.py
  47. +1
    -1
      frappe/utils/password.py
  48. +1
    -1
      frappe/utils/pdf.py
  49. +1
    -1
      frappe/utils/scheduler.py
  50. +1
    -1
      frappe/utils/user.py
  51. +4
    -4
      frappe/website/render.py
  52. +1
    -1
      frappe/website/router.py

+ 5
- 5
frappe/app.py View File

@@ -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:


+ 1
- 1
frappe/build.py View File

@@ -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


+ 2
- 2
frappe/core/doctype/communication/comment.py View File

@@ -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", [])


+ 1
- 1
frappe/core/doctype/communication/email.py View File

@@ -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()


+ 3
- 3
frappe/core/doctype/doctype/doctype.py View File

@@ -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:


+ 2
- 2
frappe/core/doctype/file/file.py View File

@@ -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:


+ 1
- 1
frappe/core/page/data_import_tool/importer.py View File

@@ -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())


+ 1
- 1
frappe/custom/doctype/customize_form/customize_form.py View File

@@ -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:


+ 3
- 3
frappe/database.py View File

@@ -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


+ 1
- 1
frappe/desk/doctype/bulk_update/bulk_update.py View File

@@ -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



+ 2
- 2
frappe/desk/doctype/desktop_icon/desktop_icon.py View File

@@ -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:


+ 1
- 1
frappe/desk/doctype/todo/todo.py View File

@@ -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


+ 1
- 1
frappe/desk/form/save.py View File

@@ -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


+ 1
- 1
frappe/desk/like.py View File

@@ -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)


+ 1
- 1
frappe/desk/moduleview.py View File

@@ -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:


+ 1
- 1
frappe/desk/notifications.py View File

@@ -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


+ 3
- 3
frappe/desk/tags.py View File

@@ -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


+ 1
- 1
frappe/email/__init__.py View File

@@ -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()


+ 2
- 2
frappe/email/doctype/email_account/email_account.py View File

@@ -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):


+ 1
- 1
frappe/email/doctype/email_domain/email_domain.py View File

@@ -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


+ 1
- 1
frappe/email/queue.py View File

@@ -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):


+ 5
- 5
frappe/email/receive.py View File

@@ -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


+ 8
- 10
frappe/email/smtp.py View File

@@ -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'))


+ 4
- 4
frappe/integrations/doctype/dropbox_settings/dropbox_settings.py View File

@@ -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


+ 2
- 2
frappe/integrations/utils.py View File

@@ -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



+ 12
- 9
frappe/model/base_document.py View File

@@ -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.


+ 5
- 5
frappe/model/db_schema.py View File

@@ -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:


+ 6
- 6
frappe/model/document.py View File

@@ -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."""


+ 2
- 2
frappe/model/meta.py View File

@@ -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


+ 2
- 2
frappe/model/rename_doc.py View File

@@ -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()



+ 1
- 1
frappe/oauth.py View File

@@ -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"))


+ 1
- 1
frappe/patches/v4_0/rename_sitemap_to_route.py View File

@@ -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

+ 1
- 1
frappe/patches/v4_2/set_assign_in_doc.py View File

@@ -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

+ 1
- 1
frappe/patches/v5_0/fix_text_editor_file_urls.py View File

@@ -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



+ 2
- 2
frappe/patches/v5_0/rename_ref_type_fieldnames.py View File

@@ -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")

+ 1
- 1
frappe/patches/v6_19/comment_feed_communication.py View File

@@ -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


+ 1
- 1
frappe/patches/v7_0/re_route.py View File

@@ -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

+ 1
- 1
frappe/patches/v7_2/set_in_standard_filter_property.py View File

@@ -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}):


+ 1
- 1
frappe/test_runner.py View File

@@ -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



+ 1
- 1
frappe/utils/__init__.py View File

@@ -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:


+ 1
- 1
frappe/utils/background_jobs.py View File

@@ -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


+ 6
- 6
frappe/utils/dateutils.py View File

@@ -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



+ 1
- 1
frappe/utils/error.py View File

@@ -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):


+ 1
- 1
frappe/utils/file_manager.py View File

@@ -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):


+ 1
- 1
frappe/utils/help.py View File

@@ -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)


+ 1
- 1
frappe/utils/jinja.py View File

@@ -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"))



+ 1
- 1
frappe/utils/password.py View File

@@ -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



+ 1
- 1
frappe/utils/pdf.py View File

@@ -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


+ 1
- 1
frappe/utils/scheduler.py View File

@@ -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:


+ 1
- 1
frappe/utils/user.py View File

@@ -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



+ 4
- 4
frappe/website/render.py View File

@@ -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"


+ 1
- 1
frappe/website/router.py View File

@@ -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


Loading…
Cancel
Save