some py3 friendly syntax changes (#8372)

This commit is contained in:
Andrew Williamson 2018-05-30 11:29:13 +01:00 коммит произвёл GitHub
Родитель a77b94a1f7
Коммит b457a5cece
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
59 изменённых файлов: 135 добавлений и 138 удалений

Просмотреть файл

@ -55,7 +55,7 @@ def main():
'eg. ./locale/generate_category_po_files.py')
return
print 'Loading translations JSON dump...'
print('Loading translations JSON dump...')
all_translations = json.load(open('./locale/category_translations.json'))
for locale in os.listdir('./locale/'):
@ -66,18 +66,18 @@ def main():
fname = os.path.join(directory, 'LC_MESSAGES', 'django.po')
if not os.path.exists(fname):
print "Skipping %s since it doesn't contain a django.po file"
print("Skipping %s since it doesn't contain a django.po file")
continue
translations_for_this_locale = extract_translations_for_given_locale(
all_translations, locale)
if not translations_for_this_locale:
print 'Skipping locale %s, it has no translations :(' % locale
print('Skipping locale %s, it has no translations :(' % locale)
continue
print "Writing %d translations to %s" % (
len(translations_for_this_locale), fname)
print("Writing %d translations to %s" % (
len(translations_for_this_locale), fname))
write_po(fname, translations_for_this_locale)

Просмотреть файл

@ -36,7 +36,7 @@ def main():
# Needs to stay below the opts.user injection.
ctx['python'] = opts.python
print TEMPLATE % ctx
print(TEMPLATE % ctx)
if __name__ == "__main__":

Просмотреть файл

@ -82,6 +82,6 @@ def main(requirements_path):
if __name__ == '__main__':
if len(sys.argv) < 2:
print 'Usage: %s <requirement-file>' % sys.argv[0]
print('Usage: %s <requirement-file>' % sys.argv[0])
sys.exit(1)
main(sys.argv[1])

Просмотреть файл

@ -45,7 +45,7 @@ class ThemeUpdate(object):
try:
with open(path, 'r') as f:
return base64.b64encode(f.read())
except IOError, e:
except IOError as e:
if len(e.args) == 1:
log_exception('I/O error: {0}'.format(e[0]))
else:

Просмотреть файл

@ -19,7 +19,7 @@ except ImportError:
from olympia.constants import applications, base
import olympia.core.logger
from utils import get_cdn_url, log_configure, PLATFORM_NAMES_TO_CONSTANTS
from .utils import get_cdn_url, log_configure, PLATFORM_NAMES_TO_CONSTANTS
# Go configure the log.

Просмотреть файл

@ -1,7 +1,7 @@
from django.conf.urls import include, url
from rest_framework.routers import SimpleRouter
from views import AddonAbuseViewSet, UserAbuseViewSet
from .views import AddonAbuseViewSet, UserAbuseViewSet
reporting = SimpleRouter()

Просмотреть файл

@ -95,7 +95,7 @@ def process_fxa_event(raw_body, **kwargs):
if not (event_type and uid and timestamp):
raise ValueError(
'Properties event, uuid, and ts must all be non-empty')
except (ValueError, KeyError, TypeError), e:
except (ValueError, KeyError, TypeError) as e:
log.exception('Invalid account message: %s' % e)
else:
if event_type == 'primaryEmailChanged':

Просмотреть файл

@ -28,7 +28,7 @@ class Command(BaseCommand):
log.info(
u'%s tokens (%s) expired' % (len(done), ','.join(token_uuids)))
if version_pk:
print 'Warning: --version_id ignored as tokens provided too'
print('Warning: --version_id ignored as tokens provided too')
elif version_pk:
done = [t.expire() for t in ActivityLogToken.objects.filter(
version__pk=version_pk)]

Просмотреть файл

@ -808,7 +808,7 @@ class Addon(OnChangeMixin, ModelBase):
log.info(u'Version changed from current: %s to %s '
u'for addon %s'
% tuple(diff + [self]))
except Exception, e:
except Exception as e:
log.error(u'Could not save version changes current: %s to %s '
u'for addon %s (%s)' %
tuple(diff + [self, e]))

Просмотреть файл

@ -128,7 +128,7 @@ def delete_persona_image(dst, **kw):
return
try:
storage.delete(dst)
except Exception, e:
except Exception as e:
log.error('Error deleting persona image: %s' % e)

Просмотреть файл

@ -269,7 +269,7 @@ class TestAddonIndexer(TestCase):
# the index is an arbitrary super high version.
assert extracted['current_version']['compatible_apps'] == {
FIREFOX.id: {
'min': 2000000200100L,
'min': 2000000200100,
'max': 9999000000200100,
'max_human': '4.0',
'min_human': '2.0',
@ -303,7 +303,7 @@ class TestAddonIndexer(TestCase):
# the index is an arbitrary super high version.
assert extracted['latest_unlisted_version']['compatible_apps'] == {
FIREFOX.id: {
'min': 4009900200100L,
'min': 4009900200100,
'max': 9999000000200100,
'max_human': '5.0.99',
'min_human': '4.0.99',
@ -338,8 +338,8 @@ class TestAddonIndexer(TestCase):
assert extracted['current_version']['compatible_apps'] == {
FIREFOX.id: {
'min': 2000000200100L,
'max': 4000000200100L,
'min': 2000000200100,
'max': 4000000200100,
'max_human': '4.0',
'min_human': '2.0',
}

Просмотреть файл

@ -34,5 +34,5 @@ def do_addnewversion(application, version):
try:
AppVersion.objects.create(application=amo.APPS[application].id,
version=version)
except IntegrityError, e:
except IntegrityError as e:
raise CommandError('Version %r already exists: %r' % (version, e))

Просмотреть файл

@ -39,7 +39,7 @@ def cleanup(master, slave):
buffer = []
for _ in xrange(CHUNK):
try:
buffer.append(ks.next())
buffer.append(next(ks))
except StopIteration:
yield buffer
return
@ -54,7 +54,7 @@ def cleanup(master, slave):
drop = [k for k, size in zip(ks, pipe.execute())
if not k.startswith(settings.CACHE_PREFIX) or
0 < size < MIN or size > MAX]
except RedisError, err:
except RedisError as err:
log.warning('ignoring pipe.execute() error: {}'.format(err))
continue
num += len(ks)
@ -66,7 +66,7 @@ def cleanup(master, slave):
pipe.expire(k, EXPIRE)
try:
pipe.execute()
except RedisError, err:
except RedisError as err:
log.warning('ignoring pipe.execute() error: {}'.format(err))
continue
time.sleep(1) # Poor man's rate limiting.

Просмотреть файл

@ -527,6 +527,6 @@ class BasePreview(object):
log.info('Removing filename: %s for preview: %s'
% (filename, instance.pk))
storage.delete(filename)
except Exception, e:
except Exception as e:
log.error(
'Error deleting preview file (%s): %s' % (filename, e))

Просмотреть файл

@ -40,7 +40,7 @@ def memcache():
try:
s = socket.socket()
s.connect((ip, int(port)))
except Exception, e:
except Exception as e:
result = False
status = 'Failed to connect to memcached (%s): %s' % (host, e)
monitor_log.critical(status)
@ -69,7 +69,7 @@ def libraries():
try:
Image.new('RGB', (16, 16)).save(StringIO.StringIO(), 'JPEG')
libraries_results.append(('PIL+JPEG', True, 'Got it!'))
except Exception, e:
except Exception as e:
msg = "Failed to create a jpeg image: %s" % e
libraries_results.append(('PIL+JPEG', False, msg))
@ -143,7 +143,7 @@ def rabbitmq():
try:
broker.connect()
rabbitmq_results.append((hostname, True))
except Exception, e:
except Exception as e:
rabbitmq_results.append((hostname, False))
status = 'Failed to chat with rabbitmq %s: %s' % (hostname, e)
monitor_log.critical(status)
@ -175,7 +175,7 @@ def redis():
host=host, port=port, db=db, password=password,
socket_timeout=socket_timeout)
redis_results[alias] = redis_connection.info()
except Exception, e:
except Exception as e:
redis_results[alias] = None
status.append('Failed to chat with redis:%s' % alias)
monitor_log.critical('Failed to chat with redis: (%s)' % e)

Просмотреть файл

@ -45,7 +45,7 @@ def set_modified_on_object(app_label, model_name, pk, **kw):
try:
log.info('Setting modified on object: %s, %s' % (model_name, pk))
obj.update(modified=datetime.datetime.now(), **kw)
except Exception, e:
except Exception as e:
log.error('Failed to set modified on: %s, %s - %s' %
(model_name, pk, e))

Просмотреть файл

@ -91,7 +91,7 @@ def get_es_index_name(key):
def setup_es_test_data(es):
try:
es.cluster.health()
except Exception, e:
except Exception as e:
e.args = tuple(
[u"%s (it looks like ES is not running, try starting it or "
u"don't run ES tests: make test_no_es)" % e.args[0]] +
@ -512,7 +512,7 @@ class TestCase(PatchMixin, InitializeSessionMixin, BaseTestCase):
if isinstance(dt, basestring):
try:
dt = dateutil_parser(dt)
except ValueError, e:
except ValueError as e:
raise AssertionError(
'Expected valid date; got %s\n%s' % (dt, e))

Просмотреть файл

@ -581,7 +581,7 @@ def pngcrush_image(src, **kw):
log.info('Image optimization completed for: %s' % src)
return True
except Exception, e:
except Exception as e:
log.error('Error optimizing image: %s; %s' % (src, e))
return False

Просмотреть файл

@ -173,7 +173,7 @@ class JWTKeyAuthentication(JSONWebTokenAuthentication):
try:
payload = jwt_auth.jwt_decode_handler(jwt_value)
except Exception, exc:
except Exception as exc:
try:
# Log all exceptions
log.info('JWTKeyAuthentication failed; '

Просмотреть файл

@ -52,7 +52,7 @@ def jwt_decode_handler(token, get_api_key=APIKey.get_jwt_key):
try:
api_key = get_api_key(key=token_data['iss'])
except ObjectDoesNotExist, exc:
except ObjectDoesNotExist as exc:
log.info('No API key for JWT issuer: {}'.format(token_data['iss']))
raise exceptions.AuthenticationFailed(
detail='Unknown JWT iss (issuer).')
@ -88,18 +88,18 @@ def jwt_decode_handler(token, get_api_key=APIKey.get_jwt_key):
if int(payload['iat']) > (now + api_settings.JWT_LEEWAY):
raise jwt.InvalidIssuedAtError(
'Issued At claim (iat) cannot be in the future.')
except jwt.MissingRequiredClaimError, exc:
except jwt.MissingRequiredClaimError as exc:
log.info(u'Missing required claim during JWT authentication: '
u'{e.__class__.__name__}: {e}'.format(e=exc))
raise exceptions.AuthenticationFailed(
detail=u'Invalid JWT: {}.'.format(exc))
except jwt.InvalidIssuedAtError, exc:
except jwt.InvalidIssuedAtError as exc:
log.info(u'Invalid iat during JWT authentication: '
u'{e.__class__.__name__}: {e}'.format(e=exc))
raise exceptions.AuthenticationFailed(
detail='JWT iat (issued at time) is invalid. Make sure your '
'system clock is synchronized with something like TLSdate.')
except Exception, exc:
except Exception as exc:
log.warning(u'Unhandled exception during JWT authentication: '
u'{e.__class__.__name__}: {e}'.format(e=exc))
raise

Просмотреть файл

@ -49,7 +49,7 @@ def resize_icon(src, dst, **kw):
try:
resize_image(src, dst, (32, 32))
return True
except Exception, e:
except Exception as e:
log.error("Error saving collection icon: %s" % e)
@ -63,7 +63,7 @@ def delete_icon(dst, **kw):
try:
storage.delete(dst)
except Exception, e:
except Exception as e:
log.error("Error deleting icon: %s" % e)
@ -104,7 +104,7 @@ def collection_watchers(*ids, **kw):
.count())
Collection.objects.filter(pk=pk).update(subscribers=watchers)
log.info('Updated collection watchers: %s' % pk)
except Exception, e:
except Exception as e:
log.error('Updating collection watchers failed: %s, %s' % (pk, e))

Просмотреть файл

@ -479,7 +479,7 @@ def edit(request, collection, username, slug):
.filter(collection=collection))
meta = {c.addon_id: c for c in qs}
addons = collection.addons.all()
comments = get_notes(collection, raw=True).next()
comments = next(get_notes(collection, raw=True))
if is_admin:
initial = {

Просмотреть файл

@ -460,7 +460,7 @@ class TestFeaturedLocale(TestCase):
for a in ass:
mtch = rx.match(a.attrib['href'])
if mtch:
print mtch.group(2)
print(mtch.group(2))
def test_creatured_locale_en_US(self):
res = self.client.get(self.url, follow=True)

Просмотреть файл

@ -2,7 +2,7 @@ import re
from django.utils.translation import ugettext_lazy as _
from base import (
from .base import (
ADDON_DICT, ADDON_EXTENSION, ADDON_LPAPP, ADDON_PERSONA, ADDON_PLUGIN,
ADDON_SEARCH, ADDON_STATICTHEME, ADDON_THEME)

Просмотреть файл

@ -813,7 +813,7 @@ class SingleCategoryForm(happyforms.Form):
# support Firefox. Hoping to unify per-app categories in the meantime.
app = amo.FIREFOX
sorted_cats = sorted(CATEGORIES[app.id][self.addon.type].items(),
key=lambda (slug, cat): slug)
key=lambda slug_cat: slug_cat[0])
self.fields['category'].choices = [
(c.id, c.name) for _, c in sorted_cats]

Просмотреть файл

@ -55,22 +55,22 @@ class Command(BaseCommand):
add-on directly present on one of the landing pages (category landing
pages, mozilla collections landing pages, homepage).
"""
print 'Starting to fetch all addons...'
print('Starting to fetch all addons...')
addons = set()
print 'Fetching featured add-ons.'
print('Fetching featured add-ons.')
for featuredcollection in FeaturedCollection.objects.all():
addons.update(featuredcollection.collection.addons.all())
print 'Fetching mozilla collections add-ons.'
print('Fetching mozilla collections add-ons.')
try:
mozilla = UserProfile.objects.get(username='mozilla')
for collection in Collection.objects.filter(author=mozilla):
addons.update(collection.addons.all())
except UserProfile.DoesNotExist:
print 'Skipping mozilla collections as user does not exist.'
print('Skipping mozilla collections as user does not exist.')
print 'Fetching 5 top-rated extensions/themes from each category.'
print('Fetching 5 top-rated extensions/themes from each category.')
for cat in CATEGORIES[amo.FIREFOX.id][amo.ADDON_EXTENSION].values():
addons.update(Addon.objects.public().filter(
category=cat.id).order_by('-bayesian_rating')[:5])
@ -78,7 +78,7 @@ class Command(BaseCommand):
addons.update(Addon.objects.public().filter(
category=cat.id).order_by('-bayesian_rating')[:5])
print 'Fetching 5 trending extensions/themes from each category.'
print('Fetching 5 trending extensions/themes from each category.')
for cat in CATEGORIES[amo.FIREFOX.id][amo.ADDON_EXTENSION].values():
addons.update(Addon.objects.public().filter(
category=cat.id).order_by('-hotness')[:5])
@ -86,15 +86,15 @@ class Command(BaseCommand):
addons.update(Addon.objects.public().filter(
category=cat.id).order_by('-hotness')[:5])
print 'Fetching 25 most popular themes.'
print('Fetching 25 most popular themes.')
addons.update(
Addon.objects.public().filter(
type=amo.ADDON_PERSONA).order_by('-average_daily_users')[:25])
print 'Fetching disco pane add-ons.'
print('Fetching disco pane add-ons.')
addons.update(
Addon.objects.public().filter(
id__in=[item.addon_id for item in discopane_items['default']]))
print 'Done fetching, %d add-ons to process total.' % len(addons)
print('Done fetching, %d add-ons to process total.' % len(addons))
return addons

Просмотреть файл

@ -9,6 +9,6 @@ class Command(BaseCommand):
from olympia.devhub import tasks
qs = FileUpload.objects.filter(validation=None)
pks = qs.values_list('pk', flat=True)
print 'Restarting %s tasks.' % len(pks)
print('Restarting %s tasks.' % len(pks))
for pk in pks:
tasks.validator.delay(pk)

Просмотреть файл

@ -34,7 +34,7 @@ def change():
.filter(version__addon__type=amo.ADDON_SEARCH)
.exclude(platform=amo.PLATFORM_ALL.id))
k = 0
print 'Changing %s files' % len(files)
print('Changing %s files' % len(files))
for chunk in chunked(files, 100):
for file in File.objects.no_cache().filter(pk__in=chunk):
file.platform = amo.PLATFORM_ALL.id
@ -43,7 +43,7 @@ def change():
file.save()
k += 1
if not k % 50:
print '... done %s' % k
print('... done %s' % k)
def report():
@ -53,18 +53,16 @@ def report():
.filter(files_count__gt=1))
for chunk in chunked(versions, 100):
for version in Version.objects.no_cache().filter(pk__in=chunk):
print 'Addon: %s, %s' % (version.addon.pk,
version.addon.name)
print 'Version: %s - %s files' % (version.pk,
version.files.count())
print 'URL: %s' % reverse('devhub.versions.edit',
print('Addon: %s, %s' % (version.addon.pk,
version.addon.name))
print('Version: %s - %s files' % (version.pk,
version.files.count()))
print('URL: %s' % reverse('devhub.versions.edit',
args=[version.addon.slug,
version.pk])
version.pk]))
hashes = []
for file in version.all_files:
print 'File: %s, %s' % (file.filename, file.hash)
print('File: %s, %s' % (file.filename, file.hash))
if file.hash in hashes:
print '...this hash is repeated, same file?'
print('...this hash is repeated, same file?')
hashes.append(file.hash)
print

Просмотреть файл

@ -152,7 +152,7 @@ def validation_task(fn):
data = fn(id_, hash_, *args, **kw)
result = json.loads(data)
return result
except Exception, e:
except Exception as e:
log.exception('Unhandled error during validation: %r' % e)
is_webextension = kw.get('is_webextension', False)
@ -777,7 +777,7 @@ def resize_icon(source, dest_folder, target_sizes, **kw):
return {
'icon_hash': icon_hash
}
except Exception, e:
except Exception as e:
log.error("Error saving addon icon (%s): %s" % (dest_file, e))
@ -801,7 +801,7 @@ def resize_preview(src, preview_pk, **kw):
preview.sizes = sizes
preview.save()
return True
except Exception, e:
except Exception as e:
log.error("Error saving preview: %s" % e)
@ -823,7 +823,7 @@ def get_preview_sizes(ids, **kw):
'image': image_size(preview.image_path),
}
preview.update(sizes=sizes)
except Exception, err:
except Exception as err:
log.error('Failed to find size of preview: %s, error: %s'
% (addon.pk, err))
@ -840,10 +840,10 @@ def failed_validation(*messages):
def _fetch_content(url):
try:
return urllib2.urlopen(url, timeout=15)
except urllib2.HTTPError, e:
except urllib2.HTTPError as e:
raise Exception(
ugettext('%s responded with %s (%s).') % (url, e.code, e.msg))
except urllib2.URLError, e:
except urllib2.URLError as e:
# Unpack the URLError to try and find a useful message.
if isinstance(e.reason, socket.timeout):
raise Exception(ugettext('Connection to "%s" timed out.') % url)

Просмотреть файл

@ -1225,7 +1225,7 @@ class TestUploadDetail(BaseUploadTest):
upload = FileUpload.objects.get()
response = self.client.get(reverse('devhub.upload_detail_for_version',
args=[addon.slug, upload.uuid.hex]))
print response.content
print(response.content)
data = json.loads(response.content)
assert data['validation']['messages'] == []

Просмотреть файл

@ -719,7 +719,7 @@ def json_upload_detail(request, upload, addon_slug=None):
if result['validation']:
try:
pkg = parse_addon(upload, addon=addon, user=request.user)
except django_forms.ValidationError, exc:
except django_forms.ValidationError as exc:
errors_before = result['validation'].get('errors', 0)
# This doesn't guard against client-side tinkering, and is purely
# to display those non-linter errors nicely in the frontend. What

Просмотреть файл

@ -25,7 +25,7 @@ class Command(BaseCommand):
if not options['force']:
files = files.filter(_webext_permissions=None)
pks = files.values_list('pk', flat=True)
print 'pks count %s' % pks.count()
print('pks count %s' % pks.count())
if pks:
grouping = []
for chunk in chunked(pks, 100):

Просмотреть файл

@ -221,7 +221,7 @@ class File(OnChangeMixin, ModelBase):
if name in zip_.namelist():
try:
opts = json.load(zip_.open(name))
except ValueError, exc:
except ValueError as exc:
log.info('Could not parse harness-options.json in %r: %s' %
(path, exc))
else:
@ -356,7 +356,7 @@ class File(OnChangeMixin, ModelBase):
try:
manifest = zip.read('chrome.manifest')
except KeyError, e:
except KeyError as e:
log.info('No file named: chrome.manifest in file: %s' % self.pk)
return ''
@ -370,10 +370,10 @@ class File(OnChangeMixin, ModelBase):
if 'localepicker.properties' not in p:
p = os.path.join(p, 'localepicker.properties')
res = zip.extract_from_manifest(p)
except (zipfile.BadZipfile, IOError), e:
except (zipfile.BadZipfile, IOError) as e:
log.error('Error unzipping: %s, %s in file: %s' % (p, e, self.pk))
return ''
except (ValueError, KeyError), e:
except (ValueError, KeyError) as e:
log.error('No file named: %s in file: %s' % (e, self.pk))
return ''

Просмотреть файл

@ -45,7 +45,7 @@ def extract_webext_permissions(ids, **kw):
(len(permissions), file_.pk))
WebextPermission.objects.update_or_create(
defaults={'permissions': permissions}, file=file_)
except Exception, err:
except Exception as err:
log.error('Failed to extract: %s, error: %s' % (file_.pk, err))

Просмотреть файл

@ -289,7 +289,7 @@ class RDFExtractor(object):
if list(self.rdf.triples((manifest, None, None))):
self.root = manifest
else:
self.root = self.rdf.subjects(None, self.manifest).next()
self.root = next(self.rdf.subjects(None, self.manifest))
def find(self, name, ctx=None):
"""Like $() for install.rdf, where name is the selector."""

Просмотреть файл

@ -75,7 +75,7 @@ def index_data(alias, index):
try:
get_modules()[alias].reindex(index)
except Exception, exc:
except Exception as exc:
index_data.retry(
args=(alias, index), exc=exc, max_retries=3)
raise

Просмотреть файл

@ -44,7 +44,7 @@ class ReindexingManager(models.Manager):
try:
reindex = self.get(alias=index)
# Yes. Let's reindex on both indexes.
return [idx for idx in reindex.new_index, reindex.old_index
return [idx for idx in (reindex.new_index, reindex.old_index)
if idx is not None]
except Reindexing.DoesNotExist:
return [index]

Просмотреть файл

@ -32,7 +32,7 @@ class BaseFormMixin(object):
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError, e:
except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]

Просмотреть файл

@ -1,5 +1,5 @@
from addons.cron import reset_featured_addons
print 'here we go'
print('here we go')
reset_featured_addons()

Просмотреть файл

@ -4,10 +4,10 @@ from market.models import Price
tiers = [Decimal(x) for x in
'0.99', '1.99', '2.99', '3.99', '4.99', '5.99', '6.99', '7.99',
'8.99', '9.99', '10.99', '11.99', '12.99', '13.99', '14.99', '15.99',
'16.99', '17.99', '18.99', '19.99', '20.99', '21.99', '22.99',
'23.99', '24.99', '29.99', '34.99', '39.99', '44.99', '49.99']
('0.99', '1.99', '2.99', '3.99', '4.99', '5.99', '6.99', '7.99',
'8.99', '9.99', '10.99', '11.99', '12.99', '13.99', '14.99', '15.99',
'16.99', '17.99', '18.99', '19.99', '20.99', '21.99', '22.99',
'23.99', '24.99', '29.99', '34.99', '39.99', '44.99', '49.99')]
def run():

Просмотреть файл

@ -17,12 +17,12 @@ def run():
name = '%s Localizers' % locale
rules = 'Locale.%s:Edit,L10nTools:View' % locale
group = Group.objects.create(pk=pk, name=name, rules=rules)
print 'New group created: (%d) %s' % (pk, name)
print('New group created: (%d) %s' % (pk, name))
try:
old_group = Group.objects.get(pk__lt=50000, name=name)
except Group.DoesNotExist:
print 'Old group not found: %s' % name
print('Old group not found: %s' % name)
continue
# Rename old groups so they are distinguisable.
@ -33,4 +33,4 @@ def run():
for user in old_group.users.all():
cnt += 1
GroupUser.objects.create(group=group, user=user)
print 'Migrated %d users to new group (%s)' % (cnt, name)
print('Migrated %d users to new group (%s)' % (cnt, name))

Просмотреть файл

@ -144,4 +144,4 @@ def run():
price=Decimal(v),
currency=currency)
except Price.DoesNotExist:
print 'Skipping creating: %s, %s for %s' % (k, v, currency)
print('Skipping creating: %s, %s for %s' % (k, v, currency))

Просмотреть файл

@ -8,4 +8,4 @@ def run():
for chunk in chunked(Webapp.objects.all(), 50):
for app in chunk:
generate_image_assets.delay(app, slug='featured_tile')
print u'Generated feature tile for app %d' % app.id
print(u'Generated feature tile for app %d' % app.id)

Просмотреть файл

@ -15,7 +15,7 @@ def reindex_reviews(addon_id, **kw):
Addon.objects.get(id=addon_id).reviews[0].save()
except IndexError:
# It's possible that `total_ratings` was wrong.
print 'No reviews found for %s' % addon_id
print('No reviews found for %s' % addon_id)
def run():

Просмотреть файл

@ -7,13 +7,13 @@ from market.models import Price
@transaction.commit_on_success
def run():
print 'Adding in new tiers'
print('Adding in new tiers')
for tier in ['0.10', '0.25', '0.50', '12.49']:
exists = Price.objects.no_cache().filter(price=Decimal(tier)).exists()
if exists:
print 'Tier already exists, skipping: %s' % tier
print('Tier already exists, skipping: %s' % tier)
continue
print 'Created tier: %s' % tier
print('Created tier: %s' % tier)
Price.objects.create(name='Tier 0', price=Decimal(tier),
active=True)

Просмотреть файл

@ -5,10 +5,10 @@ from market.models import Price
@transaction.commit_on_success
def run():
print 'Renaming tiers'
print('Renaming tiers')
for k, tier in enumerate(Price.objects.no_cache().filter(active=True)
.order_by('price')):
new = 'Tier %s' % k
print 'Renaming %s to %s' % (tier.name, new)
print('Renaming %s to %s' % (tier.name, new))
tier.name = new
tier.save()

Просмотреть файл

@ -21,18 +21,18 @@ def run():
try:
entertainment = all_cats.filter(slug='entertainment-sports')[0]
except IndexError:
print 'Could not find Category with slug="entertainment-sports"'
print('Could not find Category with slug="entertainment-sports"')
else:
# (a) Change name of the category to "Entertainment."
entertainment.name = 'Entertainment'
entertainment.slug = 'entertainment'
entertainment.save()
print 'Renamed "Entertainment & Sports" to "Entertainment"'
print('Renamed "Entertainment & Sports" to "Entertainment"')
# (b) Create a new category called "Sports."
Category.objects.create(type=amo.ADDON_WEBAPP, slug='sports',
name='Sports')
print 'Created "Sports"'
print('Created "Sports"')
# --
@ -40,11 +40,11 @@ def run():
try:
music = all_cats.filter(slug='music')[0]
except IndexError:
print 'Could not find Category with slug="music"'
print('Could not find Category with slug="music"')
else:
music.name = 'Music'
music.save()
print 'Renamed "Music & Audio" to "Music"'
print('Renamed "Music & Audio" to "Music"')
# --
@ -52,11 +52,11 @@ def run():
try:
social = all_cats.filter(slug='social')[0]
except IndexError:
print 'Could not find Category with slug="social"'
print('Could not find Category with slug="social"')
else:
social.name = 'Social'
social.save()
print 'Renamed "Social & Communication" to "Social"'
print('Renamed "Social & Communication" to "Social"')
# --
@ -64,18 +64,18 @@ def run():
try:
books = all_cats.filter(slug='books-reference')[0]
except IndexError:
print 'Could not find Category with slug="books-reference"'
print('Could not find Category with slug="books-reference"')
else:
# (a) Change name of the category to "Books.""
books.name = 'Books'
books.slug = 'books'
books.save()
print 'Renamed "Books & Reference" to "Books"'
print('Renamed "Books & Reference" to "Books"')
# (b) Create a new category called "Reference."
Category.objects.create(type=amo.ADDON_WEBAPP, slug='reference',
name='Reference')
print 'Created "Reference"'
print('Created "Reference"')
# --
@ -83,16 +83,16 @@ def run():
try:
photos = all_cats.filter(slug='photos-media')[0]
except IndexError:
print 'Could not find Category with slug="photos-media"'
print('Could not find Category with slug="photos-media"')
else:
photos.name = 'Photo & Video'
photos.slug = 'photo-video'
photos.save()
print 'Renamed "Photos & Media" to "Photo & Video"'
print('Renamed "Photos & Media" to "Photo & Video"')
# --
# (6) Add "Maps & Navigation."
Category.objects.create(type=amo.ADDON_WEBAPP, slug='maps-navigation',
name='Maps & Navigation')
print 'Created "Maps & Navigation"'
print('Created "Maps & Navigation"')

Просмотреть файл

@ -33,9 +33,9 @@ def run():
try:
tier = Price.objects.get(price=Decimal(amount))
except Price.DoesNotExist:
print 'Tier not found: %s' % amount
print('Tier not found: %s' % amount)
continue
tier.name = name
tier.save()
print 'Tier changed: %s to %s' % (amount, name)
print('Tier changed: %s to %s' % (amount, name))

Просмотреть файл

@ -121,7 +121,7 @@ def run():
try:
tier = Price.objects.filter(price=k).no_transforms()[0]
except IndexError:
print 'Tier does not exist: {0}'.format(k)
print('Tier does not exist: {0}'.format(k))
continue
for country, values in v.items():
@ -133,4 +133,4 @@ def run():
region=values['region'],
currency=values['currency']
)
print 'Creating: {0}, {1}'.format(k, country)
print('Creating: {0}, {1}'.format(k, country))

Просмотреть файл

@ -20,17 +20,17 @@ def run():
for aer in AddonExcludedRegion.objects.filter(region=18):
try:
aer.update(region=mkt.regions.MX.id)
print 'OK: %s New Mexico -> Old Mexico' % aer.id
print('OK: %s New Mexico -> Old Mexico' % aer.id)
except (IntegrityError, ObjectDoesNotExist):
print 'SKIP: %s New Mexico -> Old Mexico' % aer.id
print('SKIP: %s New Mexico -> Old Mexico' % aer.id)
# And the featured apps, if there were any.
for far in FeaturedAppRegion.objects.filter(region=18):
try:
far.update(region=mkt.regions.MX.id)
print 'OK: %s New Mexico -> Old Mexico' % far.id
print('OK: %s New Mexico -> Old Mexico' % far.id)
except (IntegrityError, ObjectDoesNotExist):
print 'SKIP: %s New Mexico -> Old Mexico' % far.id
print('SKIP: %s New Mexico -> Old Mexico' % far.id)
# New regions were added.
exclude_new_region([

Просмотреть файл

@ -73,7 +73,7 @@ def update_global_totals(job, date, **kw):
try:
cursor = connection.cursor()
cursor.execute(q, p)
except Exception, e:
except Exception as e:
log.critical('Failed to update global stats: (%s): %s' % (p, e))
else:
log.debug('Committed global stats details: (%s) has (%s) for (%s)'
@ -204,7 +204,7 @@ def index_update_counts(ids, index=None, **kw):
data.append(search.extract_update_count(update))
bulk_index(es, data, index=index,
doc_type=UpdateCount.get_mapping_type(), refresh=True)
except Exception, exc:
except Exception as exc:
index_update_counts.retry(args=[ids, index], exc=exc, **kw)
raise
@ -224,7 +224,7 @@ def index_download_counts(ids, index=None, **kw):
data.append(search.extract_download_count(dl))
bulk_index(es, data, index=index,
doc_type=DownloadCount.get_mapping_type(), refresh=True)
except Exception, exc:
except Exception as exc:
index_download_counts.retry(args=[ids, index], exc=exc)
raise
@ -253,7 +253,7 @@ def index_collection_counts(ids, index=None, **kw):
bulk_index(es, data, index=index,
doc_type=CollectionCount.get_mapping_type(),
refresh=True)
except Exception, exc:
except Exception as exc:
index_collection_counts.retry(args=[ids], exc=exc)
raise
@ -275,6 +275,6 @@ def index_theme_user_counts(ids, index=None, **kw):
data.append(search.extract_theme_user_count(user_count))
bulk_index(es, data, index=index,
doc_type=ThemeUserCount.get_mapping_type(), refresh=True)
except Exception, exc:
except Exception as exc:
index_theme_user_counts.retry(args=[ids], exc=exc, **kw)
raise

Просмотреть файл

@ -245,7 +245,7 @@ class _TransField(object):
if self.default_locale.lower() == locale:
super(_TransField, self).validate(val)
super(_TransField, self).run_validators(val)
except forms.ValidationError, e:
except forms.ValidationError as e:
errors.extend(e.messages, locale)
if errors:

Просмотреть файл

@ -24,7 +24,7 @@ def delete_photo(dst, **kw):
try:
storage.delete(dst)
except Exception, e:
except Exception as e:
task_log.error("Error deleting userpic: %s" % e)
@ -37,7 +37,7 @@ def resize_photo(src, dst, locally=False, **kw):
try:
resize_image(src, dst, (200, 200))
return True
except Exception, e:
except Exception as e:
task_log.error("Error saving userpic: %s" % e)

Просмотреть файл

@ -146,7 +146,7 @@ class TestEdit(UserViewBase):
self.data.update(biography='<a href="https://google.com">google</a>')
response = self.client.post(self.url, self.data, follow=True)
assert response.status_code == 200
print response.context
print(response.context)
self.assertFormError(response, 'form', 'biography',
u'No links are allowed.')

Просмотреть файл

@ -38,7 +38,7 @@ def do_adduser(user, group):
GroupUser.objects.create(user=user, group=group)
except IntegrityError, e:
except IntegrityError as e:
raise CommandError('User is already in that group? %s' % e)
except UserProfile.DoesNotExist:
raise CommandError('User ({user}) does not exist.'.format(user=user))

Просмотреть файл

@ -8,5 +8,5 @@ class Command(BaseCommand):
def handle(self, *args, **options):
celery_error.delay()
print ('A RuntimeError exception was raised from a celery task. '
'Check the logs!')
print('A RuntimeError exception was raised from a celery task. '
'Check the logs!')

Просмотреть файл

@ -170,10 +170,9 @@ class TestEmailPreview(TestCase):
args=[self.topic.topic]))
assert r.status_code == 200
rdr = csv.reader(StringIO(r.content))
assert rdr.next() == ['from_email', 'recipient_list', 'subject',
'body']
assert rdr.next() == ['admin@mozilla.org', 'funnyguy@mozilla.org',
'the subject', 'Hello Ivan Krsti\xc4\x87']
assert next(rdr) == ['from_email', 'recipient_list', 'subject', 'body']
assert next(rdr) == ['admin@mozilla.org', 'funnyguy@mozilla.org',
'the subject', 'Hello Ivan Krsti\xc4\x87']
class TestMonthlyPick(TestCase):

Просмотреть файл

@ -19,7 +19,7 @@ import lxml.html # noqa
from lxml.html import submit_form # noqa
from fxa import oauth as fxa_oauth # noqa
import helpers # noqa
from . import helpers # noqa
logging.Formatter.converter = time.gmtime

Просмотреть файл

@ -1,7 +1,7 @@
from pypom import Region
from selenium.webdriver.common.by import By
from base import Base
from .base import Base
class Collections(Base):