* 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 indentationversion-14
@@ -55,8 +55,8 @@ def application(request): | |||||
response = frappe.handler.handle() | response = frappe.handler.handle() | ||||
elif frappe.request.path.startswith("/api/"): | 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() | response = frappe.api.handle() | ||||
elif frappe.request.path.startswith('/backups'): | elif frappe.request.path.startswith('/backups'): | ||||
@@ -71,13 +71,13 @@ def application(request): | |||||
else: | else: | ||||
raise NotFound | raise NotFound | ||||
except HTTPException, e: | |||||
except HTTPException as e: | |||||
return e | return e | ||||
except frappe.SessionStopped, e: | |||||
except frappe.SessionStopped as e: | |||||
response = frappe.utils.response.handle_session_stopped() | response = frappe.utils.response.handle_session_stopped() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
response = handle_exception(e) | response = handle_exception(e) | ||||
else: | else: | ||||
@@ -113,7 +113,7 @@ def get_build_maps(): | |||||
source_paths.append(s) | source_paths.append(s) | ||||
build_maps[target] = source_paths | build_maps[target] = source_paths | ||||
except ValueError, e: | |||||
except ValueError as e: | |||||
print(path) | print(path) | ||||
print('JSON syntax error {0}'.format(str(e))) | print('JSON syntax error {0}'.format(str(e))) | ||||
return build_maps | return build_maps | ||||
@@ -103,7 +103,7 @@ def get_comments_from_parent(doc): | |||||
try: | try: | ||||
_comments = frappe.db.get_value(doc.reference_doctype, doc.reference_name, "_comments") or "[]" | _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): | if e.args[0] in (1146, 1054): | ||||
# 1146 = no table | # 1146 = no table | ||||
# 1054 = missing column | # 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, | frappe.db.sql("""update `tab%s` set `_comments`=%s where name=%s""" % (reference_doctype, | ||||
"%s", "%s"), (json.dumps(_comments), reference_name)) | "%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): | if e.args[0] == 1054 and getattr(frappe.local, 'request', None): | ||||
# missing column and in request, add column and update after commit | # missing column and in request, add column and update after commit | ||||
frappe.local._comments = (getattr(frappe.local, "_comments", []) | frappe.local._comments = (getattr(frappe.local, "_comments", []) | ||||
@@ -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, | communication._notify(print_html=print_html, print_format=print_format, attachments=attachments, | ||||
recipients=recipients, cc=cc) | recipients=recipients, cc=cc) | ||||
except MySQLdb.OperationalError, e: | |||||
except MySQLdb.OperationalError as e: | |||||
# deadlock, try again | # deadlock, try again | ||||
if e.args[0]==1213: | if e.args[0]==1213: | ||||
frappe.db.rollback() | frappe.db.rollback() | ||||
@@ -458,7 +458,7 @@ def validate_fields(meta): | |||||
group by `{fieldname}` having count(*) > 1 limit 1""".format( | group by `{fieldname}` having count(*) > 1 limit 1""".format( | ||||
doctype=d.parent, fieldname=d.fieldname)) | doctype=d.parent, fieldname=d.fieldname)) | ||||
except MySQLdb.OperationalError, e: | |||||
except MySQLdb.OperationalError as e: | |||||
if e.args and e.args[0]==1054: | if e.args and e.args[0]==1054: | ||||
# ignore if missing column, else raise | # ignore if missing column, else raise | ||||
# this happens in case of Custom Field | # 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 = frappe.get_doc(dict(doctype= "Role", role_name=role, desk_access=1)) | ||||
r.flags.ignore_mandatory = r.flags.ignore_permissions = True | r.flags.ignore_mandatory = r.flags.ignore_permissions = True | ||||
r.insert() | r.insert() | ||||
except frappe.DoesNotExistError, e: | |||||
except frappe.DoesNotExistError as e: | |||||
pass | pass | ||||
except frappe.SQLError, e: | |||||
except frappe.SQLError as e: | |||||
if e.args[0]==1146: | if e.args[0]==1146: | ||||
pass | pass | ||||
else: | else: | ||||
@@ -363,12 +363,12 @@ def get_local_image(file_url): | |||||
return image, filename, extn | return image, filename, extn | ||||
def get_web_image(file_url): | def get_web_image(file_url): | ||||
# downlaod | |||||
# download | |||||
file_url = frappe.utils.get_url(file_url) | file_url = frappe.utils.get_url(file_url) | ||||
r = requests.get(file_url, stream=True) | r = requests.get(file_url, stream=True) | ||||
try: | try: | ||||
r.raise_for_status() | r.raise_for_status() | ||||
except requests.exceptions.HTTPError, e: | |||||
except requests.exceptions.HTTPError as e: | |||||
if "404" in e.args[0]: | if "404" in e.args[0]: | ||||
frappe.msgprint(_("File '{0}' not found").format(file_url)) | frappe.msgprint(_("File '{0}' not found").format(file_url)) | ||||
else: | else: | ||||
@@ -313,7 +313,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False, | |||||
if submit_after_import: | if submit_after_import: | ||||
doc.submit() | doc.submit() | ||||
log('Submitted row (#%d) %s' % (row_idx + 1, as_link(doc.doctype, doc.name))) | log('Submitted row (#%d) %s' % (row_idx + 1, as_link(doc.doctype, doc.name))) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
error = True | error = True | ||||
if doc: | if doc: | ||||
frappe.errprint(doc if isinstance(doc, dict) else doc.as_dict()) | frappe.errprint(doc if isinstance(doc, dict) else doc.as_dict()) | ||||
@@ -301,7 +301,7 @@ class CustomizeForm(Document): | |||||
else: | else: | ||||
try: | try: | ||||
property_value = frappe.db.get_value("DocType", self.doc_type, property_name) | property_value = frappe.db.get_value("DocType", self.doc_type, property_name) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1054: | if e.args[0]==1054: | ||||
property_value = None | property_value = None | ||||
else: | else: | ||||
@@ -148,7 +148,7 @@ class Database: | |||||
self._cursor.execute(query) | self._cursor.execute(query) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
# ignore data definition errors | # ignore data definition errors | ||||
if ignore_ddl and e.args[0] in (1146,1054,1091): | if ignore_ddl and e.args[0] in (1146,1054,1091): | ||||
pass | pass | ||||
@@ -217,7 +217,7 @@ class Database: | |||||
could cause the system to hang.""" | could cause the system to hang.""" | ||||
if self.transaction_writes and \ | if self.transaction_writes and \ | ||||
query and query.strip().split()[0].lower() in ['start', 'alter', 'drop', 'create', "begin", "truncate"]: | 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'): | if query and query.strip().lower() in ('commit', 'rollback'): | ||||
self.transaction_writes = 0 | self.transaction_writes = 0 | ||||
@@ -455,7 +455,7 @@ class Database: | |||||
if (filters is not None) and (filters!=doctype or doctype=="DocType"): | if (filters is not None) and (filters!=doctype or doctype=="DocType"): | ||||
try: | try: | ||||
out = self._get_values_from_table(fields, filters, doctype, as_dict, debug, order_by, update) | 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): | if ignore and e.args[0] in (1146, 1054): | ||||
# table or column not found, return None | # table or column not found, return None | ||||
out = None | out = None | ||||
@@ -32,7 +32,7 @@ def update(doctype, field, value, condition='', limit=500): | |||||
try: | try: | ||||
doc.save() | doc.save() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
frappe.msgprint(_("Validation failed for {0}").format(frappe.bold(doc.name))) | frappe.msgprint(_("Validation failed for {0}").format(frappe.bold(doc.name))) | ||||
raise e | raise e | ||||
@@ -145,7 +145,7 @@ def add_user_icon(_doctype, _report=None, label=None, link=None, type='link', st | |||||
icon_name = new_icon.name | icon_name = new_icon.name | ||||
except Exception, e: | |||||
except Exception as e: | |||||
raise e | raise e | ||||
return icon_name | return icon_name | ||||
@@ -194,7 +194,7 @@ def set_desktop_icons(visible_list, ignore_duplicate=True): | |||||
if frappe.db.exists('DocType', module_name): | if frappe.db.exists('DocType', module_name): | ||||
try: | try: | ||||
add_user_icon(module_name, standard=1) | add_user_icon(module_name, standard=1) | ||||
except frappe.UniqueValidationError, e: | |||||
except frappe.UniqueValidationError as e: | |||||
if not ignore_duplicate: | if not ignore_duplicate: | ||||
raise e | raise e | ||||
else: | else: | ||||
@@ -65,7 +65,7 @@ class ToDo(Document): | |||||
frappe.db.set_value(self.reference_type, self.reference_name, | frappe.db.set_value(self.reference_type, self.reference_name, | ||||
"_assign", json.dumps(assignments), update_modified=False) | "_assign", json.dumps(assignments), update_modified=False) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0] == 1146 and frappe.flags.in_install: | if e.args[0] == 1146 and frappe.flags.in_install: | ||||
# no table | # no table | ||||
return | return | ||||
@@ -20,7 +20,7 @@ def savedocs(doc, action): | |||||
else: | else: | ||||
try: | try: | ||||
doc.save() | 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) | 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)) | frappe.msgprint(frappe._("{0} {1} already exists").format(doctype, name)) | ||||
raise | raise | ||||
@@ -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) | 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: | if isinstance(e.args, (tuple, list)) and e.args and e.args[0]==1054: | ||||
add_column(doctype, "_liked_by", "Text") | add_column(doctype, "_liked_by", "Text") | ||||
_toggle_like(doctype, name, add, user) | _toggle_like(doctype, name, add, user) | ||||
@@ -196,7 +196,7 @@ def get_last_modified(doctype): | |||||
def _get(): | def _get(): | ||||
try: | try: | ||||
last_modified = frappe.get_all(doctype, fields=["max(modified)"], as_list=True, limit_page_length=1)[0][0] | 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: | if e.args[0]==1146: | ||||
last_modified = None | last_modified = None | ||||
else: | else: | ||||
@@ -100,7 +100,7 @@ def get_notifications_for_doctypes(config, notification_count): | |||||
pass | pass | ||||
# frappe.msgprint("Permission Error in notifications for {0}".format(d)) | # 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') | # OperationalError: (1412, 'Table definition has changed, please retry transaction') | ||||
if e.args[0]!=1412: | if e.args[0]!=1412: | ||||
raise | raise | ||||
@@ -31,7 +31,7 @@ def check_user_tags(dt): | |||||
"if the user does not have a tags column, then it creates one" | "if the user does not have a tags column, then it creates one" | ||||
try: | try: | ||||
frappe.db.sql("select `_user_tags` from `tab%s` limit 1" % dt) | frappe.db.sql("select `_user_tags` from `tab%s` limit 1" % dt) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0] == 1054: | if e.args[0] == 1054: | ||||
DocTags(dt).setup() | DocTags(dt).setup() | ||||
@@ -57,7 +57,7 @@ def get_tags(doctype, txt, cat_tags): | |||||
where _user_tags like '%{1}%' | where _user_tags like '%{1}%' | ||||
limit 50""".format(frappe.db.escape(doctype), frappe.db.escape(txt))): | limit 50""".format(frappe.db.escape(doctype), frappe.db.escape(txt))): | ||||
tags.extend(_user_tags[1:].split(",")) | tags.extend(_user_tags[1:].split(",")) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1054: raise | if e.args[0]!=1054: raise | ||||
return sorted(filter(lambda t: t and txt.lower() in t.lower(), list(set(tags)))) | return sorted(filter(lambda t: t and txt.lower() in t.lower(), list(set(tags)))) | ||||
@@ -102,7 +102,7 @@ class DocTags: | |||||
try: | try: | ||||
frappe.db.sql("update `tab%s` set _user_tags=%s where name=%s" % \ | frappe.db.sql("update `tab%s` set _user_tags=%s where name=%s" % \ | ||||
(self.dt,'%s','%s'), (tags , dn)) | (self.dt,'%s','%s'), (tags , dn)) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1054: | if e.args[0]==1054: | ||||
if not tags: | if not tags: | ||||
# no tags, nothing to do | # no tags, nothing to do | ||||
@@ -26,7 +26,7 @@ def get_contact_list(txt): | |||||
) | ) | ||||
if not out: | if not out: | ||||
out = get_users() | out = get_users() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1146: | if e.args[0]==1146: | ||||
# no Contact, use User | # no Contact, use User | ||||
out = get_users() | out = get_users() | ||||
@@ -161,7 +161,7 @@ class EmailAccount(Document): | |||||
email_server = EmailServer(frappe._dict(args)) | email_server = EmailServer(frappe._dict(args)) | ||||
try: | try: | ||||
email_server.connect() | email_server.connect() | ||||
except (error_proto, imaplib.IMAP4.error), e: | |||||
except (error_proto, imaplib.IMAP4.error) as e: | |||||
message = e.message.lower().replace(" ","") | 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 | 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 | '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)}) | frappe.publish_realtime('new_email', {"account":self.email_account_name, "number":len(incoming_mails)}) | ||||
if exceptions: | if exceptions: | ||||
raise Exception, frappe.as_json(exceptions) | |||||
raise Exception(frappe.as_json(exceptions)) | |||||
def handle_bad_emails(self, email_server, uid, raw, reason): | def handle_bad_emails(self, email_server, uid, raw, reason): | ||||
if cint(email_server.settings.use_imap): | if cint(email_server.settings.use_imap): | ||||
@@ -73,7 +73,7 @@ class EmailDomain(Document): | |||||
email_account.set("smtp_server",self.smtp_server) | email_account.set("smtp_server",self.smtp_server) | ||||
email_account.set("smtp_port",self.smtp_port) | email_account.set("smtp_port",self.smtp_port) | ||||
email_account.save() | email_account.save() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
frappe.msgprint(email_account.name) | frappe.msgprint(email_account.name) | ||||
frappe.throw(e) | frappe.throw(e) | ||||
return None | return None | ||||
@@ -406,7 +406,7 @@ def send_one(email, smtpserver=None, auto_commit=True, now=False, from_test=Fals | |||||
# no need to attempt further | # no need to attempt further | ||||
return | return | ||||
except Exception, e: | |||||
except Exception as e: | |||||
frappe.db.rollback() | frappe.db.rollback() | ||||
if any("Sent" == s.status for s in recipients_list): | if any("Sent" == s.status for s in recipients_list): | ||||
@@ -58,7 +58,7 @@ class EmailServer: | |||||
frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) | frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) | ||||
raise | raise | ||||
except Exception, e: | |||||
except Exception as e: | |||||
frappe.msgprint(_('Cannot connect: {0}').format(str(e))) | frappe.msgprint(_('Cannot connect: {0}').format(str(e))) | ||||
raise | raise | ||||
@@ -84,7 +84,7 @@ class EmailServer: | |||||
frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) | frappe.msgprint(_('Invalid Mail Server. Please rectify and try again.')) | ||||
raise | raise | ||||
except poplib.error_proto, e: | |||||
except poplib.error_proto as e: | |||||
if self.is_temporary_system_problem(e): | if self.is_temporary_system_problem(e): | ||||
return False | return False | ||||
@@ -143,7 +143,7 @@ class EmailServer: | |||||
for m in xrange(101, num+1): | for m in xrange(101, num+1): | ||||
self.pop.dele(m) | self.pop.dele(m) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if self.has_login_limit_exceeded(e): | if self.has_login_limit_exceeded(e): | ||||
pass | pass | ||||
@@ -246,10 +246,10 @@ class EmailServer: | |||||
self.errors = True | self.errors = True | ||||
raise | raise | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if self.has_login_limit_exceeded(e): | if self.has_login_limit_exceeded(e): | ||||
self.errors = True | self.errors = True | ||||
raise LoginLimitExceeded, e | |||||
raise LoginLimitExceeded(e) | |||||
else: | else: | ||||
# log performs rollback and logs error in Error Log | # log performs rollback and logs error in Error Log | ||||
@@ -2,7 +2,7 @@ | |||||
# MIT License. See license.txt | # MIT License. See license.txt | ||||
from __future__ import unicode_literals | from __future__ import unicode_literals | ||||
from six import reraise as raise_ | |||||
import frappe | import frappe | ||||
import smtplib | import smtplib | ||||
import email.utils | import email.utils | ||||
@@ -183,22 +183,20 @@ class SMTPServer: | |||||
# check if logged correctly | # check if logged correctly | ||||
if ret[0]!=235: | if ret[0]!=235: | ||||
frappe.msgprint(ret[1]) | frappe.msgprint(ret[1]) | ||||
raise frappe.OutgoingEmailError, ret[1] | |||||
raise frappe.OutgoingEmailError(ret[1]) | |||||
return self._sess | return self._sess | ||||
except _socket.error, e: | |||||
except _socket.error as e: | |||||
# Invalid mail server -- due to refusing connection | # Invalid mail server -- due to refusing connection | ||||
frappe.msgprint(_('Invalid Outgoing Mail Server or Port')) | 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")) | 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: | except smtplib.SMTPException: | ||||
frappe.msgprint(_('Unable to send emails at this time')) | frappe.msgprint(_('Unable to send emails at this time')) | ||||
@@ -26,7 +26,7 @@ class DropboxSettings(Document): | |||||
def validate_dropbox_credentails(self): | def validate_dropbox_credentails(self): | ||||
try: | try: | ||||
self.get_dropbox_session() | self.get_dropbox_session() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
frappe.throw(e.message) | frappe.throw(e.message) | ||||
def get_dropbox_session(self): | def get_dropbox_session(self): | ||||
@@ -213,7 +213,7 @@ def upload_file_to_dropbox(filename, folder, dropbox_client): | |||||
uploader.upload_chunked() | uploader.upload_chunked() | ||||
uploader.finish(folder + "/" + os.path.basename(filename), overwrite=True) | 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.'", | # if "[401] u'Access token not found.'", | ||||
# it means that the user needs to again allow dropbox backup from the UI | # it means that the user needs to again allow dropbox backup from the UI | ||||
# so re-raise | # so re-raise | ||||
@@ -242,9 +242,9 @@ def upload_from_folder(path, dropbox_folder, dropbox_client, did_not_upload, err | |||||
try: | try: | ||||
response = dropbox_client.metadata(dropbox_folder) | response = dropbox_client.metadata(dropbox_folder) | ||||
except dropbox.rest.ErrorResponse, e: | |||||
except dropbox.rest.ErrorResponse as e: | |||||
# folder not found | # folder not found | ||||
if e.status==404: | |||||
if e.status == 404: | |||||
response = {"contents": []} | response = {"contents": []} | ||||
else: | else: | ||||
raise | raise | ||||
@@ -22,7 +22,7 @@ def make_get_request(url, auth=None, headers=None, data=None): | |||||
frappe.flags.integration_request.raise_for_status() | frappe.flags.integration_request.raise_for_status() | ||||
return frappe.flags.integration_request.json() | return frappe.flags.integration_request.json() | ||||
except Exception, exc: | |||||
except Exception as exc: | |||||
frappe.log_error(frappe.get_traceback()) | frappe.log_error(frappe.get_traceback()) | ||||
raise exc | 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 urlparse.parse_qs(frappe.flags.integration_request.text) | ||||
return frappe.flags.integration_request.json() | return frappe.flags.integration_request.json() | ||||
except Exception, exc: | |||||
except Exception as exc: | |||||
frappe.log_error() | frappe.log_error() | ||||
raise exc | raise exc | ||||
@@ -2,6 +2,7 @@ | |||||
# MIT License. See license.txt | # MIT License. See license.txt | ||||
from __future__ import unicode_literals | from __future__ import unicode_literals | ||||
from six import reraise as raise_ | |||||
import frappe, sys | import frappe, sys | ||||
from frappe import _ | from frappe import _ | ||||
from frappe.utils import (cint, flt, now, cstr, strip_html, getdate, get_datetime, to_timedelta, | 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): | if issubclass(_class, BaseDocument): | ||||
_class = getattr(module, classname) | _class = getattr(module, classname) | ||||
else: | else: | ||||
raise ImportError, doctype | |||||
raise ImportError(doctype) | |||||
else: | else: | ||||
raise ImportError, doctype | |||||
raise ImportError(doctype) | |||||
_classes[doctype] = _class | _classes[doctype] = _class | ||||
return _classes[doctype] | return _classes[doctype] | ||||
@@ -140,7 +141,9 @@ class BaseDocument(object): | |||||
value.parent_doc = self | value.parent_doc = self | ||||
return value | return value | ||||
else: | 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): | def extend(self, key, value): | ||||
if isinstance(value, list): | if isinstance(value, list): | ||||
@@ -159,7 +162,7 @@ class BaseDocument(object): | |||||
if "doctype" not in value: | if "doctype" not in value: | ||||
value["doctype"] = self.get_table_field_doctype(key) | value["doctype"] = self.get_table_field_doctype(key) | ||||
if not value["doctype"]: | if not value["doctype"]: | ||||
raise AttributeError, key | |||||
raise AttributeError(key) | |||||
value = get_controller(value["doctype"])(value) | value = get_controller(value["doctype"])(value) | ||||
value.init_valid_columns() | value.init_valid_columns() | ||||
@@ -294,7 +297,7 @@ class BaseDocument(object): | |||||
columns = ", ".join(["`"+c+"`" for c in columns]), | columns = ", ".join(["`"+c+"`" for c in columns]), | ||||
values = ", ".join(["%s"] * len(columns)) | values = ", ".join(["%s"] * len(columns)) | ||||
), d.values()) | ), d.values()) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1062: | if e.args[0]==1062: | ||||
if "PRIMARY" in cstr(e.args[1]): | if "PRIMARY" in cstr(e.args[1]): | ||||
if self.meta.autoname=="hash": | if self.meta.autoname=="hash": | ||||
@@ -303,9 +306,9 @@ class BaseDocument(object): | |||||
self.db_insert() | self.db_insert() | ||||
return | return | ||||
type, value, traceback = sys.exc_info() | |||||
frappe.msgprint(_("Duplicate name {0} {1}").format(self.doctype, self.name)) | 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]): | elif "Duplicate" in cstr(e.args[1]): | ||||
# unique constraint | # unique constraint | ||||
@@ -336,7 +339,7 @@ class BaseDocument(object): | |||||
doctype = self.doctype, | doctype = self.doctype, | ||||
values = ", ".join(["`"+c+"`=%s" for c in columns]) | values = ", ".join(["`"+c+"`=%s" for c in columns]) | ||||
), d.values() + [name]) | ), d.values() + [name]) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1062 and "Duplicate" in cstr(e.args[1]): | if e.args[0]==1062 and "Duplicate" in cstr(e.args[1]): | ||||
self.show_unique_validation_message(e) | self.show_unique_validation_message(e) | ||||
else: | else: | ||||
@@ -358,7 +361,7 @@ class BaseDocument(object): | |||||
frappe.msgprint(_("{0} must be unique".format(label or fieldname))) | frappe.msgprint(_("{0} must be unique".format(label or fieldname))) | ||||
# this is used to preserve traceback | # 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): | def db_set(self, fieldname, value=None, update_modified=True): | ||||
'''Set a value in the document object, update the timestamp and update the database. | '''Set a value in the document object, update the timestamp and update the database. | ||||
@@ -60,7 +60,7 @@ def updatedb(dt, meta=None): | |||||
""" | """ | ||||
res = frappe.db.sql("select issingle from tabDocType where name=%s", (dt,)) | res = frappe.db.sql("select issingle from tabDocType where name=%s", (dt,)) | ||||
if not res: | if not res: | ||||
raise Exception, 'Wrong doctype "%s" in updatedb' % dt | |||||
raise Exception('Wrong doctype "%s" in updatedb' % dt) | |||||
if not res[0][0]: | if not res[0][0]: | ||||
tab = DbTable(dt, 'tab', meta) | tab = DbTable(dt, 'tab', meta) | ||||
@@ -118,7 +118,7 @@ class DbTable: | |||||
max_length = frappe.db.sql("""select max(char_length(`{fieldname}`)) from `tab{doctype}`"""\ | max_length = frappe.db.sql("""select max(char_length(`{fieldname}`)) from `tab{doctype}`"""\ | ||||
.format(fieldname=col.fieldname, doctype=self.doctype)) | .format(fieldname=col.fieldname, doctype=self.doctype)) | ||||
except MySQLdb.OperationalError, e: | |||||
except MySQLdb.OperationalError as e: | |||||
if e.args[0]==1054: | if e.args[0]==1054: | ||||
# Unknown column 'column_name' in 'field list' | # Unknown column 'column_name' in 'field list' | ||||
continue | continue | ||||
@@ -337,7 +337,7 @@ class DbTable: | |||||
if query: | if query: | ||||
try: | try: | ||||
frappe.db.sql("alter table `{}` {}".format(self.name, ", ".join(query))) | frappe.db.sql("alter table `{}` {}".format(self.name, ", ".join(query))) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
# sanitize | # sanitize | ||||
if e.args[0]==1060: | if e.args[0]==1060: | ||||
frappe.throw(str(e)) | frappe.throw(str(e)) | ||||
@@ -504,7 +504,7 @@ class DbManager: | |||||
host = self.get_current_host() | host = self.get_current_host() | ||||
try: | try: | ||||
self.db.sql("DROP USER '%s'@'%s';" % (target, host)) | self.db.sql("DROP USER '%s'@'%s';" % (target, host)) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1396: | if e.args[0]==1396: | ||||
pass | pass | ||||
else: | else: | ||||
@@ -570,7 +570,7 @@ def remove_all_foreign_keys(): | |||||
dbtab = DbTable(t[0]) | dbtab = DbTable(t[0]) | ||||
try: | try: | ||||
fklist = dbtab.get_foreign_keys() | fklist = dbtab.get_foreign_keys() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1146: | if e.args[0]==1146: | ||||
fklist = [] | fklist = [] | ||||
else: | else: | ||||
@@ -50,7 +50,7 @@ def get_doc(arg1, arg2=None): | |||||
if controller: | if controller: | ||||
return controller(arg1, arg2) | return controller(arg1, arg2) | ||||
raise ImportError, arg1 | |||||
raise ImportError(arg1) | |||||
class Document(BaseDocument): | class Document(BaseDocument): | ||||
"""All controllers inherit from `Document`.""" | """All controllers inherit from `Document`.""" | ||||
@@ -203,9 +203,9 @@ class Document(BaseDocument): | |||||
else: | else: | ||||
try: | try: | ||||
self.db_insert() | self.db_insert() | ||||
except frappe.DuplicateEntryError, e: | |||||
except frappe.DuplicateEntryError as e: | |||||
if not ignore_if_duplicate: | if not ignore_if_duplicate: | ||||
raise e | |||||
raise e | |||||
# children | # children | ||||
for d in self.get_all_children(): | for d in self.get_all_children(): | ||||
@@ -562,7 +562,7 @@ class Document(BaseDocument): | |||||
self._action = "submit" | self._action = "submit" | ||||
self.check_permission("submit") | self.check_permission("submit") | ||||
else: | else: | ||||
raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 0 to 2") | |||||
raise frappe.DocstatusTransitionError(_("Cannot change docstatus from 0 to 2")) | |||||
elif docstatus==1: | elif docstatus==1: | ||||
if self.docstatus==1: | if self.docstatus==1: | ||||
@@ -572,10 +572,10 @@ class Document(BaseDocument): | |||||
self._action = "cancel" | self._action = "cancel" | ||||
self.check_permission("cancel") | self.check_permission("cancel") | ||||
else: | else: | ||||
raise frappe.DocstatusTransitionError, _("Cannot change docstatus from 1 to 0") | |||||
raise frappe.DocstatusTransitionError(_("Cannot change docstatus from 1 to 0")) | |||||
elif docstatus==2: | elif docstatus==2: | ||||
raise frappe.ValidationError, _("Cannot edit cancelled document") | |||||
raise frappe.ValidationError(_("Cannot edit cancelled document")) | |||||
def set_parent_in_children(self): | def set_parent_in_children(self): | ||||
"""Updates `parent` and `parenttype` property in all children.""" | """Updates `parent` and `parenttype` property in all children.""" | ||||
@@ -230,7 +230,7 @@ class Meta(Document): | |||||
self.extend("fields", frappe.db.sql("""SELECT * FROM `tabCustom Field` | self.extend("fields", frappe.db.sql("""SELECT * FROM `tabCustom Field` | ||||
WHERE dt = %s AND docstatus < 2""", (self.name,), as_dict=1, | WHERE dt = %s AND docstatus < 2""", (self.name,), as_dict=1, | ||||
update={"is_custom_field": 1})) | update={"is_custom_field": 1})) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]==1146: | if e.args[0]==1146: | ||||
return | return | ||||
else: | else: | ||||
@@ -385,7 +385,7 @@ def is_single(doctype): | |||||
try: | try: | ||||
return frappe.db.get_value("DocType", doctype, "issingle") | return frappe.db.get_value("DocType", doctype, "issingle") | ||||
except IndexError: | 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): | def get_parent_dt(dt): | ||||
parent_dt = frappe.db.sql("""select parent from tabDocField | parent_dt = frappe.db.sql("""select parent from tabDocField | ||||
@@ -85,7 +85,7 @@ def update_attachments(doctype, old, new): | |||||
if old != "File Data" and doctype != "DocType": | if old != "File Data" and doctype != "DocType": | ||||
frappe.db.sql("""update `tabFile` set attached_to_name=%s | frappe.db.sql("""update `tabFile` set attached_to_name=%s | ||||
where attached_to_name=%s and attached_to_doctype=%s""", (new, old, doctype)) | 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? | if e.args[0]!=1054: # in patch? | ||||
raise | raise | ||||
@@ -373,7 +373,7 @@ def bulk_rename(doctype, rows=None, via_console = False): | |||||
frappe.db.commit() | frappe.db.commit() | ||||
else: | else: | ||||
msg = _("Ignored: {0} to {1}").format(row[0], row[1]) | 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)) | msg = _("** Failed: {0} to {1}: {2}").format(row[0], row[1], repr(e)) | ||||
frappe.db.rollback() | frappe.db.rollback() | ||||
@@ -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')) | oc = frappe.get_doc("OAuth Client", frappe.db.get_value("OAuth Bearer Token", frappe.get_request_header("Authorization").split(" ")[1], 'client')) | ||||
try: | try: | ||||
request.client = request.client or oc.as_dict() | 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)) | 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")) | return frappe.session.user == urllib.unquote(cookie_dict.get('user_id', "Guest")) | ||||
@@ -20,6 +20,6 @@ def execute(): | |||||
def rename_field_if_exists(doctype, old_fieldname, new_fieldname): | def rename_field_if_exists(doctype, old_fieldname, new_fieldname): | ||||
try: | try: | ||||
rename_field(doctype, old_fieldname, new_fieldname) | rename_field(doctype, old_fieldname, new_fieldname) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0] != 1054: | if e.args[0] != 1054: | ||||
raise | raise |
@@ -6,6 +6,6 @@ def execute(): | |||||
where ifnull(reference_type, '')!='' and ifnull(reference_name, '')!=''"""): | where ifnull(reference_type, '')!='' and ifnull(reference_name, '')!=''"""): | ||||
try: | try: | ||||
frappe.get_doc("ToDo", name).on_update() | frappe.get_doc("ToDo", name).on_update() | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1146: | if e.args[0]!=1146: | ||||
raise | raise |
@@ -14,7 +14,7 @@ def execute(): | |||||
try: | try: | ||||
result = frappe.get_all(opts.parent, fields=["name", opts.fieldname]) | result = frappe.get_all(opts.parent, fields=["name", opts.fieldname]) | ||||
except frappe.SQLError, e: | |||||
except frappe.SQLError as e: | |||||
# bypass single tables | # bypass single tables | ||||
continue | continue | ||||
@@ -7,13 +7,13 @@ import frappe | |||||
def execute(): | def execute(): | ||||
try: | try: | ||||
frappe.db.sql("alter table `tabEmail Queue` change `ref_docname` `reference_name` varchar(255)") | 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): | if e.args[0] not in (1054, 1060): | ||||
raise | raise | ||||
try: | try: | ||||
frappe.db.sql("alter table `tabEmail Queue` change `ref_doctype` `reference_doctype` varchar(255)") | 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): | if e.args[0] not in (1054, 1060): | ||||
raise | raise | ||||
frappe.reload_doctype("Email Queue") | frappe.reload_doctype("Email Queue") |
@@ -260,7 +260,7 @@ def update_for_dynamically_linked_docs(timeline_doctype): | |||||
try: | try: | ||||
docs = frappe.get_all(reference_doctype, fields=["name", df.fieldname], | docs = frappe.get_all(reference_doctype, fields=["name", df.fieldname], | ||||
filters={ df.options: timeline_doctype }) | filters={ df.options: timeline_doctype }) | ||||
except frappe.SQLError, e: | |||||
except frappe.SQLError as e: | |||||
if e.args and e.args[0]==1146: | if e.args and e.args[0]==1146: | ||||
# single | # single | ||||
continue | continue | ||||
@@ -18,5 +18,5 @@ def update_routes(doctypes): | |||||
frappe.db.sql("""update ignore `tab{0}` set route = concat(ifnull(parent_website_route, ""), | 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)) | if(ifnull(parent_website_route, "")="", "", "/"), page_name) {1}""".format(d, condition)) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1054: raise | if e.args[0]!=1054: raise |
@@ -5,7 +5,7 @@ def execute(): | |||||
try: | try: | ||||
frappe.db.sql('update `tabCustom Field` set in_standard_filter = in_filter_dash') | 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 | if e.args[0]!=1054: raise e | ||||
for doctype in frappe.get_all("DocType", {"istable": 0, "issingle": 0, "custom": 0}): | for doctype in frappe.get_all("DocType", {"istable": 0, "issingle": 0, "custom": 0}): | ||||
@@ -303,7 +303,7 @@ def make_test_objects(doctype, test_records=None, verbose=None, reset=False): | |||||
except frappe.NameError: | except frappe.NameError: | ||||
pass | 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: | if d.flags.ignore_these_exceptions_in_test and e.__class__ in d.flags.ignore_these_exceptions_in_test: | ||||
pass | pass | ||||
@@ -227,7 +227,7 @@ def get_file_timestamp(fn): | |||||
try: | try: | ||||
return str(cint(os.stat(fn).st_mtime)) | return str(cint(os.stat(fn).st_mtime)) | ||||
except OSError, e: | |||||
except OSError as e: | |||||
if e.args[0]!=2: | if e.args[0]!=2: | ||||
raise | raise | ||||
else: | else: | ||||
@@ -64,7 +64,7 @@ def execute_job(site, method, event, job_name, kwargs, user=None, async=True, re | |||||
try: | try: | ||||
method(**kwargs) | method(**kwargs) | ||||
except (MySQLdb.OperationalError, frappe.RetryBackgroundJobError), e: | |||||
except (MySQLdb.OperationalError, frappe.RetryBackgroundJobError) as e: | |||||
frappe.db.rollback() | frappe.db.rollback() | ||||
if (retry < 5 and | if (retry < 5 and | ||||
@@ -29,8 +29,8 @@ def user_to_str(date, date_format=None): | |||||
try: | try: | ||||
return datetime.datetime.strptime(date, | return datetime.datetime.strptime(date, | ||||
dateformats[date_format]).strftime('%Y-%m-%d') | 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): | def parse_date(date): | ||||
"""tries to parse given date to system's format i.e. yyyy-mm-dd. returns a string""" | """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) | parsed_date = user_to_str(date, f) | ||||
if parsed_date: | if parsed_date: | ||||
break | break | ||||
except ValueError, e: | |||||
except ValueError as e: | |||||
pass | pass | ||||
if not parsed_date: | 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 | return parsed_date | ||||
@@ -40,7 +40,7 @@ def make_error_snapshot(exception): | |||||
logger.error('New Exception collected with id: {}'.format(error_id)) | 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) | logger.error('Could not take error snapshot: {0}'.format(e), exc_info=True) | ||||
def get_snapshot(exception, context=10): | def get_snapshot(exception, context=10): | ||||
@@ -236,7 +236,7 @@ def remove_all(dt, dn, from_delete=False): | |||||
for fid in frappe.db.sql_list("""select name from `tabFile` where | for fid in frappe.db.sql_list("""select name from `tabFile` where | ||||
attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)): | attached_to_doctype=%s and attached_to_name=%s""", (dt, dn)): | ||||
remove_file(fid, dt, dn, from_delete) | remove_file(fid, dt, dn, from_delete) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1054: raise # (temp till for patched) | if e.args[0]!=1054: raise # (temp till for patched) | ||||
def remove_file_by_url(file_url, doctype=None, name=None): | def remove_file_by_url(file_url, doctype=None, name=None): | ||||
@@ -51,7 +51,7 @@ class HelpDatabase(object): | |||||
if not self.help_db_name in dbman.get_database_list(): | if not self.help_db_name in dbman.get_database_list(): | ||||
try: | try: | ||||
dbman.create_user(self.help_db_name, self.help_db_name) | dbman.create_user(self.help_db_name, self.help_db_name) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
# user already exists | # user already exists | ||||
if e.args[0] != 1396: raise | if e.args[0] != 1396: raise | ||||
dbman.create_database(self.help_db_name) | dbman.create_database(self.help_db_name) | ||||
@@ -30,7 +30,7 @@ def validate_template(html): | |||||
jenv = get_jenv() | jenv = get_jenv() | ||||
try: | try: | ||||
jenv.from_string(html) | jenv.from_string(html) | ||||
except TemplateSyntaxError, e: | |||||
except TemplateSyntaxError as e: | |||||
frappe.msgprint('Line {}: {}'.format(e.lineno, e.message)) | frappe.msgprint('Line {}: {}'.format(e.lineno, e.message)) | ||||
frappe.throw(frappe._("Syntax error in template")) | frappe.throw(frappe._("Syntax error in template")) | ||||
@@ -60,7 +60,7 @@ def delete_all_passwords_for(doctype, name): | |||||
try: | try: | ||||
frappe.db.sql("""delete from __Auth where doctype=%(doctype)s and name=%(name)s""", | frappe.db.sql("""delete from __Auth where doctype=%(doctype)s and name=%(name)s""", | ||||
{ 'doctype': doctype, 'name': name }) | { 'doctype': doctype, 'name': name }) | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1054: | if e.args[0]!=1054: | ||||
raise | raise | ||||
@@ -21,7 +21,7 @@ def get_pdf(html, options=None, output = None): | |||||
with open(fname, "rb") as fileobj: | with open(fname, "rb") as fileobj: | ||||
filedata = fileobj.read() | filedata = fileobj.read() | ||||
except IOError, e: | |||||
except IOError as e: | |||||
if ("ContentNotFoundError" in e.message | if ("ContentNotFoundError" in e.message | ||||
or "ContentOperationNotPermittedError" in e.message | or "ContentOperationNotPermittedError" in e.message | ||||
or "UnknownContentError" in e.message | or "UnknownContentError" in e.message | ||||
@@ -270,7 +270,7 @@ def reset_enabled_scheduler_events(login_manager): | |||||
if login_manager.info.user_type == "System User": | if login_manager.info.user_type == "System User": | ||||
try: | try: | ||||
frappe.db.set_global('enabled_scheduler_events', None) | frappe.db.set_global('enabled_scheduler_events', None) | ||||
except MySQLdb.OperationalError, e: | |||||
except MySQLdb.OperationalError as e: | |||||
if e.args[0]==1205: | if e.args[0]==1205: | ||||
frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events") | frappe.log_error(frappe.get_traceback(), "Error in reset_enabled_scheduler_events") | ||||
else: | else: | ||||
@@ -43,7 +43,7 @@ class UserPermissions: | |||||
user = frappe.get_doc("User", self.name).as_dict() | user = frappe.get_doc("User", self.name).as_dict() | ||||
except frappe.DoesNotExistError: | except frappe.DoesNotExistError: | ||||
pass | pass | ||||
except Exception, e: | |||||
except Exception as e: | |||||
# install boo-boo | # install boo-boo | ||||
if e.args[0] != 1146: raise | if e.args[0] != 1146: raise | ||||
@@ -30,7 +30,7 @@ def render(path=None, http_status_code=None): | |||||
else: | else: | ||||
try: | try: | ||||
data = render_page_by_language(path) | data = render_page_by_language(path) | ||||
except frappe.DoesNotExistError, e: | |||||
except frappe.DoesNotExistError as e: | |||||
doctype, name = get_doctype_from_path(path) | doctype, name = get_doctype_from_path(path) | ||||
if doctype and name: | if doctype and name: | ||||
path = "print" | path = "print" | ||||
@@ -48,13 +48,13 @@ def render(path=None, http_status_code=None): | |||||
if not data: | if not data: | ||||
try: | try: | ||||
data = render_page(path) | data = render_page(path) | ||||
except frappe.PermissionError, e: | |||||
except frappe.PermissionError as e: | |||||
data, http_status_code = render_403(e, path) | 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) | data, http_status_code = render_403(e, path) | ||||
except frappe.Redirect, e: | |||||
except frappe.Redirect as e: | |||||
return build_response(path, "", 301, { | return build_response(path, "", 301, { | ||||
"Location": frappe.flags.redirect_location or (frappe.local.response or {}).get('location'), | "Location": frappe.flags.redirect_location or (frappe.local.response or {}).get('location'), | ||||
"Cache-Control": "no-store, no-cache, must-revalidate" | "Cache-Control": "no-store, no-cache, must-revalidate" | ||||
@@ -112,7 +112,7 @@ def get_page_info_from_doctypes(path=None): | |||||
# just want one path, return it! | # just want one path, return it! | ||||
if path: | if path: | ||||
return routes[r.route] | return routes[r.route] | ||||
except Exception, e: | |||||
except Exception as e: | |||||
if e.args[0]!=1054: raise e | if e.args[0]!=1054: raise e | ||||
return routes | return routes | ||||