Przeglądaj źródła

Python 3 compatible print statements (#3199)

* changes print statements in file to python 3 compatible style using `__future__`

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* changes deprecated md5 module to hashlib

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements

* adds python 3 style for print statements
version-14
tundebabzy 8 lat temu
committed by Rushabh Mehta
rodzic
commit
7b41d7e5eb
48 zmienionych plików z 212 dodań i 206 usunięć
  1. +6
    -6
      frappe/__init__.py
  2. +10
    -10
      frappe/build.py
  3. +3
    -3
      frappe/commands/__init__.py
  4. +7
    -7
      frappe/commands/scheduler.py
  5. +8
    -8
      frappe/commands/site.py
  6. +3
    -3
      frappe/commands/translate.py
  7. +7
    -7
      frappe/commands/utils.py
  8. +2
    -2
      frappe/core/page/data_import_tool/data_import_tool.py
  9. +2
    -2
      frappe/core/page/data_import_tool/importer.py
  10. +2
    -2
      frappe/desk/tags.py
  11. +2
    -2
      frappe/email/doctype/email_account/email_account.py
  12. +5
    -4
      frappe/frappeclient.py
  13. +17
    -17
      frappe/installer.py
  14. +2
    -2
      frappe/model/document.py
  15. +2
    -2
      frappe/model/meta.py
  16. +2
    -2
      frappe/model/rename_doc.py
  17. +2
    -2
      frappe/model/sync.py
  18. +2
    -2
      frappe/model/utils/__init__.py
  19. +2
    -2
      frappe/model/utils/rename_field.py
  20. +3
    -3
      frappe/modules/import_file.py
  21. +2
    -2
      frappe/modules/patch_handler.py
  22. +3
    -3
      frappe/modules/utils.py
  23. +2
    -1
      frappe/oauth.py
  24. +2
    -2
      frappe/patches/v4_0/create_custom_field_for_owner_match.py
  25. +5
    -5
      frappe/patches/v4_1/file_manager_fix.py
  26. +3
    -3
      frappe/patches/v5_0/fix_text_editor_file_urls.py
  27. +2
    -1
      frappe/patches/v6_1/rename_file_data.py
  28. +4
    -2
      frappe/patches/v6_4/reduce_varchar_length.py
  29. +2
    -1
      frappe/patches/v8_0/install_new_build_system_requirements.py
  30. +13
    -13
      frappe/permissions.py
  31. +13
    -13
      frappe/test_runner.py
  32. +4
    -4
      frappe/translate.py
  33. +8
    -8
      frappe/utils/__init__.py
  34. +2
    -2
      frappe/utils/autodoc.py
  35. +3
    -3
      frappe/utils/background_jobs.py
  36. +5
    -5
      frappe/utils/backups.py
  37. +3
    -3
      frappe/utils/bench_helper.py
  38. +5
    -5
      frappe/utils/boilerplate.py
  39. +13
    -13
      frappe/utils/doctor.py
  40. +2
    -2
      frappe/utils/fixtures.py
  41. +3
    -3
      frappe/utils/help.py
  42. +2
    -2
      frappe/utils/image.py
  43. +2
    -2
      frappe/utils/install.py
  44. +2
    -2
      frappe/utils/scheduler.py
  45. +2
    -2
      frappe/utils/sel.py
  46. +10
    -10
      frappe/utils/setup_docs.py
  47. +4
    -4
      frappe/website/doctype/web_page/web_page.py
  48. +2
    -2
      frappe/www/error.py

+ 6
- 6
frappe/__init__.py Wyświetl plik

@@ -4,7 +4,7 @@
globals attached to frappe module globals attached to frappe module
+ some utility functions that should probably be moved + some utility functions that should probably be moved
""" """
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


from werkzeug.local import Local, release_local from werkzeug.local import Local, release_local
import os, sys, importlib, inspect, json import os, sys, importlib, inspect, json
@@ -185,7 +185,7 @@ def get_site_config(sites_path=None, site_path=None):
if os.path.exists(site_config): if os.path.exists(site_config):
config.update(get_file_json(site_config)) config.update(get_file_json(site_config))
elif local.site and not local.flags.new_site: elif local.site and not local.flags.new_site:
print "{0} does not exist".format(local.site)
print("{0} does not exist".format(local.site))
sys.exit(1) sys.exit(1)
#raise IncorrectSitePath, "{0} does not exist".format(site_config) #raise IncorrectSitePath, "{0} does not exist".format(site_config)


@@ -241,7 +241,7 @@ def errprint(msg):
:param msg: Message.""" :param msg: Message."""
msg = as_unicode(msg) msg = as_unicode(msg)
if not request or (not "cmd" in local.form_dict) or conf.developer_mode: if not request or (not "cmd" in local.form_dict) or conf.developer_mode:
print msg.encode('utf-8')
print(msg.encode('utf-8'))


error_log.append(msg) error_log.append(msg)


@@ -251,7 +251,7 @@ def log(msg):
:param msg: Message.""" :param msg: Message."""
if not request: if not request:
if conf.get("logging") or False: if conf.get("logging") or False:
print repr(msg)
print(repr(msg))


debug_log.append(as_unicode(msg)) debug_log.append(as_unicode(msg))


@@ -288,7 +288,7 @@ def msgprint(msg, title=None, raise_exception=0, as_table=False, indicator=None,
out.msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>' out.msg = '<table border="1px" style="border-collapse: collapse" cellpadding="2px">' + ''.join(['<tr>'+''.join(['<td>%s</td>' % c for c in r])+'</tr>' for r in msg]) + '</table>'


if flags.print_messages and out.msg: if flags.print_messages and out.msg:
print "Message: " + repr(out.msg).encode("utf-8")
print("Message: " + repr(out.msg).encode("utf-8"))


if title: if title:
out.title = title out.title = title
@@ -784,7 +784,7 @@ def get_hooks(hook=None, default=None, app_name=None):
# if app is not installed while restoring # if app is not installed while restoring
# ignore it # ignore it
pass pass
print 'Could not find app "{0}"'.format(app_name)
print('Could not find app "{0}"'.format(app_name))
if not request: if not request:
sys.exit(1) sys.exit(1)
raise raise


+ 10
- 10
frappe/build.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
from frappe.utils.minify import JavascriptMinify from frappe.utils.minify import JavascriptMinify
import subprocess import subprocess


@@ -114,8 +114,8 @@ def get_build_maps():


build_maps[target] = source_paths build_maps[target] = source_paths
except ValueError, e: except ValueError, e:
print path
print 'JSON syntax error {0}'.format(str(e))
print(path)
print('JSON syntax error {0}'.format(str(e)))
return build_maps return build_maps


timestamps = {} timestamps = {}
@@ -130,7 +130,7 @@ def pack(target, sources, no_compress, verbose):
suffix = None suffix = None
if ':' in f: f, suffix = f.split(':') if ':' in f: f, suffix = f.split(':')
if not os.path.exists(f) or os.path.isdir(f): if not os.path.exists(f) or os.path.isdir(f):
print "did not find " + f
print("did not find " + f)
continue continue
timestamps[f] = os.path.getmtime(f) timestamps[f] = os.path.getmtime(f)
try: try:
@@ -147,7 +147,7 @@ def pack(target, sources, no_compress, verbose):
outtxt += unicode(minified or '', 'utf-8').strip('\n') + ';' outtxt += unicode(minified or '', 'utf-8').strip('\n') + ';'


if verbose: if verbose:
print "{0}: {1}k".format(f, int(len(minified) / 1024))
print("{0}: {1}k".format(f, int(len(minified) / 1024)))
elif outtype=="js" and extn=="html": elif outtype=="js" and extn=="html":
# add to frappe.templates # add to frappe.templates
outtxt += html_to_js_template(f, data) outtxt += html_to_js_template(f, data)
@@ -156,8 +156,8 @@ def pack(target, sources, no_compress, verbose):
outtxt += '\n' + data + '\n' outtxt += '\n' + data + '\n'


except Exception: except Exception:
print "--Error in:" + f + "--"
print frappe.get_traceback()
print("--Error in:" + f + "--")
print(frappe.get_traceback())


if not no_compress and outtype == 'css': if not no_compress and outtype == 'css':
pass pass
@@ -166,7 +166,7 @@ def pack(target, sources, no_compress, verbose):
with open(target, 'w') as f: with open(target, 'w') as f:
f.write(outtxt.encode("utf-8")) f.write(outtxt.encode("utf-8"))


print "Wrote %s - %sk" % (target, str(int(os.path.getsize(target)/1024)))
print("Wrote %s - %sk" % (target, str(int(os.path.getsize(target)/1024))))


def html_to_js_template(path, content): def html_to_js_template(path, content):
'''returns HTML template content as Javascript code, adding it to `frappe.templates`''' '''returns HTML template content as Javascript code, adding it to `frappe.templates`'''
@@ -189,7 +189,7 @@ def files_dirty():
if ':' in f: f, suffix = f.split(':') if ':' in f: f, suffix = f.split(':')
if not os.path.exists(f) or os.path.isdir(f): continue if not os.path.exists(f) or os.path.isdir(f): continue
if os.path.getmtime(f) != timestamps.get(f): if os.path.getmtime(f) != timestamps.get(f):
print f + ' dirty'
print(f + ' dirty')
return True return True
else: else:
return False return False
@@ -211,7 +211,7 @@ def compile_less():


timestamps[fpath] = mtime timestamps[fpath] = mtime


print "compiling {0}".format(fpath)
print("compiling {0}".format(fpath))


css_path = os.path.join(path, "public", "css", fname.rsplit(".", 1)[0] + ".css") css_path = os.path.join(path, "public", "css", fname.rsplit(".", 1)[0] + ".css")
os.system("lessc {0} > {1}".format(fpath, css_path)) os.system("lessc {0} > {1}".format(fpath, css_path))

+ 3
- 3
frappe/commands/__init__.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals, absolute_import
from __future__ import unicode_literals, absolute_import, print_function
import sys import sys
import click import click
import cProfile import cProfile
@@ -29,7 +29,7 @@ def pass_context(f):
ps = pstats.Stats(pr, stream=s)\ ps = pstats.Stats(pr, stream=s)\
.sort_stats('cumtime', 'tottime', 'ncalls') .sort_stats('cumtime', 'tottime', 'ncalls')
ps.print_stats() ps.print_stats()
print s.getvalue()
print(s.getvalue())


return ret return ret


@@ -40,7 +40,7 @@ def get_site(context):
site = context.sites[0] site = context.sites[0]
return site return site
except (IndexError, TypeError): except (IndexError, TypeError):
print 'Please specify --site sitename'
print('Please specify --site sitename')
sys.exit(1) sys.exit(1)


def call_command(cmd, context): def call_command(cmd, context):


+ 7
- 7
frappe/commands/scheduler.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals, absolute_import
from __future__ import unicode_literals, absolute_import, print_function
import click import click
import json, sys import json, sys
import frappe import frappe
@@ -42,7 +42,7 @@ def enable_scheduler(context):
frappe.connect() frappe.connect()
frappe.utils.scheduler.enable_scheduler() frappe.utils.scheduler.enable_scheduler()
frappe.db.commit() frappe.db.commit()
print "Enabled for", site
print("Enabled for", site)
finally: finally:
frappe.destroy() frappe.destroy()


@@ -57,7 +57,7 @@ def disable_scheduler(context):
frappe.connect() frappe.connect()
frappe.utils.scheduler.disable_scheduler() frappe.utils.scheduler.disable_scheduler()
frappe.db.commit() frappe.db.commit()
print "Disabled for", site
print("Disabled for", site)
finally: finally:
frappe.destroy() frappe.destroy()


@@ -90,7 +90,7 @@ def scheduler(context, state, site=None):
frappe.utils.scheduler.enable_scheduler() frappe.utils.scheduler.enable_scheduler()
frappe.db.commit() frappe.db.commit()


print 'Scheduler {0}d for site {1}'.format(state, site)
print('Scheduler {0}d for site {1}'.format(state, site))


finally: finally:
frappe.destroy() frappe.destroy()
@@ -143,7 +143,7 @@ def purge_jobs(site=None, queue=None, event=None):
from frappe.utils.doctor import purge_pending_jobs from frappe.utils.doctor import purge_pending_jobs
frappe.init(site or '') frappe.init(site or '')
count = purge_pending_jobs(event=event, site=site, queue=queue) count = purge_pending_jobs(event=event, site=site, queue=queue)
print "Purged {} jobs".format(count)
print("Purged {} jobs".format(count))


@click.command('schedule') @click.command('schedule')
def start_scheduler(): def start_scheduler():
@@ -170,11 +170,11 @@ def ready_for_migration(context, site=None):
pending_jobs = get_pending_jobs(site=site) pending_jobs = get_pending_jobs(site=site)


if pending_jobs: if pending_jobs:
print 'NOT READY for migration: site {0} has pending background jobs'.format(site)
print('NOT READY for migration: site {0} has pending background jobs'.format(site))
sys.exit(1) sys.exit(1)


else: else:
print 'READY for migration: site {0} does not have any background jobs'.format(site)
print('READY for migration: site {0} does not have any background jobs'.format(site))
return 0 return 0


finally: finally:


+ 8
- 8
frappe/commands/site.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals, absolute_import
from __future__ import unicode_literals, absolute_import, print_function
import click import click
import hashlib, os, sys import hashlib, os, sys
import frappe import frappe
@@ -65,7 +65,7 @@ def _new_site(db_name, site, mariadb_root_username=None, mariadb_root_password=N
frappe.db.commit() frappe.db.commit()


scheduler_status = "disabled" if frappe.utils.scheduler.is_scheduler_disabled() else "enabled" scheduler_status = "disabled" if frappe.utils.scheduler.is_scheduler_disabled() else "enabled"
print "*** Scheduler is", scheduler_status, "***"
print("*** Scheduler is", scheduler_status, "***")


finally: finally:
if installing and os.path.exists(installing): if installing and os.path.exists(installing):
@@ -91,7 +91,7 @@ def restore(context, sql_file_path, mariadb_root_username=None, mariadb_root_pas
if not os.path.exists(sql_file_path): if not os.path.exists(sql_file_path):
sql_file_path = '../' + sql_file_path sql_file_path = '../' + sql_file_path
if not os.path.exists(sql_file_path): if not os.path.exists(sql_file_path):
print 'Invalid path {0}' + sql_file_path[3:]
print('Invalid path {0}' + sql_file_path[3:])
sys.exit(1) sys.exit(1)


if sql_file_path.endswith('sql.gz'): if sql_file_path.endswith('sql.gz'):
@@ -162,7 +162,7 @@ def list_apps(context):
site = get_site(context) site = get_site(context)
frappe.init(site=site) frappe.init(site=site)
frappe.connect() frappe.connect()
print "\n".join(frappe.get_installed_apps())
print("\n".join(frappe.get_installed_apps()))
frappe.destroy() frappe.destroy()


@click.command('add-system-manager') @click.command('add-system-manager')
@@ -204,7 +204,7 @@ def migrate(context, rebuild_website=False):
from frappe.migrate import migrate from frappe.migrate import migrate


for site in context.sites: for site in context.sites:
print 'Migrating', site
print('Migrating', site)
frappe.init(site=site) frappe.init(site=site)
frappe.connect() frappe.connect()
try: try:
@@ -281,10 +281,10 @@ def backup(context, with_files=False, backup_path_db=None, backup_path_files=Non
odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files, backup_path_private_files=backup_path_private_files, force=True) odb = scheduled_backup(ignore_files=not with_files, backup_path_db=backup_path_db, backup_path_files=backup_path_files, backup_path_private_files=backup_path_private_files, force=True)
if verbose: if verbose:
from frappe.utils import now from frappe.utils import now
print "database backup taken -", odb.backup_path_db, "- on", now()
print("database backup taken -", odb.backup_path_db, "- on", now())
if with_files: if with_files:
print "files backup taken -", odb.backup_path_files, "- on", now()
print "private files backup taken -", odb.backup_path_private_files, "- on", now()
print("files backup taken -", odb.backup_path_files, "- on", now())
print("private files backup taken -", odb.backup_path_private_files, "- on", now())


frappe.destroy() frappe.destroy()




+ 3
- 3
frappe/commands/translate.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals, absolute_import
from __future__ import unicode_literals, absolute_import, print_function
import click import click
import frappe import frappe
from frappe.commands import pass_context, get_site from frappe.commands import pass_context, get_site
@@ -32,8 +32,8 @@ def new_language(context, lang_code, app):
frappe.connect(site=context['sites'][0]) frappe.connect(site=context['sites'][0])
frappe.translate.write_translations_file(app, lang_code) frappe.translate.write_translations_file(app, lang_code)


print "File created at ./apps/{app}/{app}/translations/{lang_code}.csv".format(app=app, lang_code=lang_code)
print "You will need to add the language in frappe/geo/languages.json, if you haven't done it already."
print("File created at ./apps/{app}/{app}/translations/{lang_code}.csv".format(app=app, lang_code=lang_code))
print("You will need to add the language in frappe/geo/languages.json, if you haven't done it already.")


@click.command('get-untranslated') @click.command('get-untranslated')
@click.argument('lang') @click.argument('lang')


+ 7
- 7
frappe/commands/utils.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals, absolute_import
from __future__ import unicode_literals, absolute_import, print_function
import click import click
import json, os, sys import json, os, sys
from distutils.spawn import find_executable from distutils.spawn import find_executable
@@ -117,7 +117,7 @@ def execute(context, method, args=None, kwargs=None):
finally: finally:
frappe.destroy() frappe.destroy()
if ret: if ret:
print json.dumps(ret)
print(json.dumps(ret))




@click.command('add-to-email-queue') @click.command('add-to-email-queue')
@@ -207,7 +207,7 @@ def import_doc(context, path, force=False):
if not os.path.exists(path): if not os.path.exists(path):
path = os.path.join('..', path) path = os.path.join('..', path)
if not os.path.exists(path): if not os.path.exists(path):
print 'Invalid path {0}'.format(path)
print('Invalid path {0}'.format(path))
sys.exit(1) sys.exit(1)


for site in context.sites: for site in context.sites:
@@ -235,7 +235,7 @@ def import_csv(context, path, only_insert=False, submit_after_import=False, igno
if not os.path.exists(path): if not os.path.exists(path):
path = os.path.join('..', path) path = os.path.join('..', path)
if not os.path.exists(path): if not os.path.exists(path):
print 'Invalid path {0}'.format(path)
print('Invalid path {0}'.format(path))
sys.exit(1) sys.exit(1)


with open(path, 'r') as csvfile: with open(path, 'r') as csvfile:
@@ -250,7 +250,7 @@ def import_csv(context, path, only_insert=False, submit_after_import=False, igno
via_console=True) via_console=True)
frappe.db.commit() frappe.db.commit()
except Exception: except Exception:
print frappe.get_traceback()
print(frappe.get_traceback())


frappe.destroy() frappe.destroy()


@@ -364,7 +364,7 @@ def request(context, args):


frappe.handler.execute_cmd(frappe.form_dict.cmd) frappe.handler.execute_cmd(frappe.form_dict.cmd)


print frappe.response
print(frappe.response)
finally: finally:
frappe.destroy() frappe.destroy()


@@ -399,7 +399,7 @@ def get_version():
for m in sorted(frappe.get_all_apps()): for m in sorted(frappe.get_all_apps()):
module = frappe.get_module(m) module = frappe.get_module(m)
if hasattr(module, "__version__"): if hasattr(module, "__version__"):
print "{0} {1}".format(m, module.__version__)
print("{0} {1}".format(m, module.__version__))








+ 2
- 2
frappe/core/page/data_import_tool/data_import_tool.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe, os import frappe, os
from frappe import _ from frappe import _
@@ -29,7 +29,7 @@ def get_doctype_options():
def import_file_by_path(path, ignore_links=False, overwrite=False, submit=False, pre_process=None, no_email=True): def import_file_by_path(path, ignore_links=False, overwrite=False, submit=False, pre_process=None, no_email=True):
from frappe.utils.csvutils import read_csv_content from frappe.utils.csvutils import read_csv_content
from frappe.core.page.data_import_tool.importer import upload from frappe.core.page.data_import_tool.importer import upload
print "Importing " + path
print("Importing " + path)
with open(path, "r") as infile: with open(path, "r") as infile:
upload(rows = read_csv_content(infile.read()), ignore_links=ignore_links, no_email=no_email, overwrite=overwrite, upload(rows = read_csv_content(infile.read()), ignore_links=ignore_links, no_email=no_email, overwrite=overwrite,
submit_after_import=submit, pre_process=pre_process) submit_after_import=submit, pre_process=pre_process)


+ 2
- 2
frappe/core/page/data_import_tool/importer.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe, json import frappe, json
import frappe.permissions import frappe.permissions
@@ -210,7 +210,7 @@ def upload(rows = None, submit_after_import=None, ignore_encoding_errors=False,


def log(msg): def log(msg):
if via_console: if via_console:
print msg.encode('utf-8')
print(msg.encode('utf-8'))
else: else:
ret.append(msg) ret.append(msg)




+ 2
- 2
frappe/desk/tags.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import json import json
""" """
Server side functions for tagging. Server side functions for tagging.
@@ -84,7 +84,7 @@ class DocTags:
def remove(self, dn, tag): def remove(self, dn, tag):
"""remove a user tag""" """remove a user tag"""
tl = self.get_tags(dn).split(',') tl = self.get_tags(dn).split(',')
print tag, filter(lambda x:x!=tag, tl)
print(tag, filter(lambda x:x!=tag, tl))
self.update(dn, filter(lambda x:x.lower()!=tag.lower(), tl)) self.update(dn, filter(lambda x:x.lower()!=tag.lower(), tl))


def remove_all(self, dn): def remove_all(self, dn):


+ 2
- 2
frappe/email/doctype/email_account/email_account.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt # For license information, please see license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
import imaplib import imaplib
import re import re
@@ -644,7 +644,7 @@ def test_internet(host="8.8.8.8", port=53, timeout=3):
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port)) socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True return True
except Exception as ex: except Exception as ex:
print ex.message
print(ex.message)
return False return False


def notify_unreplied(): def notify_unreplied():


+ 5
- 4
frappe/frappeclient.py Wyświetl plik

@@ -1,3 +1,4 @@
from __future__ import print_function
import requests import requests
import json import json
import frappe import frappe
@@ -192,11 +193,11 @@ class FrappeClient(object):
meta = frappe.get_meta(doctype) meta = frappe.get_meta(doctype)
tables = {} tables = {}
for df in meta.get_table_fields(): for df in meta.get_table_fields():
if verbose: print "getting " + df.options
if verbose: print("getting " + df.options)
tables[df.fieldname] = self.get_list(df.options, limit_page_length=999999) tables[df.fieldname] = self.get_list(df.options, limit_page_length=999999)


# get links # get links
if verbose: print "getting " + doctype
if verbose: print("getting " + doctype)
docs = self.get_list(doctype, limit_page_length=999999, filters=filters) docs = self.get_list(doctype, limit_page_length=999999, filters=filters)


# build - attach children to parents # build - attach children to parents
@@ -210,7 +211,7 @@ class FrappeClient(object):
if child.parent in docs_map: if child.parent in docs_map:
docs_map[child.parent].setdefault(fieldname, []).append(child) docs_map[child.parent].setdefault(fieldname, []).append(child)


if verbose: print "inserting " + doctype
if verbose: print("inserting " + doctype)
for doc in docs: for doc in docs:
if exclude and doc["name"] in exclude: if exclude and doc["name"] in exclude:
continue continue
@@ -281,7 +282,7 @@ class FrappeClient(object):
try: try:
rjson = response.json() rjson = response.json()
except ValueError: except ValueError:
print response.text
print(response.text)
raise raise


if rjson and ("exc" in rjson) and rjson["exc"]: if rjson and ("exc" in rjson) and rjson["exc"]:


+ 17
- 17
frappe/installer.py Wyświetl plik

@@ -4,7 +4,7 @@
# called from wnf.py # called from wnf.py
# lib/wnf.py --install [rootpassword] [dbname] [source] # lib/wnf.py --install [rootpassword] [dbname] [source]


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import os, json, sys, subprocess, shutil import os, json, sys, subprocess, shutil
import frappe import frappe
@@ -40,8 +40,8 @@ def install_db(root_login="root", root_password=None, db_name=None, source_sql=N
check_if_ready_for_barracuda() check_if_ready_for_barracuda()
import_db_from_sql(source_sql, verbose) import_db_from_sql(source_sql, verbose)
if not 'tabDefaultValue' in frappe.db.get_tables(): if not 'tabDefaultValue' in frappe.db.get_tables():
print '''Database not installed, this can due to lack of permission, or that the database name exists.
Check your mysql root password, or use --force to reinstall'''
print('''Database not installed, this can due to lack of permission, or that the database name exists.
Check your mysql root password, or use --force to reinstall''')
sys.exit(1) sys.exit(1)


remove_missing_apps() remove_missing_apps()
@@ -63,14 +63,14 @@ def create_database_and_user(force, verbose):
raise Exception("Database %s already exists" % (db_name,)) raise Exception("Database %s already exists" % (db_name,))


dbman.create_user(db_name, frappe.conf.db_password) dbman.create_user(db_name, frappe.conf.db_password)
if verbose: print "Created user %s" % db_name
if verbose: print("Created user %s" % db_name)


dbman.create_database(db_name) dbman.create_database(db_name)
if verbose: print "Created database %s" % db_name
if verbose: print("Created database %s" % db_name)


dbman.grant_all_privileges(db_name, db_name) dbman.grant_all_privileges(db_name, db_name)
dbman.flush_privileges() dbman.flush_privileges()
if verbose: print "Granted privileges to user %s and database %s" % (db_name, db_name)
if verbose: print("Granted privileges to user %s and database %s" % (db_name, db_name))


# close root connection # close root connection
frappe.db.close() frappe.db.close()
@@ -84,12 +84,12 @@ def create_user_settings_table():
) ENGINE=InnoDB DEFAULT CHARSET=utf8""") ) ENGINE=InnoDB DEFAULT CHARSET=utf8""")


def import_db_from_sql(source_sql, verbose): def import_db_from_sql(source_sql, verbose):
if verbose: print "Starting database import..."
if verbose: print("Starting database import...")
db_name = frappe.conf.db_name db_name = frappe.conf.db_name
if not source_sql: if not source_sql:
source_sql = os.path.join(os.path.dirname(frappe.__file__), 'data', 'Framework.sql') source_sql = os.path.join(os.path.dirname(frappe.__file__), 'data', 'Framework.sql')
DbManager(frappe.local.db).restore_database(db_name, source_sql, db_name, frappe.conf.db_password) DbManager(frappe.local.db).restore_database(db_name, source_sql, db_name, frappe.conf.db_password)
if verbose: print "Imported from database %s" % source_sql
if verbose: print("Imported from database %s" % source_sql)


def get_root_connection(root_login='root', root_password=None): def get_root_connection(root_login='root', root_password=None):
if not frappe.local.flags.root_connection: if not frappe.local.flags.root_connection:
@@ -124,7 +124,7 @@ def install_app(name, verbose=False, set_as_patched=True):
frappe.msgprint("App {0} already installed".format(name)) frappe.msgprint("App {0} already installed".format(name))
return return


print "Installing {0}...".format(name)
print("Installing {0}...".format(name))


if name != "frappe": if name != "frappe":
frappe.only_for("System Manager") frappe.only_for("System Manager")
@@ -182,7 +182,7 @@ def remove_app(app_name, dry_run=False, yes=False):
return return


from frappe.utils.backups import scheduled_backup from frappe.utils.backups import scheduled_backup
print "Backing up..."
print("Backing up...")
scheduled_backup(ignore_files=True) scheduled_backup(ignore_files=True)


drop_doctypes = [] drop_doctypes = []
@@ -191,7 +191,7 @@ def remove_app(app_name, dry_run=False, yes=False):
for module_name in frappe.get_module_list(app_name): for module_name in frappe.get_module_list(app_name):
for doctype in frappe.get_list("DocType", filters={"module": module_name}, for doctype in frappe.get_list("DocType", filters={"module": module_name},
fields=["name", "issingle"]): fields=["name", "issingle"]):
print "removing DocType {0}...".format(doctype.name)
print("removing DocType {0}...".format(doctype.name))


if not dry_run: if not dry_run:
frappe.delete_doc("DocType", doctype.name) frappe.delete_doc("DocType", doctype.name)
@@ -202,11 +202,11 @@ def remove_app(app_name, dry_run=False, yes=False):
# remove reports, pages and web forms # remove reports, pages and web forms
for doctype in ("Report", "Page", "Web Form"): for doctype in ("Report", "Page", "Web Form"):
for record in frappe.get_list(doctype, filters={"module": module_name}): for record in frappe.get_list(doctype, filters={"module": module_name}):
print "removing {0} {1}...".format(doctype, record.name)
print("removing {0} {1}...".format(doctype, record.name))
if not dry_run: if not dry_run:
frappe.delete_doc(doctype, record.name) frappe.delete_doc(doctype, record.name)


print "removing Module {0}...".format(module_name)
print("removing Module {0}...".format(module_name))
if not dry_run: if not dry_run:
frappe.delete_doc("Module Def", module_name) frappe.delete_doc("Module Def", module_name)


@@ -369,10 +369,10 @@ def check_if_ready_for_barracuda():




def print_db_config(explanation, config_text): def print_db_config(explanation, config_text):
print ("="*80)
print (explanation)
print (config_text)
print ("="*80)
print("="*80)
print(explanation)
print(config_text)
print("="*80)




def extract_sql_gzip(sql_gz_path): def extract_sql_gzip(sql_gz_path):


+ 2
- 2
frappe/model/document.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
import time import time
import redis import redis
@@ -612,7 +612,7 @@ class Document(BaseDocument):
msgprint(msg) msgprint(msg)


if frappe.flags.print_messages: if frappe.flags.print_messages:
print self.as_json().encode("utf-8")
print(self.as_json().encode("utf-8"))


raise frappe.MandatoryError('[{doctype}, {name}]: {fields}'.format( raise frappe.MandatoryError('[{doctype}, {name}]: {fields}'.format(
fields=", ".join((each[0] for each in missing)), fields=", ".join((each[0] for each in missing)),


+ 2
- 2
frappe/model/meta.py Wyświetl plik

@@ -15,7 +15,7 @@ Example:


''' '''


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe, json, os import frappe, json, os
from frappe.utils import cstr, cint from frappe.utils import cstr, cint
from frappe.model import default_fields, no_value_fields, optional_fields from frappe.model import default_fields, no_value_fields, optional_fields
@@ -480,7 +480,7 @@ def trim_tables(doctype=None):
columns_to_remove = [f for f in list(set(columns) - set(fields)) if f not in ignore_fields columns_to_remove = [f for f in list(set(columns) - set(fields)) if f not in ignore_fields
and not f.startswith("_")] and not f.startswith("_")]
if columns_to_remove: if columns_to_remove:
print doctype, "columns removed:", columns_to_remove
print(doctype, "columns removed:", columns_to_remove)
columns_to_remove = ", ".join(["drop `{0}`".format(c) for c in columns_to_remove]) columns_to_remove = ", ".join(["drop `{0}`".format(c) for c in columns_to_remove])
query = """alter table `tab{doctype}` {columns}""".format( query = """alter table `tab{doctype}` {columns}""".format(
doctype=doctype, columns=columns_to_remove) doctype=doctype, columns=columns_to_remove)


+ 2
- 2
frappe/model/rename_doc.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
from frappe import _ from frappe import _
from frappe.utils import cint from frappe.utils import cint
@@ -374,7 +374,7 @@ def bulk_rename(doctype, rows=None, via_console = False):
frappe.db.rollback() frappe.db.rollback()


if via_console: if via_console:
print msg
print(msg)
else: else:
rename_log.append(msg) rename_log.append(msg)




+ 2
- 2
frappe/model/sync.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
""" """
Sync's doctype and docfields from txt files to database Sync's doctype and docfields from txt files to database
perms will get synced only if none exist perms will get synced only if none exist
@@ -50,7 +50,7 @@ def sync_for(app_name, force=0, sync_everything = False, verbose=False, reset_pe
# show progress bar # show progress bar
update_progress_bar("Updating DocTypes for {0}".format(app_name), i, l) update_progress_bar("Updating DocTypes for {0}".format(app_name), i, l)


print ""
print()




def get_doc_files(files, start_path, force=0, sync_everything = False, verbose=False): def get_doc_files(files, start_path, force=0, sync_everything = False, verbose=False):


+ 2
- 2
frappe/model/utils/__init__.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
from frappe.utils import cstr from frappe.utils import cstr
from frappe.build import html_to_js_template from frappe.build import html_to_js_template
@@ -29,7 +29,7 @@ def set_field_property(filters, key, value):
for d in docs: for d in docs:
d.get('fields', filters)[0].set(key, value) d.get('fields', filters)[0].set(key, value)
d.save() d.save()
print 'Updated {0}'.format(d.name)
print('Updated {0}'.format(d.name))


frappe.db.commit() frappe.db.commit()




+ 2
- 2
frappe/model/utils/rename_field.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import json import json
@@ -14,7 +14,7 @@ def rename_field(doctype, old_fieldname, new_fieldname):
meta = frappe.get_meta(doctype, cached=False) meta = frappe.get_meta(doctype, cached=False)
new_field = meta.get_field(new_fieldname) new_field = meta.get_field(new_fieldname)
if not new_field: if not new_field:
print "rename_field: " + (new_fieldname) + " not found in " + doctype
print("rename_field: " + (new_fieldname) + " not found in " + doctype)
return return


if new_field.fieldtype == "Table": if new_field.fieldtype == "Table":


+ 3
- 3
frappe/modules/import_file.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe, os, json import frappe, os, json
from frappe.modules import get_module_path, scrub_dt_dn from frappe.modules import get_module_path, scrub_dt_dn
@@ -38,7 +38,7 @@ def import_file_by_path(path, force=False, data_import=False, pre_process=None,
try: try:
docs = read_doc_from_file(path) docs = read_doc_from_file(path)
except IOError: except IOError:
print path + " missing"
print (path + " missing")
return return


if docs: if docs:
@@ -77,7 +77,7 @@ def read_doc_from_file(path):
try: try:
doc = json.loads(f.read()) doc = json.loads(f.read())
except ValueError: except ValueError:
print "bad json: {0}".format(path)
print("bad json: {0}".format(path))
raise raise
else: else:
raise IOError, '%s missing' % path raise IOError, '%s missing' % path


+ 2
- 2
frappe/modules/patch_handler.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
""" """
Execute Patch Files Execute Patch Files


@@ -125,4 +125,4 @@ def check_session_stopped():
raise frappe.SessionStopped('Session Stopped') raise frappe.SessionStopped('Session Stopped')


def log(msg): def log(msg):
print msg
print (msg)

+ 3
- 3
frappe/modules/utils.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
""" """
Utilities for using modules Utilities for using modules
""" """
@@ -121,7 +121,7 @@ def sync_customizations_for_doctype(data):
if data.get('custom_perms'): if data.get('custom_perms'):
sync('custom_perms', 'Custom DocPerm', 'parent') sync('custom_perms', 'Custom DocPerm', 'parent')


print 'Updating customizations for {0}'.format(doctype)
print('Updating customizations for {0}'.format(doctype))
validate_fields_for_doctype(doctype) validate_fields_for_doctype(doctype)


if update_schema and not frappe.db.get_value('DocType', doctype, 'issingle'): if update_schema and not frappe.db.get_value('DocType', doctype, 'issingle'):
@@ -154,7 +154,7 @@ def reload_doc(module, dt=None, dn=None, force=False, reset_permissions=False):
def export_doc(doctype, name, module=None): def export_doc(doctype, name, module=None):
"""Write a doc to standard path.""" """Write a doc to standard path."""
from frappe.modules.export_file import write_document_file from frappe.modules.export_file import write_document_file
print doctype, name
print(doctype, name)


if not module: module = frappe.db.get_value('DocType', name, 'module') if not module: module = frappe.db.get_value('DocType', name, 'module')
write_document_file(frappe.get_doc(doctype, name), module) write_document_file(frappe.get_doc(doctype, name), module)


+ 2
- 1
frappe/oauth.py Wyświetl plik

@@ -1,3 +1,4 @@
from __future__ import print_function
import frappe, urllib import frappe, urllib


from frappe import _ from frappe import _
@@ -155,7 +156,7 @@ class OAuthWebRequestValidator(RequestValidator):
try: try:
request.client = request.client or oc.as_dict() request.client = request.client or oc.as_dict()
except Exception, e: except Exception, 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"))




+ 2
- 2
frappe/patches/v4_0/create_custom_field_for_owner_match.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field from frappe.custom.doctype.custom_field.custom_field import create_custom_field


@@ -18,7 +18,7 @@ def create_custom_field_for_owner_match():
# a link field pointing to User already exists # a link field pointing to User already exists
if (frappe.db.get_value("DocField", {"parent": dt, "fieldtype": "Link", "options": "User", "default": "__user"}) if (frappe.db.get_value("DocField", {"parent": dt, "fieldtype": "Link", "options": "User", "default": "__user"})
or frappe.db.get_value("Custom Field", {"dt": dt, "fieldtype": "Link", "options": "User", "default": "__user"})): or frappe.db.get_value("Custom Field", {"dt": dt, "fieldtype": "Link", "options": "User", "default": "__user"})):
print "User link field already exists for", dt
print("User link field already exists for", dt)
continue continue


fieldname = "{}_owner".format(frappe.scrub(dt)) fieldname = "{}_owner".format(frappe.scrub(dt))


+ 5
- 5
frappe/patches/v4_1/file_manager_fix.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import os import os
@@ -37,7 +37,7 @@ def execute():
_file_name, content = get_file(name) _file_name, content = get_file(name)
b.content_hash = get_content_hash(content) b.content_hash = get_content_hash(content)
except IOError: except IOError:
print 'Warning: Error processing ', name
print('Warning: Error processing ', name)
b.content_hash = None b.content_hash = None
b.flags.ignore_duplicate_entry_error = True b.flags.ignore_duplicate_entry_error = True
b.save() b.save()
@@ -62,18 +62,18 @@ def rename_replacing_files():
f.write(('\n'.join(missing_files) + '\n').encode('utf-8')) f.write(('\n'.join(missing_files) + '\n').encode('utf-8'))


for file_name, file_datas in replaced_files: for file_name, file_datas in replaced_files:
print 'processing ' + file_name
print ('processing ' + file_name)
content_hash = frappe.db.get_value('File', file_datas[0], 'content_hash') content_hash = frappe.db.get_value('File', file_datas[0], 'content_hash')
if not content_hash: if not content_hash:
continue continue
new_file_name = get_file_name(file_name, content_hash) new_file_name = get_file_name(file_name, content_hash)
if os.path.exists(get_files_path(new_file_name)): if os.path.exists(get_files_path(new_file_name)):
continue continue
print 'skipping ' + file_name
print('skipping ' + file_name)
try: try:
os.rename(get_files_path(file_name), get_files_path(new_file_name)) os.rename(get_files_path(file_name), get_files_path(new_file_name))
except OSError: except OSError:
print 'Error renaming ', file_name
print('Error renaming ', file_name)
for name in file_datas: for name in file_datas:
f = frappe.get_doc('File', name) f = frappe.get_doc('File', name)
f.file_name = new_file_name f.file_name = new_file_name


+ 3
- 3
frappe/patches/v5_0/fix_text_editor_file_urls.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe
import re import re


@@ -36,10 +36,10 @@ def scrub_relative_urls(html):
return re.sub("""src[\s]*=[\s]*['"]files/([^'"]*)['"]""", 'src="/files/\g<1>"', html) return re.sub("""src[\s]*=[\s]*['"]files/([^'"]*)['"]""", 'src="/files/\g<1>"', html)
# return re.sub("""(src|href)[^\w'"]*['"](?!http|ftp|mailto|/|#|%|{|cid:|\.com/www\.)([^'" >]+)['"]""", '\g<1>="/\g<2>"', html) # return re.sub("""(src|href)[^\w'"]*['"](?!http|ftp|mailto|/|#|%|{|cid:|\.com/www\.)([^'" >]+)['"]""", '\g<1>="/\g<2>"', html)
except: except:
print "Error", html
print("Error", html)
raise raise


def print_diff(html, old_value): def print_diff(html, old_value):
import difflib import difflib
diff = difflib.unified_diff(old_value.splitlines(1), html.splitlines(1), lineterm='') diff = difflib.unified_diff(old_value.splitlines(1), html.splitlines(1), lineterm='')
print '\n'.join(list(diff))
print('\n'.join(list(diff)))

+ 2
- 1
frappe/patches/v6_1/rename_file_data.py Wyświetl plik

@@ -1,3 +1,4 @@
from __future__ import print_function
import frappe import frappe


def execute(): def execute():
@@ -21,7 +22,7 @@ def execute():
try: try:
file.save() file.save()
except: except:
print frappe.get_traceback()
print(frappe.get_traceback())
raise raise


from frappe.utils.nestedset import rebuild_tree from frappe.utils.nestedset import rebuild_tree


+ 4
- 2
frappe/patches/v6_4/reduce_varchar_length.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe


def execute(): def execute():
@@ -20,8 +20,10 @@ def execute():
max_length = max_length[0][0] if max_length else None max_length = max_length[0][0] if max_length else None


if max_length and 140 < max_length <= 255: if max_length and 140 < max_length <= 255:
print "setting length of '{fieldname}' in '{doctype}' as {length}".format(
print(
"setting length of '{fieldname}' in '{doctype}' as {length}".format(
fieldname=fieldname, doctype=doctype, length=max_length) fieldname=fieldname, doctype=doctype, length=max_length)
)


# create property setter for length # create property setter for length
frappe.make_property_setter({ frappe.make_property_setter({


+ 2
- 1
frappe/patches/v8_0/install_new_build_system_requirements.py Wyświetl plik

@@ -1,3 +1,4 @@
from __future__ import print_function
from subprocess import Popen, call, PIPE from subprocess import Popen, call, PIPE


def execute(): def execute():
@@ -7,7 +8,7 @@ def execute():
if output: if output:
call(['brew', 'upgrade', 'node']) call(['brew', 'upgrade', 'node'])
else: else:
print 'Please update your NodeJS version'
print('Please update your NodeJS version')


call([ call([
'npm', 'install', 'npm', 'install',


+ 13
- 13
frappe/permissions.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe, copy, json import frappe, copy, json
from frappe import _, msgprint from frappe import _, msgprint
from frappe.utils import cint from frappe.utils import cint
@@ -25,21 +25,21 @@ def has_permission(doctype, ptype="read", doc=None, verbose=False, user=None):
if not user: user = frappe.session.user if not user: user = frappe.session.user


if frappe.is_table(doctype): if frappe.is_table(doctype):
if verbose: print "Table type, always true"
if verbose: print("Table type, always true")
return True return True


meta = frappe.get_meta(doctype) meta = frappe.get_meta(doctype)


if ptype=="submit" and not cint(meta.is_submittable): if ptype=="submit" and not cint(meta.is_submittable):
if verbose: print "Not submittable"
if verbose: print("Not submittable")
return False return False


if ptype=="import" and not cint(meta.allow_import): if ptype=="import" and not cint(meta.allow_import):
if verbose: print "Not importable"
if verbose: print("Not importable")
return False return False


if user=="Administrator": if user=="Administrator":
if verbose: print "Administrator"
if verbose: print("Administrator")
return True return True


def false_if_not_shared(): def false_if_not_shared():
@@ -50,18 +50,18 @@ def has_permission(doctype, ptype="read", doc=None, verbose=False, user=None):
if doc: if doc:
doc_name = doc if isinstance(doc, basestring) else doc.name doc_name = doc if isinstance(doc, basestring) else doc.name
if doc_name in shared: if doc_name in shared:
if verbose: print "Shared"
if verbose: print("Shared")
if ptype in ("read", "write", "share") or meta.permissions[0].get(ptype): if ptype in ("read", "write", "share") or meta.permissions[0].get(ptype):
if verbose: print "Is shared"
if verbose: print("Is shared")
return True return True


elif shared: elif shared:
# if atleast one shared doc of that type, then return True # if atleast one shared doc of that type, then return True
# this is used in db_query to check if permission on DocType # this is used in db_query to check if permission on DocType
if verbose: print "Has a shared document"
if verbose: print("Has a shared document")
return True return True


if verbose: print "Not Shared"
if verbose: print("Not Shared")
return False return False


role_permissions = get_role_permissions(meta, user=user, verbose=verbose) role_permissions = get_role_permissions(meta, user=user, verbose=verbose)
@@ -79,19 +79,19 @@ def has_permission(doctype, ptype="read", doc=None, verbose=False, user=None):


if role_permissions["if_owner"].get(ptype) and ptype!="create": if role_permissions["if_owner"].get(ptype) and ptype!="create":
owner_perm = doc.owner == frappe.session.user owner_perm = doc.owner == frappe.session.user
if verbose: print "Owner permission: {0}".format(owner_perm)
if verbose: print("Owner permission: {0}".format(owner_perm))


# check if user permission # check if user permission
if not owner_perm and role_permissions["apply_user_permissions"].get(ptype): if not owner_perm and role_permissions["apply_user_permissions"].get(ptype):
user_perm = user_has_permission(doc, verbose=verbose, user=user, user_perm = user_has_permission(doc, verbose=verbose, user=user,
user_permission_doctypes=role_permissions.get("user_permission_doctypes", {}).get(ptype) or []) user_permission_doctypes=role_permissions.get("user_permission_doctypes", {}).get(ptype) or [])


if verbose: print "User permission: {0}".format(user_perm)
if verbose: print("User permission: {0}".format(user_perm))


if not owner_perm and not user_perm: if not owner_perm and not user_perm:
controller_perm = has_controller_permissions(doc, ptype, user=user) controller_perm = has_controller_permissions(doc, ptype, user=user)


if verbose: print "Controller permission: {0}".format(controller_perm)
if verbose: print("Controller permission: {0}".format(controller_perm))


# permission true if any one condition is explicitly True or all permissions are undefined (None) # permission true if any one condition is explicitly True or all permissions are undefined (None)
perm = any([owner_perm, user_perm, controller_perm]) or \ perm = any([owner_perm, user_perm, controller_perm]) or \
@@ -100,7 +100,7 @@ def has_permission(doctype, ptype="read", doc=None, verbose=False, user=None):
if not perm: if not perm:
perm = false_if_not_shared() perm = false_if_not_shared()


if verbose: print "Final Permission: {0}".format(perm)
if verbose: print("Final Permission: {0}".format(perm))


return perm return perm




+ 13
- 13
frappe/test_runner.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import unittest, json, sys import unittest, json, sys
@@ -48,7 +48,7 @@ def main(app=None, module=None, doctype=None, verbose=False, tests=(), force=Fal
set_test_email_config() set_test_email_config()


if verbose: if verbose:
print 'Running "before_tests" hooks'
print('Running "before_tests" hooks')
for fn in frappe.get_hooks("before_tests", app_name=app): for fn in frappe.get_hooks("before_tests", app_name=app):
frappe.get_attr(fn)() frappe.get_attr(fn)()


@@ -110,14 +110,14 @@ def run_all_tests(app=None, verbose=False, profile=False):
s = StringIO.StringIO() s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats() ps.print_stats()
print s.getvalue()
print(s.getvalue())


return out return out


def run_tests_for_doctype(doctype, verbose=False, tests=(), force=False, profile=False): def run_tests_for_doctype(doctype, verbose=False, tests=(), force=False, profile=False):
module = frappe.db.get_value("DocType", doctype, "module") module = frappe.db.get_value("DocType", doctype, "module")
if not module: if not module:
print 'Invalid doctype {0}'.format(doctype)
print('Invalid doctype {0}'.format(doctype))
sys.exit(1) sys.exit(1)


test_module = get_module_name(doctype, module, "test_") test_module = get_module_name(doctype, module, "test_")
@@ -158,7 +158,7 @@ def _run_unittest(module, verbose=False, tests=(), profile=False):
s = StringIO.StringIO() s = StringIO.StringIO()
ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps = pstats.Stats(pr, stream=s).sort_stats('cumulative')
ps.print_stats() ps.print_stats()
print s.getvalue()
print(s.getvalue())


return out return out


@@ -205,7 +205,7 @@ def make_test_records(doctype, verbose=0, force=False):


if not options in frappe.local.test_objects: if not options in frappe.local.test_objects:
if options in frappe.local.test_objects: if options in frappe.local.test_objects:
print "No test records or circular reference for {0}".format(options)
print("No test records or circular reference for {0}".format(options))
frappe.local.test_objects[options] = [] frappe.local.test_objects[options] = []
make_test_records(options, verbose, force) make_test_records(options, verbose, force)
make_test_records_for_doctype(options, verbose, force) make_test_records_for_doctype(options, verbose, force)
@@ -247,7 +247,7 @@ def make_test_records_for_doctype(doctype, verbose=0, force=False):
module, test_module = get_modules(doctype) module, test_module = get_modules(doctype)


if verbose: if verbose:
print "Making for " + doctype
print("Making for " + doctype)


if hasattr(test_module, "_make_test_records"): if hasattr(test_module, "_make_test_records"):
frappe.local.test_objects[doctype] += test_module._make_test_records(verbose) frappe.local.test_objects[doctype] += test_module._make_test_records(verbose)
@@ -317,11 +317,11 @@ def make_test_objects(doctype, test_records=None, verbose=None, reset=False):
return records return records


def print_mandatory_fields(doctype): def print_mandatory_fields(doctype):
print "Please setup make_test_records for: " + doctype
print "-" * 60
print("Please setup make_test_records for: " + doctype)
print("-" * 60)
meta = frappe.get_meta(doctype) meta = frappe.get_meta(doctype)
print "Autoname: " + (meta.autoname or "")
print "Mandatory Fields: "
print("Autoname: " + (meta.autoname or ""))
print("Mandatory Fields: ")
for d in meta.get("fields", {"reqd":1}): for d in meta.get("fields", {"reqd":1}):
print d.parent + ":" + d.fieldname + " | " + d.fieldtype + " | " + (d.options or "")
print
print(d.parent + ":" + d.fieldname + " | " + d.fieldtype + " | " + (d.options or ""))
print()

+ 4
- 4
frappe/translate.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


""" """
frappe.translate frappe.translate
@@ -584,7 +584,7 @@ def get_untranslated(lang, untranslated_file, get_all=False):
.replace("\n", "|||")) .replace("\n", "|||"))


if get_all: if get_all:
print str(len(messages)) + " messages"
print(str(len(messages)) + " messages")
with open(untranslated_file, "w") as f: with open(untranslated_file, "w") as f:
for m in messages: for m in messages:
# replace \n with ||| so that internal linebreaks don't get split # replace \n with ||| so that internal linebreaks don't get split
@@ -597,13 +597,13 @@ def get_untranslated(lang, untranslated_file, get_all=False):
untranslated.append(m[1]) untranslated.append(m[1])


if untranslated: if untranslated:
print str(len(untranslated)) + " missing translations of " + str(len(messages))
print(str(len(untranslated)) + " missing translations of " + str(len(messages)))
with open(untranslated_file, "w") as f: with open(untranslated_file, "w") as f:
for m in untranslated: for m in untranslated:
# replace \n with ||| so that internal linebreaks don't get split # replace \n with ||| so that internal linebreaks don't get split
f.write((escape_newlines(m) + os.linesep).encode("utf-8")) f.write((escape_newlines(m) + os.linesep).encode("utf-8"))
else: else:
print "all translated!"
print("all translated!")


def update_translations(lang, untranslated_file, translated_file): def update_translations(lang, untranslated_file, translated_file):
"""Update translations from a source and target file for a given language. """Update translations from a source and target file for a given language.


+ 8
- 8
frappe/utils/__init__.py Wyświetl plik

@@ -3,9 +3,9 @@


# util __init__.py # util __init__.py


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
from werkzeug.test import Client from werkzeug.test import Client
import os, re, urllib, sys, json, md5, requests, traceback
import os, re, urllib, sys, json, hashlib, requests, traceback
from markdown2 import markdown as _markdown from markdown2 import markdown as _markdown
from .html_utils import sanitize_html from .html_utils import sanitize_html


@@ -142,7 +142,7 @@ def has_gravatar(email):
# since querying gravatar for every item will be slow # since querying gravatar for every item will be slow
return '' return ''


hexdigest = md5.md5(frappe.as_unicode(email).encode('utf-8')).hexdigest()
hexdigest = hashlib.md5(frappe.as_unicode(email).encode('utf-8')).hexdigest()


gravatar_url = "https://secure.gravatar.com/avatar/{hash}?d=404&s=200".format(hash=hexdigest) gravatar_url = "https://secure.gravatar.com/avatar/{hash}?d=404&s=200".format(hash=hexdigest)
try: try:
@@ -155,7 +155,7 @@ def has_gravatar(email):
return '' return ''


def get_gravatar_url(email): def get_gravatar_url(email):
return "https://secure.gravatar.com/avatar/{hash}?d=mm&s=200".format(hash=md5.md5(email).hexdigest())
return "https://secure.gravatar.com/avatar/{hash}?d=mm&s=200".format(hash=hashlib.md5(email).hexdigest())


def get_gravatar(email): def get_gravatar(email):
gravatar_url = has_gravatar(email) gravatar_url = has_gravatar(email)
@@ -278,8 +278,8 @@ def execute_in_shell(cmd, verbose=0):
err = stderr.read() err = stderr.read()


if verbose: if verbose:
if err: print err
if out: print out
if err: print(err)
if out: print(out)


return err, out return err, out


@@ -421,10 +421,10 @@ def watch(path, handler=None, debug=True):
class Handler(FileSystemEventHandler): class Handler(FileSystemEventHandler):
def on_any_event(self, event): def on_any_event(self, event):
if debug: if debug:
print "File {0}: {1}".format(event.event_type, event.src_path)
print("File {0}: {1}".format(event.event_type, event.src_path))


if not handler: if not handler:
print "No handler specified"
print("No handler specified")
return return


handler(event.src_path, event.event_type) handler(event.src_path, event.event_type)


+ 2
- 2
frappe/utils/autodoc.py Wyświetl plik

@@ -8,7 +8,7 @@ frappe.utils.autodoc
Inspect elements of a given module and return its objects Inspect elements of a given module and return its objects
""" """


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import inspect, importlib, re, frappe import inspect, importlib, re, frappe
from frappe.model.document import get_controller from frappe.model.document import get_controller
@@ -49,7 +49,7 @@ def automodule(name):


installed = None installed = None
def get_version(name): def get_version(name):
print name
print(name)
global installed global installed


if not installed: if not installed:


+ 3
- 3
frappe/utils/background_jobs.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import redis import redis
from rq import Connection, Queue, Worker from rq import Connection, Queue, Worker
from frappe.utils import cstr from frappe.utils import cstr
@@ -135,7 +135,7 @@ def get_jobs(site=None, queue=None, key='method'):
jobs_per_site[site].append(job.kwargs[key]) jobs_per_site[site].append(job.kwargs[key])


else: else:
print 'No site found in job', job.__dict__
print('No site found in job', job.__dict__)


return jobs_per_site return jobs_per_site


@@ -181,5 +181,5 @@ def enqueue_test_job():


def test_job(s): def test_job(s):
import time import time
print 'sleeping...'
print('sleeping...')
time.sleep(s) time.sleep(s)

+ 5
- 5
frappe/utils/backups.py Wyświetl plik

@@ -3,7 +3,7 @@


"""This module handles the On Demand Backup utility""" """This module handles the On Demand Backup utility"""


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


#Imports #Imports
from frappe import _ from frappe import _
@@ -103,7 +103,7 @@ class BackupGenerator:
cmd_string = """tar -cf %s %s""" % (backup_path, files_path) cmd_string = """tar -cf %s %s""" % (backup_path, files_path)
err, out = frappe.utils.execute_in_shell(cmd_string) err, out = frappe.utils.execute_in_shell(cmd_string)


print 'Backed up files', os.path.abspath(backup_path)
print('Backed up files', os.path.abspath(backup_path))


def take_dump(self): def take_dump(self):
import frappe.utils import frappe.utils
@@ -198,13 +198,13 @@ def is_file_old(db_file_name, older_than=24):
file_datetime = datetime.fromtimestamp\ file_datetime = datetime.fromtimestamp\
(os.stat(db_file_name).st_ctime) (os.stat(db_file_name).st_ctime)
if datetime.today() - file_datetime >= timedelta(hours = older_than): if datetime.today() - file_datetime >= timedelta(hours = older_than):
if verbose: print "File is old"
if verbose: print("File is old")
return True return True
else: else:
if verbose: print "File is recent"
if verbose: print("File is recent")
return False return False
else: else:
if verbose: print "File does not exist"
if verbose: print("File does not exist")
return True return True


def get_backup_path(): def get_backup_path():


+ 3
- 3
frappe/utils/bench_helper.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import click import click
import frappe import frappe
import os import os
@@ -66,11 +66,11 @@ def get_app_commands(app):


@click.command('get-frappe-commands') @click.command('get-frappe-commands')
def get_frappe_commands(): def get_frappe_commands():
print json.dumps(get_app_commands('frappe').keys())
print(json.dumps(get_app_commands('frappe').keys()))


@click.command('get-frappe-help') @click.command('get-frappe-help')
def get_frappe_help(): def get_frappe_help():
print click.Context(get_app_group('frappe')).get_help()
print(click.Context(get_app_group('frappe')).get_help())


def get_apps(): def get_apps():
return frappe.get_all_apps(with_internal_apps=False, sites_path='.') return frappe.get_all_apps(with_internal_apps=False, sites_path='.')


+ 5
- 5
frappe/utils/boilerplate.py Wyświetl plik

@@ -1,14 +1,14 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe, os, re import frappe, os, re
from frappe.utils import touch_file, encode, cstr from frappe.utils import touch_file, encode, cstr


def make_boilerplate(dest, app_name): def make_boilerplate(dest, app_name):
if not os.path.exists(dest): if not os.path.exists(dest):
print "Destination directory does not exist"
print("Destination directory does not exist")
return return


# app_name should be in snake_case # app_name should be in snake_case
@@ -38,10 +38,10 @@ def make_boilerplate(dest, app_name):
hook_val = defaults[hook_key] hook_val = defaults[hook_key]


if hook_key=="app_name" and hook_val.lower().replace(" ", "_") != hook_val: if hook_key=="app_name" and hook_val.lower().replace(" ", "_") != hook_val:
print "App Name must be all lowercase and without spaces"
print("App Name must be all lowercase and without spaces")
hook_val = "" hook_val = ""
elif hook_key=="app_title" and not re.match("^(?![\W])[^\d_\s][\w -]+$", hook_val, re.UNICODE): elif hook_key=="app_title" and not re.match("^(?![\W])[^\d_\s][\w -]+$", hook_val, re.UNICODE):
print "App Title should start with a letter and it can only consist of letters, numbers, spaces and underscores"
print("App Title should start with a letter and it can only consist of letters, numbers, spaces and underscores")
hook_val = "" hook_val = ""


hooks[hook_key] = hook_val hooks[hook_key] = hook_val
@@ -96,7 +96,7 @@ def make_boilerplate(dest, app_name):
with open(os.path.join(dest, hooks.app_name, hooks.app_name, "config", "docs.py"), "w") as f: with open(os.path.join(dest, hooks.app_name, hooks.app_name, "config", "docs.py"), "w") as f:
f.write(encode(docs_template.format(**hooks))) f.write(encode(docs_template.format(**hooks)))


print "'{app}' created at {path}".format(app=app_name, path=os.path.join(dest, app_name))
print("'{app}' created at {path}".format(app=app_name, path=os.path.join(dest, app_name)))




manifest_template = """include MANIFEST.in manifest_template = """include MANIFEST.in


+ 13
- 13
frappe/utils/doctor.py Wyświetl plik

@@ -1,4 +1,4 @@
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe.utils import frappe.utils
from collections import defaultdict from collections import defaultdict
from rq import Worker, Connection from rq import Worker, Connection
@@ -97,7 +97,7 @@ def doctor(site=None):
workers_online = check_number_of_workers() workers_online = check_number_of_workers()
jobs_per_queue, job_count = get_jobs_by_queue(site) jobs_per_queue, job_count = get_jobs_by_queue(site)


print "-----Checking scheduler status-----"
print("-----Checking scheduler status-----")
if site: if site:
sites = [site] sites = [site]
else: else:
@@ -107,28 +107,28 @@ def doctor(site=None):
frappe.init(s) frappe.init(s)
frappe.connect() frappe.connect()
if is_scheduler_disabled(): if is_scheduler_disabled():
print "Scheduler disabled for", s
print("Scheduler disabled for", s)
frappe.destroy() frappe.destroy()


# TODO improve this # TODO improve this
print "Workers online:", workers_online
print "-----{0} Jobs-----".format(site)
print("Workers online:", workers_online)
print("-----{0} Jobs-----".format(site))
for queue in get_queue_list(): for queue in get_queue_list():
if jobs_per_queue[queue]: if jobs_per_queue[queue]:
print "Queue:", queue
print "Number of Jobs: ", job_count[queue]
print "Methods:"
print("Queue:", queue)
print("Number of Jobs: ", job_count[queue])
print("Methods:")
for method, count in jobs_per_queue[queue].iteritems(): for method, count in jobs_per_queue[queue].iteritems():
print "{0} : {1}".format(method, count)
print "------------"
print("{0} : {1}".format(method, count))
print("------------")


return True return True


def pending_jobs(site=None): def pending_jobs(site=None):
print "-----Pending Jobs-----"
print("-----Pending Jobs-----")
pending_jobs = get_pending_jobs(site) pending_jobs = get_pending_jobs(site)
for queue in get_queue_list(): for queue in get_queue_list():
if(pending_jobs[queue]): if(pending_jobs[queue]):
print "-----Queue :{0}-----".format(queue)
print "\n".join(pending_jobs[queue])
print("-----Queue :{0}-----".format(queue))
print("\n".join(pending_jobs[queue]))



+ 2
- 2
frappe/utils/fixtures.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe, os import frappe, os
from frappe.core.page.data_import_tool.data_import_tool import import_doc, export_json from frappe.core.page.data_import_tool.data_import_tool import import_doc, export_json
@@ -60,7 +60,7 @@ def export_fixtures():
filters = fixture.get("filters") filters = fixture.get("filters")
or_filters = fixture.get("or_filters") or_filters = fixture.get("or_filters")
fixture = fixture.get("doctype") or fixture.get("dt") fixture = fixture.get("doctype") or fixture.get("dt")
print "Exporting {0} app {1} filters {2}".format(fixture, app, (filters if filters else or_filters))
print("Exporting {0} app {1} filters {2}".format(fixture, app, (filters if filters else or_filters)))
if not os.path.exists(frappe.get_app_path(app, "fixtures")): if not os.path.exists(frappe.get_app_path(app, "fixtures")):
os.mkdir(frappe.get_app_path(app, "fixtures")) os.mkdir(frappe.get_app_path(app, "fixtures"))




+ 3
- 3
frappe/utils/help.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt # License: GNU General Public License v3. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import hashlib import hashlib
@@ -16,7 +16,7 @@ import jinja2.exceptions


def sync(): def sync():
# make table # make table
print 'Syncing help database...'
print('Syncing help database...')
help_db = HelpDatabase() help_db = HelpDatabase()
help_db.make_database() help_db.make_database()
help_db.connect() help_db.connect()
@@ -131,7 +131,7 @@ class HelpDatabase(object):
self.db.sql('''insert into help(path, content, title, intro, full_path) self.db.sql('''insert into help(path, content, title, intro, full_path)
values (%s, %s, %s, %s, %s)''', (relpath, content, title, intro, fpath)) values (%s, %s, %s, %s, %s)''', (relpath, content, title, intro, fpath))
except jinja2.exceptions.TemplateSyntaxError: except jinja2.exceptions.TemplateSyntaxError:
print "Invalid Jinja Template for {0}. Skipping".format(fpath)
print("Invalid Jinja Template for {0}. Skipping".format(fpath))


doc_contents += "</ol>" doc_contents += "</ol>"
self.db.sql('''insert into help(path, content, title, intro, full_path) values (%s, %s, %s, %s, %s)''', self.db.sql('''insert into help(path, content, title, intro, full_path) values (%s, %s, %s, %s, %s)''',


+ 2
- 2
frappe/utils/image.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import os import os


def resize_images(path, maxdim=700): def resize_images(path, maxdim=700):
@@ -16,4 +16,4 @@ def resize_images(path, maxdim=700):
im.thumbnail(size, Image.ANTIALIAS) im.thumbnail(size, Image.ANTIALIAS)
im.save(os.path.join(basepath, fname)) im.save(os.path.join(basepath, fname))


print "resized {0}".format(os.path.join(basepath, fname))
print("resized {0}".format(os.path.join(basepath, fname)))

+ 2
- 2
frappe/utils/install.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import getpass import getpass
@@ -78,7 +78,7 @@ def get_admin_password():
admin_password = getpass.getpass("Set Administrator password: ") admin_password = getpass.getpass("Set Administrator password: ")
admin_password2 = getpass.getpass("Re-enter Administrator password: ") admin_password2 = getpass.getpass("Re-enter Administrator password: ")
if not admin_password == admin_password2: if not admin_password == admin_password2:
print "\nPasswords do not match"
print("\nPasswords do not match")
return ask_admin_password() return ask_admin_password()
return admin_password return admin_password




+ 2
- 2
frappe/utils/scheduler.py Wyświetl plik

@@ -8,7 +8,7 @@ Events:
weekly weekly
""" """


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import frappe import frappe
import json import json
@@ -48,7 +48,7 @@ def enqueue_events_for_all_sites():
enqueue_events_for_site(site=site, queued_jobs=jobs_per_site[site]) enqueue_events_for_site(site=site, queued_jobs=jobs_per_site[site])
except: except:
# it should try to enqueue other sites # it should try to enqueue other sites
print frappe.get_traceback()
print(frappe.get_traceback())


def enqueue_events_for_site(site, queued_jobs): def enqueue_events_for_site(site, queued_jobs):
try: try:


+ 2
- 2
frappe/utils/sel.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.keys import Keys
from selenium import webdriver from selenium import webdriver
@@ -47,7 +47,7 @@ def start_test_server(verbose):
while not pipe.stderr.readline(): while not pipe.stderr.readline():
time.sleep(0.5) time.sleep(0.5)
if verbose: if verbose:
print "Test server started"
print("Test server started")


def get(url): def get(url):
_driver.get(url) _driver.get(url)


+ 10
- 10
frappe/utils/setup_docs.py Wyświetl plik

@@ -5,7 +5,7 @@ Call from command line:
bench setup-docs app path bench setup-docs app path


""" """
from __future__ import unicode_literals
from __future__ import unicode_literals, print_function


import os, json, frappe, shutil, re import os, json, frappe, shutil, re
from frappe.website.context import get_context from frappe.website.context import get_context
@@ -65,7 +65,7 @@ class setup_docs(object):
self.app_title = self.hooks.get("app_title")[0] self.app_title = self.hooks.get("app_title")[0]
self.app_path = frappe.get_app_path(self.app) self.app_path = frappe.get_app_path(self.app)


print "Deleting current..."
print("Deleting current...")
shutil.rmtree(self.path, ignore_errors = True) shutil.rmtree(self.path, ignore_errors = True)
os.makedirs(self.path) os.makedirs(self.path)


@@ -208,7 +208,7 @@ class setup_docs(object):
self.make_folder(basepath) self.make_folder(basepath)


if not os.path.exists(module_doc_path): if not os.path.exists(module_doc_path):
print "Writing " + module_doc_path
print("Writing " + module_doc_path)
with open(module_doc_path, "w") as f: with open(module_doc_path, "w") as f:
context = {"name": self.app + "." + module_name} context = {"name": self.app + "." + module_name}
context.update(self.app_context) context.update(self.app_context)
@@ -226,7 +226,7 @@ class setup_docs(object):
os.makedirs(path) os.makedirs(path)


index_txt_path = os.path.join(path, "index.txt") index_txt_path = os.path.join(path, "index.txt")
print "Writing " + index_txt_path
print("Writing " + index_txt_path)
with open(index_txt_path, "w") as f: with open(index_txt_path, "w") as f:
f.write("") f.write("")


@@ -239,7 +239,7 @@ class setup_docs(object):
"title": name "title": name
} }
context.update(self.app_context) context.update(self.app_context)
print "Writing " + index_html_path
print("Writing " + index_html_path)
with open(index_html_path, "w") as f: with open(index_html_path, "w") as f:
f.write(frappe.render_template(template, context)) f.write(frappe.render_template(template, context))


@@ -255,7 +255,7 @@ class setup_docs(object):
index_parts = filter(None, f.read().splitlines()) index_parts = filter(None, f.read().splitlines())


if not set(pages).issubset(set(index_parts)): if not set(pages).issubset(set(index_parts)):
print "Updating " + index_txt_path
print("Updating " + index_txt_path)
with open(index_txt_path, "w") as f: with open(index_txt_path, "w") as f:
f.write("\n".join(pages)) f.write("\n".join(pages))


@@ -268,7 +268,7 @@ class setup_docs(object):
with open(model_json_path, "r") as j: with open(model_json_path, "r") as j:
doctype_real_name = json.loads(j.read()).get("name") doctype_real_name = json.loads(j.read()).get("name")


print "Writing " + model_path
print("Writing " + model_path)


with open(model_path, "w") as f: with open(model_path, "w") as f:
context = {"doctype": doctype_real_name} context = {"doctype": doctype_real_name}
@@ -295,7 +295,7 @@ class setup_docs(object):


cnt = 0 cnt = 0
for path, context in pages.iteritems(): for path, context in pages.iteritems():
print "Writing {0}".format(path)
print("Writing {0}".format(path))


# set this for get_context / website libs # set this for get_context / website libs
frappe.local.path = path frappe.local.path = path
@@ -371,13 +371,13 @@ class setup_docs(object):


cnt += 1 cnt += 1


print "Wrote {0} files".format(cnt)
print("Wrote {0} files".format(cnt))




def copy_assets(self): def copy_assets(self):
"""Copy jquery, bootstrap and other assets to files""" """Copy jquery, bootstrap and other assets to files"""


print "Copying assets..."
print("Copying assets...")
assets_path = os.path.join(self.target, "assets") assets_path = os.path.join(self.target, "assets")


# copy assets from docs # copy assets from docs


+ 4
- 4
frappe/website/doctype/web_page/web_page.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe, re import frappe, re
import requests, requests.exceptions import requests, requests.exceptions
from frappe.utils import strip_html from frappe.utils import strip_html
@@ -136,14 +136,14 @@ def check_broken_links():
res = frappe._dict({"status_code": "Connection Error"}) res = frappe._dict({"status_code": "Connection Error"})


if res.status_code!=200: if res.status_code!=200:
print "[{0}] {1}: {2}".format(res.status_code, p.name, link)
print("[{0}] {1}: {2}".format(res.status_code, p.name, link))
cnt += 1 cnt += 1
else: else:
link = link[1:] # remove leading / link = link[1:] # remove leading /
link = link.split("#")[0] link = link.split("#")[0]


if not resolve_route(link): if not resolve_route(link):
print p.name + ":" + link
print(p.name + ":" + link)
cnt += 1 cnt += 1


print "{0} links broken".format(cnt)
print("{0} links broken".format(cnt))

+ 2
- 2
frappe/www/error.py Wyświetl plik

@@ -1,7 +1,7 @@
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt # MIT License. See license.txt


from __future__ import unicode_literals
from __future__ import unicode_literals, print_function
import frappe import frappe


no_cache = 1 no_cache = 1
@@ -9,5 +9,5 @@ no_sitemap = 1


def get_context(context): def get_context(context):
if frappe.flags.in_migrate: return if frappe.flags.in_migrate: return
print frappe.get_traceback().encode("utf-8")
print(frappe.get_traceback().encode("utf-8"))
return {"error": frappe.get_traceback().replace("<", "&lt;").replace(">", "&gt;") } return {"error": frappe.get_traceback().replace("<", "&lt;").replace(">", "&gt;") }

Ładowanie…
Anuluj
Zapisz