Skip to content

Commit

Permalink
Modernize Python 2 code to get ready for Python 3
Browse files Browse the repository at this point in the history
  • Loading branch information
cclauss committed Oct 4, 2017
1 parent 8af028b commit 01e85f2
Show file tree
Hide file tree
Showing 25 changed files with 106 additions and 91 deletions.
9 changes: 5 additions & 4 deletions bin/release_manager.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
import sys
import json
Expand Down Expand Up @@ -95,7 +96,7 @@ def get_changelog(commit_sha):
try:
pull_request = re.match("Merge pull request #(\d+)", subject).groups()[0]
pull_request = " #{}".format(pull_request)
except Exception, ex:
except Exception as ex:
pull_request = ""

author = subprocess.check_output(['git', 'log', '-1', '--pretty=format:"%an"', parents.split(' ')[-1]])[1:-1]
Expand Down Expand Up @@ -124,7 +125,7 @@ def update_release(version, build_filepath, commit_sha):
else:
release = create_release(version, commit_sha)

print "Using release id: {}".format(release['id'])
print("Using release id: {}".format(release['id']))

remove_previous_builds(release)
response = upload_asset(release, build_filepath)
Expand All @@ -135,8 +136,8 @@ def update_release(version, build_filepath, commit_sha):
if response.status_code != 200:
raise exception_from_error("Failed updating release description", response)

except Exception, ex:
print ex
except Exception as ex:
print(ex)

if __name__ == '__main__':
commit_sha = sys.argv[1]
Expand Down
7 changes: 4 additions & 3 deletions migrations/0001_warning.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
from __future__ import print_function
# This is here just to print a warning for users who use the old Fabric upgrade script.

if __name__ == '__main__':
warning = "You're using an outdated upgrade script that is running migrations the wrong way. Please upgrade to " \
"newer version of the script before continuning the upgrade process."
print "*" * 20
print warning
print "*" * 20
print("*" * 20)
print(warning)
print("*" * 20)
exit(1)
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Create Date: 2016-12-07 18:08:13.395586
"""
from __future__ import print_function
from alembic import op
import sqlalchemy as sa

Expand All @@ -26,8 +27,8 @@ def upgrade():
except ProgrammingError as e:
# The columns might exist if you ran the old migrations.
if 'column "is_draft" of relation "queries" already exists' in e.message:
print "Can't run this migration as you already have is_draft columns, please run:"
print "./manage.py db stamp {} # you might need to alter the command to match your environment.".format(revision)
print("Can't run this migration as you already have is_draft columns, please run:")
print("./manage.py db stamp {} # you might need to alter the command to match your environment.".format(revision))
exit()


Expand Down
9 changes: 5 additions & 4 deletions old_migrations/0003_update_data_source_config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import json
import jsonschema
from jsonschema import ValidationError
Expand All @@ -23,10 +24,10 @@ def validate_configuration(query_runner_type, configuration_json):
return True

def update(data_source):
print "[%s] Old options: %s" % (data_source.name, data_source.options)
print("[%s] Old options: %s" % (data_source.name, data_source.options))

if validate_configuration(data_source.type, data_source.options):
print "[%s] configuration already valid. skipping." % data_source.name
print("[%s] configuration already valid. skipping." % data_source.name)
return

if data_source.type == 'pg':
Expand Down Expand Up @@ -80,9 +81,9 @@ def update(data_source):
data_source.type = 'mongodb'

else:
print "[%s] No need to convert type of: %s" % (data_source.name, data_source.type)
print("[%s] No need to convert type of: %s" % (data_source.name, data_source.type))

print "[%s] New options: %s" % (data_source.name, data_source.options)
print("[%s] New options: %s" % (data_source.name, data_source.options))
data_source.save(only=data_source.dirty_fields)


Expand Down
5 changes: 3 additions & 2 deletions old_migrations/0013_update_counter_options.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from __future__ import print_function
import json
from redash import models

if __name__ == '__main__':
for vis in models.Visualization.select():
if vis.type == 'COUNTER':
options = json.loads(vis.options)
print "Before: ", options
print("Before: ", options)
if 'rowNumber' in options and options['rowNumber'] is not None:
options['rowNumber'] += 1
else:
Expand All @@ -18,6 +19,6 @@
options['targetColName'] = 'target'
options['targetRowNumber'] = options['rowNumber']

print "After: ", options
print("After: ", options)
vis.options = json.dumps(options)
vis.save()
3 changes: 2 additions & 1 deletion old_migrations/0014_add_alert_rearm_seconds.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import peewee
from playhouse.migrate import PostgresqlMigrator, migrate

Expand All @@ -10,7 +11,7 @@

cursor = db.database.execute_sql("SELECT column_name FROM information_schema.columns WHERE table_name='alerts' and column_name='rearm';")
if cursor.rowcount > 0:
print "Column exists. Skipping."
print("Column exists. Skipping.")
exit()

with db.database.transaction():
Expand Down
3 changes: 2 additions & 1 deletion old_migrations/0023_add_notification_destination.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import os
import peewee
from redash.models import db, NotificationDestination, AlertSubscription, Alert, Organization, User
Expand Down Expand Up @@ -29,7 +30,7 @@
org = Organization.get_by_slug('default')
user = User.select().where(User.org==org, peewee.SQL("%s = ANY(groups)", org.admin_group.id)).get()
except Exception:
print "!!! Warning: failed finding default organization or admin user, won't migrate Webhook/HipChat alert subscriptions."
print("!!! Warning: failed finding default organization or admin user, won't migrate Webhook/HipChat alert subscriptions.")
exit()

if WEBHOOK_ENDPOINT:
Expand Down
5 changes: 3 additions & 2 deletions old_migrations/0026_add_access_control_tables.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from redash.models import db, Change, AccessPermission, Query, Dashboard
from playhouse.migrate import PostgresqlMigrator, migrate

Expand All @@ -17,6 +18,6 @@
migrator.add_column('dashboards', 'version', Dashboard.version)
)
except Exception as ex:
print "Error while adding version column to queries/dashboards. Maybe it already exists?"
print ex
print("Error while adding version column to queries/dashboards. Maybe it already exists?")
print(ex)

7 changes: 4 additions & 3 deletions redash/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
import json


Expand Down Expand Up @@ -38,19 +39,19 @@ def manager():
@manager.command()
def version():
"""Displays Redash version."""
print __version__
print(__version__)


@manager.command()
def status():
print json.dumps(get_status(), indent=2)
print(json.dumps(get_status(), indent=2))


@manager.command()
def check_settings():
"""Show the settings as Redash sees them (useful for debugging)."""
for name, item in settings.all_settings().iteritems():
print "{} = {}".format(name, item)
print("{} = {}".format(name, item))


@manager.command()
Expand Down
41 changes: 21 additions & 20 deletions redash/cli/data_sources.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from sys import exit
import json

Expand Down Expand Up @@ -27,17 +28,17 @@ def list(organization=None):
data_sources = models.DataSource.query
for i, ds in enumerate(data_sources):
if i > 0:
print "-" * 20
print("-" * 20)

print "Id: {}\nName: {}\nType: {}\nOptions: {}".format(
ds.id, ds.name, ds.type, ds.options.to_json())
print("Id: {}\nName: {}\nType: {}\nOptions: {}".format(
ds.id, ds.name, ds.type, ds.options.to_json()))


def validate_data_source_type(type):
if type not in query_runners.keys():
print ("Error: the type \"{}\" is not supported (supported types: {})."
.format(type, ", ".join(query_runners.keys())))
print "OJNK"
print("OJNK")
exit(1)


Expand All @@ -53,17 +54,17 @@ def test(name, organization='default'):
data_source = models.DataSource.query.filter(
models.DataSource.name == name,
models.DataSource.org == org).one()
print "Testing connection to data source: {} (id={})".format(
name, data_source.id)
print("Testing connection to data source: {} (id={})".format(
name, data_source.id))
try:
data_source.query_runner.test_connection()
except Exception, e:
print "Failure: {}".format(e)
except Exception as e:
print("Failure: {}".format(e))
exit(1)
else:
print "Success"
print("Success")
except NoResultFound:
print "Couldn't find data source named: {}".format(name)
print("Couldn't find data source named: {}".format(name))
exit(1)


Expand All @@ -83,9 +84,9 @@ def new(name=None, type=None, options=None, organization='default'):
name = click.prompt("Name")

if type is None:
print "Select type:"
print("Select type:")
for i, query_runner_name in enumerate(query_runners.keys()):
print "{}. {}".format(i + 1, query_runner_name)
print("{}. {}".format(i + 1, query_runner_name))

idx = 0
while idx < 1 or idx > len(query_runners.keys()):
Expand Down Expand Up @@ -130,17 +131,17 @@ def new(name=None, type=None, options=None, organization='default'):
options = ConfigurationContainer(json.loads(options), schema)

if not options.is_valid():
print "Error: invalid configuration."
print("Error: invalid configuration.")
exit()

print "Creating {} data source ({}) with options:\n{}".format(
type, name, options.to_json())
print("Creating {} data source ({}) with options:\n{}".format(
type, name, options.to_json()))

data_source = models.DataSource.create_with_group(
name=name, type=type, options=options,
org=models.Organization.get_by_slug(organization))
models.db.session.commit()
print "Id: {}".format(data_source.id)
print("Id: {}".format(data_source.id))


@manager.command()
Expand All @@ -155,18 +156,18 @@ def delete(name, organization='default'):
data_source = models.DataSource.query.filter(
models.DataSource.name == name,
models.DataSource.org == org).one()
print "Deleting data source: {} (id={})".format(name, data_source.id)
print("Deleting data source: {} (id={})".format(name, data_source.id))
models.db.session.delete(data_source)
models.db.session.commit()
except NoResultFound:
print "Couldn't find data source named: {}".format(name)
print("Couldn't find data source named: {}".format(name))
exit(1)


def update_attr(obj, attr, new_value):
if new_value is not None:
old_value = getattr(obj, attr)
print "Updating {}: {} -> {}".format(attr, old_value, new_value)
print("Updating {}: {} -> {}".format(attr, old_value, new_value))
setattr(obj, attr, new_value)


Expand Down Expand Up @@ -204,4 +205,4 @@ def edit(name, new_name=None, options=None, type=None, organization='default'):
models.db.session.commit()

except NoResultFound:
print "Couldn't find data source named: {}".format(name)
print("Couldn't find data source named: {}".format(name))
27 changes: 14 additions & 13 deletions redash/cli/groups.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from __future__ import print_function
from sys import exit

from sqlalchemy.orm.exc import NoResultFound
Expand All @@ -21,21 +22,21 @@
" 'schedule_query', 'list_dashboards', 'list_alerts',"
" 'list_data_sources') (leave blank for default).")
def create(name, permissions=None, organization='default'):
print "Creating group (%s)..." % (name)
print("Creating group (%s)..." % (name))

org = models.Organization.get_by_slug(organization)

permissions = extract_permissions_string(permissions)

print "permissions: [%s]" % ",".join(permissions)
print("permissions: [%s]" % ",".join(permissions))

try:
models.db.session.add(models.Group(
name=name, org=org,
permissions=permissions))
models.db.session.commit()
except Exception, e:
print "Failed create group: %s" % e.message
except Exception as e:
print("Failed create group: %s" % e.message)
exit(1)


Expand All @@ -48,25 +49,25 @@ def create(name, permissions=None, organization='default'):
" 'schedule_query', 'list_dashboards', 'list_alerts',"
" 'list_data_sources') (leave blank for default).")
def change_permissions(group_id, permissions=None):
print "Change permissions of group %s ..." % group_id
print("Change permissions of group %s ..." % group_id)

try:
group = models.Group.query.get(group_id)
except NoResultFound:
print "User [%s] not found." % group_id
print("User [%s] not found." % group_id)
exit(1)

permissions = extract_permissions_string(permissions)
print "current permissions [%s] will be modify to [%s]" % (
",".join(group.permissions), ",".join(permissions))
print("current permissions [%s] will be modify to [%s]" % (
",".join(group.permissions), ",".join(permissions)))

group.permissions = permissions

try:
models.db.session.add(group)
models.db.session.commit()
except Exception, e:
print "Failed change permission: %s" % e.message
except Exception as e:
print("Failed change permission: %s" % e.message)
exit(1)


Expand All @@ -92,7 +93,7 @@ def list(organization=None):

for i, group in enumerate(groups):
if i > 0:
print "-" * 20
print("-" * 20)

print "Id: {}\nName: {}\nType: {}\nOrganization: {}".format(
group.id, group.name, group.type, group.org.slug)
print("Id: {}\nName: {}\nType: {}\nOrganization: {}".format(
group.id, group.name, group.type, group.org.slug))
Loading

0 comments on commit 01e85f2

Please sign in to comment.