diff --git a/opentreemap/api/auth.py b/opentreemap/api/auth.py
index a4a0422a2..b81cea029 100644
--- a/opentreemap/api/auth.py
+++ b/opentreemap/api/auth.py
@@ -1,13 +1,13 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import base64
import hashlib
import hmac
import re
-import urllib
+import urllib.request
+import urllib.parse
+import urllib.error
from django.http import HttpResponse
from django.contrib.auth import authenticate
@@ -29,9 +29,9 @@ def get_signature_for_request(request, secret_key):
# This used to use request.REQUEST, but after some testing and analysis it
# seems that both iOS & Android always pass named parameters in the query
# string, even for non-GET requests
- params = sorted(request.GET.iteritems(), key=lambda a: a[0])
+ params = sorted(iter(request.GET.items()), key=lambda a: a[0])
- paramstr = '&'.join(['%s=%s' % (k, urllib.quote_plus(str(v)))
+ paramstr = '&'.join(['%s=%s' % (k, urllib.parse.quote_plus(str(v)))
for (k, v) in params
if k.lower() != "signature"])
diff --git a/opentreemap/api/decorators.py b/opentreemap/api/decorators.py
index 948fbeb62..e2231abc5 100644
--- a/opentreemap/api/decorators.py
+++ b/opentreemap/api/decorators.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import datetime
diff --git a/opentreemap/api/instance.py b/opentreemap/api/instance.py
index 7cb06352f..f7bcf972d 100644
--- a/opentreemap/api/instance.py
+++ b/opentreemap/api/instance.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import copy
@@ -53,13 +51,13 @@ def wrapper(request, *args, **kwargs):
if request.api_version < 4:
multichoice_fields = {
field for field, info
- in instance_info_dict['fields'].iteritems()
+ in instance_info_dict['fields'].items()
if info['data_type'] == 'multichoice'}
# Remove multichoice fields from perms
instance_info_dict['fields'] = {
field: info for field, info
- in instance_info_dict['fields'].iteritems()
+ in instance_info_dict['fields'].items()
if field not in multichoice_fields}
# Remove multichoice fields from field groups
@@ -300,7 +298,7 @@ def public_instances(request):
def _contextify_instances(instances):
""" Converts instances to context dictionary"""
- return map(_instance_info_dict, instances)
+ return list(map(_instance_info_dict, instances))
def _instance_info_dict(instance):
diff --git a/opentreemap/api/migrations/0001_initial.py b/opentreemap/api/migrations/0001_initial.py
index 37fc81245..17467f6df 100644
--- a/opentreemap/api/migrations/0001_initial.py
+++ b/opentreemap/api/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/api/migrations/0002_apiaccesscredential_user.py b/opentreemap/api/migrations/0002_apiaccesscredential_user.py
index 64ee64fba..1272c90d0 100644
--- a/opentreemap/api/migrations/0002_apiaccesscredential_user.py
+++ b/opentreemap/api/migrations/0002_apiaccesscredential_user.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/api/models.py b/opentreemap/api/models.py
index 37d42a0c8..191bd0cf0 100755
--- a/opentreemap/api/models.py
+++ b/opentreemap/api/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import uuid
import base64
diff --git a/opentreemap/api/plots.py b/opentreemap/api/plots.py
index c02dca24c..5151d6f36 100644
--- a/opentreemap/api/plots.py
+++ b/opentreemap/api/plots.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from functools import wraps
@@ -42,7 +40,7 @@ def plots_closest_to_point(request, instance, lat, lng):
try:
max_plots = int(request.GET.get('max_plots', '1'))
- if max_plots not in xrange(1, 501):
+ if max_plots not in range(1, 501):
raise ValueError()
except ValueError:
raise HttpBadRequestException(
@@ -80,7 +78,7 @@ def update_or_create_plot(request, instance, plot_id=None):
for model in ["plot", "tree"]:
if model in request_dict:
- for key, val in request_dict[model].iteritems():
+ for key, val in request_dict[model].items():
data["%s.%s" % (model, key)] = val
# We explicitly disallow setting a plot's tree id.
diff --git a/opentreemap/api/test_utils.py b/opentreemap/api/test_utils.py
index fdff6f07a..dc75c6948 100644
--- a/opentreemap/api/test_utils.py
+++ b/opentreemap/api/test_utils.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.contrib.gis.geos.collections import MultiPolygon
from django.contrib.gis.geos.polygon import Polygon
diff --git a/opentreemap/api/tests.py b/opentreemap/api/tests.py
index cff420004..9e7b268df 100644
--- a/opentreemap/api/tests.py
+++ b/opentreemap/api/tests.py
@@ -1,13 +1,13 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
-from StringIO import StringIO
+
+from io import StringIO
from json import loads, dumps
-from urlparse import urlparse
+from urllib.parse import urlparse
-import urllib
+import urllib.request
+import urllib.parse
+import urllib.error
import os
import json
import base64
@@ -84,9 +84,9 @@ def _get_path(parsed_url):
"""
# If there are parameters, add them
if parsed_url[3]:
- return urllib.unquote(parsed_url[2] + ";" + parsed_url[3])
+ return urllib.parse.unquote(parsed_url[2] + ";" + parsed_url[3])
else:
- return urllib.unquote(parsed_url[2])
+ return urllib.parse.unquote(parsed_url[2])
def send_json_body(url, body_object, client, method, user=None):
@@ -794,7 +794,7 @@ def test_update_plot_with_pending(self):
self.assertEqual(3, len(Audit.pending_audits()),
"Expected 3 pends, one for each edited field")
- self.assertEqual(3, len(response_json['pending_edits'].keys()),
+ self.assertEqual(3, len(list(response_json['pending_edits'].keys())),
"Expected the json response to have a "
"pending_edits dict with 3 keys, one for each field")
@@ -808,10 +808,10 @@ def test_invalid_field_returns_200_field_is_not_in_response(self):
self.assertEqual(200, response.status_code)
response_json = loads(response.content)
- self.assertFalse("error" in response_json.keys(),
+ self.assertFalse("error" in list(response_json.keys()),
"Did not expect an error")
- self.assertFalse("foo" in response_json.keys(),
+ self.assertFalse("foo" in list(response_json.keys()),
"Did not expect foo to be added to the plot")
def test_update_creates_tree(self):
@@ -924,7 +924,7 @@ def test_update_tree_with_pending(self):
"Expected 1 pend record for the edited field.")
response_json = loads(response.content)
- self.assertEqual(1, len(response_json['pending_edits'].keys()),
+ self.assertEqual(1, len(list(response_json['pending_edits'].keys())),
"Expected the json response to have a"
" pending_edits dict with 1 keys")
@@ -1418,7 +1418,7 @@ def test_multichoice_fields_v4(self):
response = instance_info_endpoint(request, 4, self.instance.url_name)
info_dict = json.loads(response.content)
- self.assertIn('plot.udf:multi', info_dict['fields'].keys())
+ self.assertIn('plot.udf:multi', list(info_dict['fields'].keys()))
self.assertTrue(any('plot.udf:multi' in group.get('field_keys', [])
for group in info_dict['field_key_groups']))
@@ -1428,7 +1428,7 @@ def test_multichoice_removed_in_v3(self):
response = instance_info_endpoint(request, 3, self.instance.url_name)
info_dict = json.loads(response.content)
- self.assertNotIn('plot.udf:multi', info_dict['fields'].keys())
+ self.assertNotIn('plot.udf:multi', list(info_dict['fields'].keys()))
self.assertFalse(any('plot.udf:multi' in group.get('field_keys', [])
for group in info_dict['field_key_groups']))
@@ -1630,7 +1630,7 @@ def testUploadPhoto(self):
response = update_profile_photo_endpoint(req, LATEST_API,
str(peon.pk))
- self.assertEquals(response.status_code, 200)
+ self.assertEqual(response.status_code, 200)
peon = User.objects.get(pk=peon.pk)
self.assertIsNotNone(peon.photo)
@@ -1657,7 +1657,7 @@ def testCanOnlyUploadAsSelf(self):
response = update_profile_photo_endpoint(req, LATEST_API,
str(grunt.pk))
- self.assertEquals(response.status_code, 403)
+ self.assertEqual(response.status_code, 403)
def testCreateUser(self):
rslt = create_user(self.make_post_request(self.defaultUserDict))
@@ -1665,7 +1665,7 @@ def testCreateUser(self):
user = User.objects.get(pk=pk)
- for field, target_value in self.defaultUserDict.iteritems():
+ for field, target_value in self.defaultUserDict.items():
if field != 'password':
self.assertEqual(getattr(user, field), target_value)
@@ -1758,12 +1758,12 @@ def updatePeonRequest(d):
updatePeonRequest({'last_name': 'l1'})
peon = User.objects.get(pk=peon.pk)
- self.assertEquals(peon.last_name, 'l1')
+ self.assertEqual(peon.last_name, 'l1')
updatePeonRequest({'last_name': 'l2'})
peon = User.objects.get(pk=peon.pk)
- self.assertEquals(peon.last_name, 'l2')
+ self.assertEqual(peon.last_name, 'l2')
updatePeonRequest({'password': 'whateva'})
@@ -1785,12 +1785,12 @@ def updatePeonRequest(d):
updatePeonRequest({'lastname': 'l1'})
peon = User.objects.get(pk=peon.pk)
- self.assertEquals(peon.last_name, 'l1')
+ self.assertEqual(peon.last_name, 'l1')
updatePeonRequest({'lastname': 'l2'})
peon = User.objects.get(pk=peon.pk)
- self.assertEquals(peon.last_name, 'l2')
+ self.assertEqual(peon.last_name, 'l2')
def testCantRemoveRequiredFields(self):
peon = make_user(username='peon', password='pw')
@@ -1802,7 +1802,7 @@ def testCantRemoveRequiredFields(self):
resp = put_json(url, {'username': ''},
self.client, user=peon)
- self.assertEquals(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400)
def testCanOnlyUpdateLoggedInUser(self):
peon = make_user(username='peon', password='pw')
@@ -1817,7 +1817,7 @@ def testCanOnlyUpdateLoggedInUser(self):
resp = put_json(url, {'password': 'whateva'},
self.client, user=grunt)
- self.assertEquals(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403)
class SigningTest(OTMTestCase):
@@ -1876,7 +1876,7 @@ def testAwsExample(self):
sig = get_signature_for_request(
req, b'wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY')
- self.assertEquals(
+ self.assertEqual(
sig, 'i91nKc4PWAt0JJIdXwz9HxZCJDdiy6cf/Mj6vPxyYIs=')
def testTimestampVoidsSignature(self):
@@ -2035,7 +2035,7 @@ def test_user_has_rep(self):
ijim.save()
auth = base64.b64encode("jim:password")
- withauth = dict(self.sign.items() +
+ withauth = dict(list(self.sign.items()) +
[("HTTP_AUTHORIZATION", "Basic %s" % auth)])
ret = self.client.get("%s/user" % API_PFX, **withauth)
@@ -2060,18 +2060,18 @@ def _test_requires_admin_access(self, endpoint_name):
iuser.save_with_user(iuser)
resp = get_signed(self.client, url, user=self.user1)
- self.assertEquals(resp.status_code, 403)
+ self.assertEqual(resp.status_code, 403)
iuser.admin = True
iuser.save_with_user(self.user1)
resp = get_signed(self.client, url, user=self.user1)
- self.assertEquals(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200)
iuser.delete_with_user(self.user1)
resp = get_signed(self.client, url, user=self.user1)
- self.assertEquals(resp.status_code, 401)
+ self.assertEqual(resp.status_code, 401)
def test_csv_requires_admin(self):
self._test_requires_admin_access('users_csv')
@@ -2089,7 +2089,7 @@ def test_send_password_reset_email_url(self):
url = "%s/send-password-reset-email?email=%s"
response = post_json(url % (API_PFX, self.jim.email),
{}, self.client, None)
- self.assertEquals(response.status_code, 200)
+ self.assertEqual(response.status_code, 200)
class SpeciesListTest(OTMTestCase):
diff --git a/opentreemap/api/urls.py b/opentreemap/api/urls.py
index 83cc62d7b..5ce6edbc4 100644
--- a/opentreemap/api/urls.py
+++ b/opentreemap/api/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/api/user.py b/opentreemap/api/user.py
index 052d76333..638bcf781 100644
--- a/opentreemap/api/user.py
+++ b/opentreemap/api/user.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from functools import wraps
diff --git a/opentreemap/api/views.py b/opentreemap/api/views.py
index 69bed8cc6..383092fd4 100644
--- a/opentreemap/api/views.py
+++ b/opentreemap/api/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from functools import partial
diff --git a/opentreemap/appevents/handlers.py b/opentreemap/appevents/handlers.py
index e3adffaca..c004605e5 100644
--- a/opentreemap/appevents/handlers.py
+++ b/opentreemap/appevents/handlers.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.utils.timezone import now
diff --git a/opentreemap/appevents/migrations/0001_initial.py b/opentreemap/appevents/migrations/0001_initial.py
index 0669fabdc..60b7f6402 100644
--- a/opentreemap/appevents/migrations/0001_initial.py
+++ b/opentreemap/appevents/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
import treemap.json_field
diff --git a/opentreemap/appevents/migrations/0002_auto_20170907_0937.py b/opentreemap/appevents/migrations/0002_auto_20170907_0937.py
index 10566c72f..2e4b3e3ab 100644
--- a/opentreemap/appevents/migrations/0002_auto_20170907_0937.py
+++ b/opentreemap/appevents/migrations/0002_auto_20170907_0937.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-07 14:37
-from __future__ import unicode_literals
+
from django.db import migrations
import treemap.DotDict
diff --git a/opentreemap/appevents/models.py b/opentreemap/appevents/models.py
index 457ac8a65..bd7557861 100644
--- a/opentreemap/appevents/models.py
+++ b/opentreemap/appevents/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.db import models
@@ -23,10 +21,10 @@ class AppEvent(models.Model):
def create(cls, event_type, **kwargs):
# TODO: If a callable is not associated with the event_type, throw
app_event = AppEvent(event_type=event_type)
- for key, value in kwargs.iteritems():
+ for key, value in kwargs.items():
app_event.data[key] = value
app_event.save()
return app_event
# The signals need to be imported after the models are defined
-import signals # NOQA
+from . import signals # NOQA
diff --git a/opentreemap/appevents/signals.py b/opentreemap/appevents/signals.py
index 01f1c735a..2fc7014f6 100644
--- a/opentreemap/appevents/signals.py
+++ b/opentreemap/appevents/signals.py
@@ -1,14 +1,12 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.db.models.signals import post_save
from django.dispatch import receiver
-from models import AppEvent
+from .models import AppEvent
-from tasks import queue_events_to_be_handled
+from .tasks import queue_events_to_be_handled
@receiver(post_save, sender=AppEvent)
diff --git a/opentreemap/appevents/tasks.py b/opentreemap/appevents/tasks.py
index af6ab0823..5f1583299 100644
--- a/opentreemap/appevents/tasks.py
+++ b/opentreemap/appevents/tasks.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from celery import shared_task
from django.db import transaction
diff --git a/opentreemap/appevents/tests.py b/opentreemap/appevents/tests.py
index 9a68731b5..8f88bdede 100644
--- a/opentreemap/appevents/tests.py
+++ b/opentreemap/appevents/tests.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from datetime import timedelta
diff --git a/opentreemap/exporter/decorators.py b/opentreemap/exporter/decorators.py
index a446377aa..3b7aafd8b 100644
--- a/opentreemap/exporter/decorators.py
+++ b/opentreemap/exporter/decorators.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from functools import wraps
from celery import chain
diff --git a/opentreemap/exporter/lib.py b/opentreemap/exporter/lib.py
index 793f2cdf2..8e729e38c 100644
--- a/opentreemap/exporter/lib.py
+++ b/opentreemap/exporter/lib.py
@@ -1,6 +1,3 @@
-from __future__ import unicode_literals
-from __future__ import print_function
-from __future__ import division
def export_enabled_for(instance, user):
diff --git a/opentreemap/exporter/management/commands/create_photo_csv.py b/opentreemap/exporter/management/commands/create_photo_csv.py
index 96724d0b1..1a500037d 100644
--- a/opentreemap/exporter/management/commands/create_photo_csv.py
+++ b/opentreemap/exporter/management/commands/create_photo_csv.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.management.base import BaseCommand
diff --git a/opentreemap/exporter/migrations/0001_initial.py b/opentreemap/exporter/migrations/0001_initial.py
index 1c7a042db..26a1fc119 100644
--- a/opentreemap/exporter/migrations/0001_initial.py
+++ b/opentreemap/exporter/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/exporter/migrations/0002_exportjob_status_choices_to_list.py b/opentreemap/exporter/migrations/0002_exportjob_status_choices_to_list.py
new file mode 100644
index 000000000..9adc20805
--- /dev/null
+++ b/opentreemap/exporter/migrations/0002_exportjob_status_choices_to_list.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.17 on 2020-01-08 19:01
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('exporter', '0001_initial'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='exportjob',
+ name='status',
+ field=models.IntegerField(choices=[(-1, 'Something went wrong with your export.'), (0, 'Pending'), (1, 'Query returned no trees or planting sites.'), (2, 'User has no permissions on this model'), (3, 'Ready')], default=0),
+ ),
+ ]
diff --git a/opentreemap/exporter/models.py b/opentreemap/exporter/models.py
index 35df2a1fe..9b515a89d 100644
--- a/opentreemap/exporter/models.py
+++ b/opentreemap/exporter/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import datetime
@@ -36,7 +34,7 @@ class ExportJob(models.Model):
instance = models.ForeignKey(Instance)
- status = models.IntegerField(choices=STATUS_CHOICES.items(),
+ status = models.IntegerField(choices=list(STATUS_CHOICES.items()),
default=PENDING)
user = models.ForeignKey(User, null=True, blank=True)
outfile = models.FileField(upload_to="exports/%Y/%m/%d")
diff --git a/opentreemap/exporter/tasks.py b/opentreemap/exporter/tasks.py
index 4f11d7c49..4f03a1b5e 100644
--- a/opentreemap/exporter/tasks.py
+++ b/opentreemap/exporter/tasks.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import csv
import logging
@@ -78,7 +76,7 @@ def _values_for_model(
if field_name.startswith('udf:'):
name = field_name[4:]
- if name in model_class.collection_udf_settings.keys():
+ if name in list(model_class.collection_udf_settings.keys()):
field_definition_id = None
for udfd in udf_defs(instance, model):
if udfd.iscollection and udfd.name == name:
@@ -146,7 +144,7 @@ def async_csv_export(job, model, query, display_filters):
filter(instance=instance))
values = _values_for_model(instance, job, 'treemap_species',
'Species', select, select_params)
- field_names = values + select.keys()
+ field_names = values + list(select.keys())
limited_qs = (initial_qs
.extra(select=select,
select_params=select_params)
@@ -198,7 +196,7 @@ def async_csv_export(job, model, query, display_filters):
limited_qs = (initial_qs
.extra(select=select,
select_params=select_params)
- .values(*field_header_map.keys()))
+ .values(*list(field_header_map.keys())))
else:
limited_qs = initial_qs.none()
@@ -213,7 +211,7 @@ def async_csv_export(job, model, query, display_filters):
else:
csv_file = TemporaryFile()
write_csv(limited_qs, csv_file,
- field_order=field_header_map.keys(),
+ field_order=list(field_header_map.keys()),
field_header_map=field_header_map,
field_serializer_map=field_serializer_map)
filename = generate_filename(limited_qs).replace('plot', 'tree')
@@ -289,7 +287,7 @@ def _csv_field_serializer_map(instance, field_names):
def make_serializer(factor, digits):
return lambda x: str(round(factor * x, digits))
- for name, details in convertable_fields.iteritems():
+ for name, details in convertable_fields.items():
model_name, field = details
factor = storage_to_instance_units_factor(instance,
model_name,
diff --git a/opentreemap/exporter/tests.py b/opentreemap/exporter/tests.py
index c4c134876..396f691f3 100644
--- a/opentreemap/exporter/tests.py
+++ b/opentreemap/exporter/tests.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import csv
import json
@@ -47,7 +45,7 @@ def assertCSVRowValue(self, csv_file, row_index, headers_and_values):
rows[0][0] = rows[0][0][3:]
self.assertTrue(len(rows) > 1)
- for (header, value) in headers_and_values.iteritems():
+ for (header, value) in headers_and_values.items():
target_column = rows[0].index(header)
self.assertEqual(value, rows[row_index][target_column])
@@ -79,7 +77,7 @@ def assertPsuedoAsyncTaskWorks(self, model,
request = make_request(user=user)
ctx = begin_export(request, self.instance, model)
- self.assertIn('job_id', ctx.keys())
+ self.assertIn('job_id', list(ctx.keys()))
self.assertEqual(ctx['start_status'], 'OK')
job_id = ctx['job_id']
@@ -91,7 +89,7 @@ def assertPsuedoAsyncTaskWorks(self, model,
self.assertIn('.csv', ctx['url'])
self.assertEqual(ctx['status'], 'COMPLETE')
- self.assertRegexpMatches(job.outfile.name, assertion_filename)
+ self.assertRegex(job.outfile.name, assertion_filename)
class ExportTreeTaskTest(AsyncCSVTestCase):
@@ -167,7 +165,7 @@ def test_psuedo_async_species_export(self):
class UserExportsTestCase(OTMTestCase):
def assertUserJSON(self, data, expectations):
- for key, expectation in expectations.items():
+ for key, expectation in list(expectations.items()):
value = data[key]
self.assertEqual(expectation, value,
"failure for key '%s': expected '%s', found '%s'"
@@ -218,16 +216,16 @@ def get_csv_data_with_base_assertions(self):
reader = csv.reader(resp)
# Skip BOM and entry line
- reader.next()
- reader.next()
+ next(reader)
+ next(reader)
- header = reader.next()
+ header = next(reader)
- data = [dict(zip(header, [x.decode('utf8') for x in row]))
+ data = [dict(list(zip(header, [x.decode('utf8') for x in row])))
for row in reader]
commander, user1data, user2data = data
- self.assertEquals(commander['username'], self.commander.username)
+ self.assertEqual(commander['username'], self.commander.username)
self.assertUserJSON(user1data,
{'username': self.user1.username,
'email': '',
@@ -252,7 +250,7 @@ def get_csv_data_with_base_assertions(self):
def test_export_users_csv_keep_info_private(self):
data = self.get_csv_data_with_base_assertions()
commander, user1data, user2data = data
- self.assertEquals(commander['username'], self.commander.username)
+ self.assertEqual(commander['username'], self.commander.username)
self.assertUserJSON(user1data,
{'first_name': '',
'last_name': '',
@@ -263,7 +261,7 @@ def test_export_users_csv_make_info_public(self):
self.user1.save()
data = self.get_csv_data_with_base_assertions()
commander, user1data, user2data = data
- self.assertEquals(commander['username'], self.commander.username)
+ self.assertEqual(commander['username'], self.commander.username)
self.assertUserJSON(user1data,
{'first_name': self.user1.first_name,
'last_name': self.user1.last_name,
@@ -287,8 +285,8 @@ def test_export_users_json_make_info_public(self):
commander, user1data, user2data = data
- self.assertEquals(commander['username'], self.commander.username)
- self.assertEquals(user1data.get('email'), None)
+ self.assertEqual(commander['username'], self.commander.username)
+ self.assertEqual(user1data.get('email'), None)
self.assertUserJSON(user1data,
{'username': self.user1.username,
'email_hash': self.user1.email_hash,
@@ -326,9 +324,9 @@ def test_min_edit_date(self):
data = json.loads(resp.content)
- self.assertEquals(len(data), 1)
+ self.assertEqual(len(data), 1)
- self.assertEquals(data[0]['username'], self.user2.username)
+ self.assertEqual(data[0]['username'], self.user2.username)
def test_min_join_date(self):
last_week = now() - datetime.timedelta(days=7)
@@ -353,9 +351,9 @@ def test_min_join_date(self):
data = json.loads(resp.content)
- self.assertEquals(len(data), 1)
+ self.assertEqual(len(data), 1)
- self.assertEquals(data[0]['username'], self.user2.username)
+ self.assertEqual(data[0]['username'], self.user2.username)
def test_min_join_date_validation(self):
with self.assertRaises(ValidationError):
diff --git a/opentreemap/exporter/urls.py b/opentreemap/exporter/urls.py
index ddeaa08f2..12321dda9 100644
--- a/opentreemap/exporter/urls.py
+++ b/opentreemap/exporter/urls.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/exporter/user.py b/opentreemap/exporter/user.py
index 41b54efaf..85902a99d 100644
--- a/opentreemap/exporter/user.py
+++ b/opentreemap/exporter/user.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import csv
import json
@@ -101,7 +99,7 @@ def _user_as_dict(user, instance):
last_edit = last_edits[0]
modeldata.update({'last_edit_%s' % k: v
- for (k, v) in last_edit.dict().iteritems()})
+ for (k, v) in last_edit.dict().items()})
return sanitize_unicode_record(modeldata)
diff --git a/opentreemap/exporter/util.py b/opentreemap/exporter/util.py
index 19291e2b3..4db204e25 100644
--- a/opentreemap/exporter/util.py
+++ b/opentreemap/exporter/util.py
@@ -1,12 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
def sanitize_unicode_value(value):
# make sure every text value is of type 'str', coercing unicode
- if isinstance(value, unicode):
+ if isinstance(value, str):
return value.encode("utf-8")
elif isinstance(value, str):
return value
@@ -19,7 +16,7 @@ def sanitize_unicode_value(value):
# master/djqscsv/djqscsv.py#L123
def sanitize_unicode_record(record):
obj = type(record)()
- for key, val in record.iteritems():
+ for key, val in record.items():
if val:
obj[sanitize_unicode_value(key)] = sanitize_unicode_value(val)
diff --git a/opentreemap/exporter/views.py b/opentreemap/exporter/views.py
index f3e0760fa..9f25982b5 100644
--- a/opentreemap/exporter/views.py
+++ b/opentreemap/exporter/views.py
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.http import Http404
from django.shortcuts import get_object_or_404
-from tasks import async_csv_export, async_users_export
+from .tasks import async_csv_export, async_users_export
from django_tinsel.utils import decorate as do
from django_tinsel.decorators import json_api_call
diff --git a/opentreemap/geocode/tests.py b/opentreemap/geocode/tests.py
index e7cca0474..6dc89cb62 100644
--- a/opentreemap/geocode/tests.py
+++ b/opentreemap/geocode/tests.py
@@ -1,11 +1,9 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import requests
import os
-from urllib import urlencode
+from urllib.parse import urlencode
from unittest import skipIf
from django.http import HttpResponse
diff --git a/opentreemap/geocode/urls.py b/opentreemap/geocode/urls.py
index b66fdbe70..67c3653cd 100644
--- a/opentreemap/geocode/urls.py
+++ b/opentreemap/geocode/urls.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
from geocode.views import geocode_view, get_esri_token_view
diff --git a/opentreemap/geocode/views.py b/opentreemap/geocode/views.py
index 8c2e32e04..2756ec36c 100644
--- a/opentreemap/geocode/views.py
+++ b/opentreemap/geocode/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
diff --git a/opentreemap/importer/errors.py b/opentreemap/importer/errors.py
index ee5b2e954..b9249ef8f 100644
--- a/opentreemap/importer/errors.py
+++ b/opentreemap/importer/errors.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.utils.translation import ugettext_lazy as _
diff --git a/opentreemap/importer/fields.py b/opentreemap/importer/fields.py
index 024e0f0d6..961e3f214 100644
--- a/opentreemap/importer/fields.py
+++ b/opentreemap/importer/fields.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.models import Species
@@ -169,7 +167,12 @@ class trees(object):
# TODO: READONLY restore when implemented
# Note: this is a tuple and not a set so it will be ordered in exports
- ALL = tuple([p[1] for p in EXPORTER_PAIRS if p[1] not in IGNORED])
+ # List comprehensions create a scope that does not have access to the
+ # previously defined class variables, so we use a lambda to bind the
+ # variables and make them available
+ # https://stackoverflow.com/a/13913933
+ ALL = (lambda IGNORED=IGNORED, EXPORTER_PAIRS=EXPORTER_PAIRS:
+ tuple([p[1] for p in EXPORTER_PAIRS if p[1] not in IGNORED]))()
def title_case(field_names):
diff --git a/opentreemap/importer/migrations/0001_initial.py b/opentreemap/importer/migrations/0001_initial.py
index 71fd66802..9552bd384 100644
--- a/opentreemap/importer/migrations/0001_initial.py
+++ b/opentreemap/importer/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/importer/migrations/0002_auto_20150630_1556.py b/opentreemap/importer/migrations/0002_auto_20150630_1556.py
index 4c2a159da..e41cb2593 100644
--- a/opentreemap/importer/migrations/0002_auto_20150630_1556.py
+++ b/opentreemap/importer/migrations/0002_auto_20150630_1556.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/importer/migrations/0003_add_lost_job_bookkeeping_fields.py b/opentreemap/importer/migrations/0003_add_lost_job_bookkeeping_fields.py
index 87385fbf2..55ec70490 100644
--- a/opentreemap/importer/migrations/0003_add_lost_job_bookkeeping_fields.py
+++ b/opentreemap/importer/migrations/0003_add_lost_job_bookkeeping_fields.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/importer/migrations/0004_make_new_fields_nonnullable.py b/opentreemap/importer/migrations/0004_make_new_fields_nonnullable.py
index 350a4a855..5287d182d 100644
--- a/opentreemap/importer/migrations/0004_make_new_fields_nonnullable.py
+++ b/opentreemap/importer/migrations/0004_make_new_fields_nonnullable.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/importer/migrations/0005_add_import_event_schema_version.py b/opentreemap/importer/migrations/0005_add_import_event_schema_version.py
index 25aeecac1..0e2b1eadc 100644
--- a/opentreemap/importer/migrations/0005_add_import_event_schema_version.py
+++ b/opentreemap/importer/migrations/0005_add_import_event_schema_version.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/importer/migrations/0006_add_index_to_tree_import_row.py b/opentreemap/importer/migrations/0006_add_index_to_tree_import_row.py
index b555d336c..ae6228142 100644
--- a/opentreemap/importer/migrations/0006_add_index_to_tree_import_row.py
+++ b/opentreemap/importer/migrations/0006_add_index_to_tree_import_row.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-28 16:30
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/importer/models/base.py b/opentreemap/importer/models/base.py
index eb67c7e2f..1cde1c5b8 100644
--- a/opentreemap/importer/models/base.py
+++ b/opentreemap/importer/models/base.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from datetime import datetime, timedelta
@@ -321,7 +319,7 @@ def append_error(self, err, fields, data=None):
# If you give append_error a single field
# there is no need to get angry
- if isinstance(fields, basestring):
+ if isinstance(fields, str):
fields = (fields,) # make into tuple
self.errors = json.dumps(
@@ -384,7 +382,7 @@ def safe_pos_float(self, fld):
return i
def convert_units(self, data, converts):
- for fld, factor in converts.iteritems():
+ for fld, factor in converts.items():
if fld in data and factor != 1.0:
data[fld] = float(data[fld]) * factor
diff --git a/opentreemap/importer/models/species.py b/opentreemap/importer/models/species.py
index 5578db69d..d3f721d66 100644
--- a/opentreemap/importer/models/species.py
+++ b/opentreemap/importer/models/species.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import itertools
@@ -122,7 +120,7 @@ def diff_from_species(self, species):
data = self.cleaned
diffs = {}
- for (model_key, row_key) in SpeciesImportRow.SPECIES_MAP.iteritems():
+ for (model_key, row_key) in SpeciesImportRow.SPECIES_MAP.items():
row_data = data.get(row_key, None)
model_data = getattr(species, model_key)
@@ -332,18 +330,18 @@ def _prepare_merge_data(self):
species = Species.objects.filter(pk__in=possible_matches)
diffs = [self.diff_from_species(s) for s in species]
- if all(diff.keys() == ['id'] for diff in diffs):
+ if all(list(diff.keys()) == ['id'] for diff in diffs):
# Imported data differs only in ID field (None vs. something)
identical_to_existing = True
self.merged = True
else:
# Filter out diffs whose "model value" is empty
- filtered_diffs = [{k: v for k, v in diff.iteritems()
+ filtered_diffs = [{k: v for k, v in diff.items()
if v[0] is not None and v[0] != ''}
for diff in diffs]
- diff_keys = [diff.keys() for diff in filtered_diffs]
+ diff_keys = [list(diff.keys()) for diff in filtered_diffs]
diff_keys = set(itertools.chain(*diff_keys))
diff_keys.remove('id')
@@ -392,7 +390,7 @@ def commit_row(self):
self.import_event.max_tree_height_conversion_factor
})
- for modelkey, datakey in SpeciesImportRow.SPECIES_MAP.iteritems():
+ for modelkey, datakey in SpeciesImportRow.SPECIES_MAP.items():
importdata = data.get(datakey, None)
if importdata is not None:
diff --git a/opentreemap/importer/models/trees.py b/opentreemap/importer/models/trees.py
index f01b750f7..4baca068f 100644
--- a/opentreemap/importer/models/trees.py
+++ b/opentreemap/importer/models/trees.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
@@ -207,7 +205,7 @@ def _import_value_to_udf_value(self, udf_def, value):
def _commit_plot_data(self, data, plot):
plot_edited = False
- for plot_attr, field_name in TreeImportRow.PLOT_MAP.iteritems():
+ for plot_attr, field_name in TreeImportRow.PLOT_MAP.items():
value = data.get(field_name, None)
if value:
plot_edited = True
@@ -228,7 +226,7 @@ def _commit_plot_data(self, data, plot):
plot.update_updated_fields(ie.owner)
def _commit_tree_data(self, data, plot, tree, tree_edited):
- for tree_attr, field_name in TreeImportRow.TREE_MAP.iteritems():
+ for tree_attr, field_name in TreeImportRow.TREE_MAP.items():
value = data.get(field_name, None)
if value:
tree_edited = True
@@ -434,7 +432,7 @@ def validate_user_defined_fields(self):
message = str(ve)
if isinstance(ve.message_dict, dict):
message = '\n'.join(
- [unicode(m) for m in ve.message_dict.values()])
+ [str(m) for m in list(ve.message_dict.values())])
self.append_error(
errors.INVALID_UDF_VALUE, column_name, message)
diff --git a/opentreemap/importer/routes.py b/opentreemap/importer/routes.py
index df814a8c7..a10c51136 100644
--- a/opentreemap/importer/routes.py
+++ b/opentreemap/importer/routes.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django_tinsel.utils import decorate as do
from django_tinsel.decorators import render_template, json_api_call
diff --git a/opentreemap/importer/tasks.py b/opentreemap/importer/tasks.py
index 5d7512615..a757c668c 100644
--- a/opentreemap/importer/tasks.py
+++ b/opentreemap/importer/tasks.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
@@ -54,7 +52,8 @@ def _create_rows(ie, reader):
for row in reader:
data = clean_row_data(row)
- if len(filter(None, data.values())) > 0: # skip blank rows
+ # check for truthiness to skip blank rows
+ if len([_f for _f in list(data.values()) if _f]) > 0:
data = json.dumps(data)
rows.append(RowModel(data=data, import_event=ie, idx=idx))
@@ -94,7 +93,7 @@ def run_import_event_validation(import_type, import_event_id, file_obj):
try:
validation_tasks = []
- for i in xrange(0, ie.row_count, settings.IMPORT_BATCH_SIZE):
+ for i in range(0, ie.row_count, settings.IMPORT_BATCH_SIZE):
validation_tasks.append(_validate_rows.s(import_type, ie.id, i))
final_task = _finalize_validation.si(import_type, import_event_id)
@@ -164,7 +163,7 @@ def commit_import_event(import_type, import_event_id):
commit_tasks = [
_commit_rows.s(import_type, import_event_id, i)
- for i in xrange(0, ie.row_count, settings.IMPORT_BATCH_SIZE)]
+ for i in range(0, ie.row_count, settings.IMPORT_BATCH_SIZE)]
finalize_task = _finalize_commit.si(import_type, import_event_id)
diff --git a/opentreemap/importer/tests.py b/opentreemap/importer/tests.py
index 070a7ad57..f199ae518 100644
--- a/opentreemap/importer/tests.py
+++ b/opentreemap/importer/tests.py
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
# flake8: noqa
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import tempfile
import csv
@@ -10,7 +8,7 @@
import psycopg2
from datetime import date
-from StringIO import StringIO
+from io import StringIO
from unittest.case import skip, skipIf
from django.conf import settings
@@ -204,7 +202,6 @@ def test_species_diameter_and_height(self):
self.assertHasError(i, errors.SPECIES_DBH_TOO_HIGH) # 15 > 12
self.assertNotHasError(i, errors.SPECIES_HEIGHT_TOO_HIGH) # 25 < 30
-
def test_proximity(self):
p1 = mkPlot(self.instance, self.user,
geom=Point(25.0000001, 25.0000001, srid=4326))
@@ -1022,7 +1019,7 @@ def extract_errors(self, json):
if 'errors' not in json:
return errors
- for k, v in json['errors'].iteritems():
+ for k, v in json['errors'].items():
errors[k] = []
for e in v:
d = e['data']
@@ -1251,7 +1248,6 @@ def test_faulty_data1(self):
self.assertEqual(ierrors['1'],
[(errors.INVALID_GEOM[0], gflds, None)])
-
self.assertNotIn('2', ierrors)
self.assertNotIn('3', ierrors)
self.assertEqual(ierrors['4'],
@@ -1322,7 +1318,6 @@ def test_no_files(self):
self.assertTrue(isinstance(response, HttpResponseBadRequest))
-
def test_unit_changes(self):
csv = ("| point x | point y | tree height | canopy height | "
"diameter | planting site width | planting site length |\n"
@@ -1498,7 +1493,6 @@ def test_override_with_opentreemap_id(self):
self.assertEqual(int(p1_geom.x*100), 4553)
self.assertEqual(int(p1_geom.y*100), 3109)
-
def test_import_updates_updated_at_fields(self):
original_creator = make_admin_user(self.instance, username='original_creator')
p1 = mkPlot(self.instance, original_creator)
@@ -1528,7 +1522,6 @@ def test_import_updates_updated_at_fields(self):
self.assertGreater(p1.updated_at, p1_original_updated_at)
self.assertGreater(t1.plot.updated_at, p2_original_updated_at)
-
def test_swap_locations_using_otm_id(self):
center = self.instance.center
self.assertEqual(3857, center.srid)
diff --git a/opentreemap/importer/urls.py b/opentreemap/importer/urls.py
index 5f6dca874..c08902b7d 100644
--- a/opentreemap/importer/urls.py
+++ b/opentreemap/importer/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/importer/util.py b/opentreemap/importer/util.py
index a76cae049..6dec73631 100644
--- a/opentreemap/importer/util.py
+++ b/opentreemap/importer/util.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import codecs
import csv
@@ -9,17 +7,17 @@
def _clean_string(s):
s = s.strip()
- if not isinstance(s, unicode):
- s = unicode(s, 'utf-8')
+ if not isinstance(s, str):
+ s = str(s, 'utf-8')
return s
def clean_row_data(h):
h2 = {}
- for (k, v) in h.iteritems():
+ for (k, v) in h.items():
k = clean_field_name(k)
if k != 'ignore':
- if isinstance(v, basestring):
+ if isinstance(v, str):
v = _clean_string(v)
h2[k] = v
diff --git a/opentreemap/importer/views.py b/opentreemap/importer/views.py
index b366d1cd7..f8d03dddb 100644
--- a/opentreemap/importer/views.py
+++ b/opentreemap/importer/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import io
@@ -80,7 +78,7 @@ def start_import(request, instance):
}
kwargs = {k: 1 / storage_to_instance_units_factor(instance, v[0], v[1])
- for (k, v) in factors.items()}
+ for (k, v) in list(factors.items())}
process_csv(request, instance, import_type, **kwargs)
@@ -260,7 +258,7 @@ def update_row(request, instance, import_type, row_id):
fields.trees.COMMON_NAME: species.common_name
})
- for k, v in request.POST.iteritems():
+ for k, v in request.POST.items():
if k in basedata:
basedata[k] = v
@@ -433,7 +431,7 @@ def _get_page(self, *args, **kwargs):
def _add_species_resolver_to_fields(collected_fields, row):
- species_error_fields = ((f, v) for f, v in collected_fields.items()
+ species_error_fields = ((f, v) for f, v in list(collected_fields.items())
if f in fields.trees.SPECIES_FIELDS
and v.get('css_class'))
@@ -706,7 +704,7 @@ def commit(request, instance, import_type, import_event_id):
def process_csv(request, instance, import_type, **kwargs):
files = request.FILES
- filename = files.keys()[0]
+ filename = list(files.keys())[0]
file_obj = files[filename]
file_obj = io.BytesIO(decode(file_obj.read()).encode('utf-8'))
@@ -754,7 +752,7 @@ def cancel(request, instance, import_type, import_event_id):
@queryset_as_exported_csv
def export_all_species(request, instance):
- field_names = SpeciesImportRow.SPECIES_MAP.keys()
+ field_names = list(SpeciesImportRow.SPECIES_MAP.keys())
field_names.remove('id')
return Species.objects.filter(instance_id=instance.id).values(*field_names)
diff --git a/opentreemap/manage.py b/opentreemap/manage.py
index f90f70aa9..6871f369b 100755
--- a/opentreemap/manage.py
+++ b/opentreemap/manage.py
@@ -1,4 +1,4 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3.7
import os
import sys
diff --git a/opentreemap/manage_treemap/migrations/0001_initial.py b/opentreemap/manage_treemap/migrations/0001_initial.py
index 2c2608e7d..97b812229 100644
--- a/opentreemap/manage_treemap/migrations/0001_initial.py
+++ b/opentreemap/manage_treemap/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
from django.conf import settings
diff --git a/opentreemap/manage_treemap/models.py b/opentreemap/manage_treemap/models.py
index 929adbf6d..6d2f7108f 100644
--- a/opentreemap/manage_treemap/models.py
+++ b/opentreemap/manage_treemap/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import random
import string
diff --git a/opentreemap/manage_treemap/routes.py b/opentreemap/manage_treemap/routes.py
index 0b22bd5e7..6dffd1bd7 100644
--- a/opentreemap/manage_treemap/routes.py
+++ b/opentreemap/manage_treemap/routes.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import division
-from __future__ import print_function
-from __future__ import unicode_literals
+
from functools import partial
diff --git a/opentreemap/manage_treemap/templatetags/is_current_view.py b/opentreemap/manage_treemap/templatetags/is_current_view.py
index a88a07ee2..41c3d6b15 100644
--- a/opentreemap/manage_treemap/templatetags/is_current_view.py
+++ b/opentreemap/manage_treemap/templatetags/is_current_view.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django import template
from django.core.urlresolvers import reverse
diff --git a/opentreemap/manage_treemap/tests/test_ecobenefits.py b/opentreemap/manage_treemap/tests/test_ecobenefits.py
index a8c3c8910..7a12dd88d 100644
--- a/opentreemap/manage_treemap/tests/test_ecobenefits.py
+++ b/opentreemap/manage_treemap/tests/test_ecobenefits.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import division
-from __future__ import print_function
-from __future__ import unicode_literals
+
import json
diff --git a/opentreemap/manage_treemap/tests/test_fields.py b/opentreemap/manage_treemap/tests/test_fields.py
index dc1c08387..0f7d42427 100644
--- a/opentreemap/manage_treemap/tests/test_fields.py
+++ b/opentreemap/manage_treemap/tests/test_fields.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import copy
diff --git a/opentreemap/manage_treemap/tests/test_general.py b/opentreemap/manage_treemap/tests/test_general.py
index 5515558df..6b0761c01 100644
--- a/opentreemap/manage_treemap/tests/test_general.py
+++ b/opentreemap/manage_treemap/tests/test_general.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import division
-from __future__ import print_function
-from __future__ import unicode_literals
+
import json
diff --git a/opentreemap/manage_treemap/tests/test_gsi.py b/opentreemap/manage_treemap/tests/test_gsi.py
index ce9bbbc7c..8e6874e17 100644
--- a/opentreemap/manage_treemap/tests/test_gsi.py
+++ b/opentreemap/manage_treemap/tests/test_gsi.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
diff --git a/opentreemap/manage_treemap/tests/test_instance_invitations.py b/opentreemap/manage_treemap/tests/test_instance_invitations.py
index f99326482..1832557be 100644
--- a/opentreemap/manage_treemap/tests/test_instance_invitations.py
+++ b/opentreemap/manage_treemap/tests/test_instance_invitations.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from registration.models import RegistrationProfile
@@ -71,7 +69,7 @@ def test_normal_registration_without_invite(self):
user = users[0]
self.assertFalse(user.is_active)
- self.assertEquals(len(InstanceUser.objects.filter(user=user)), 0)
+ self.assertEqual(len(InstanceUser.objects.filter(user=user)), 0)
success_url = rv.get_success_url(user)
self.assertEqual(success_url, 'registration_complete')
@@ -115,7 +113,7 @@ def assert_user_was_invited(self, view, new_user):
success_url, __, __ = view.get_success_url(new_user)
self.assertEqual(success_url, '/%s/map/' % self.instance.url_name)
- self.assertEquals(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
# Make sure we have some chars and the correct receivers
@@ -123,7 +121,7 @@ def assert_user_was_invited(self, view, new_user):
self.assertGreater(len(msg.body), 10)
to = set(msg.to)
expected_to = {self.user.email}
- self.assertEquals(to, expected_to)
+ self.assertEqual(to, expected_to)
# Disable plug-in function to ensure we are testing core behavior
@override_settings(INVITATION_ACCEPTED_NOTIFICATION_EMAILS=None)
@@ -154,10 +152,10 @@ def test_does_not_redirect_when_email_different(self):
# We should get an activation email, and no others, because the emails
# did not match
- self.assertEquals(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
- self.assertEquals(tuple(msg.to), (new_user.email,))
+ self.assertEqual(tuple(msg.to), (new_user.email,))
def test_does_not_redirect_when_key_does_not_match(self):
rv = self._invite_and_register("some@email.com", key_matches=False)
@@ -177,10 +175,10 @@ def test_does_not_redirect_when_key_does_not_match(self):
# We should get an activation email, and no others, because the emails
# did not match
- self.assertEquals(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1)
msg = mail.outbox[0]
- self.assertEquals(tuple(msg.to), (new_user.email,))
+ self.assertEqual(tuple(msg.to), (new_user.email,))
# Disable plug-in function to ensure we are testing core behavior
@override_settings(INVITATION_ACCEPTED_NOTIFICATION_EMAILS=None)
diff --git a/opentreemap/manage_treemap/tests/test_roles.py b/opentreemap/manage_treemap/tests/test_roles.py
index 36c5fef28..6e05a48a2 100644
--- a/opentreemap/manage_treemap/tests/test_roles.py
+++ b/opentreemap/manage_treemap/tests/test_roles.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
@@ -80,7 +78,7 @@ def test_add_user_to_instance(self):
self.assertGreater(len(msg.subject), 10)
self.assertGreater(len(msg.body), 10)
- self.assertEquals(tuple(msg.to), (self.user4.email,))
+ self.assertEqual(tuple(msg.to), (self.user4.email,))
def test_email_not_found_creates_invite(self):
self.assertEqual(InstanceInvitation.objects.count(), 0)
@@ -114,7 +112,7 @@ def test_email_not_found_creates_invite(self):
self.assertGreater(len(msg.subject), 10)
self.assertGreater(len(msg.body), 10)
- self.assertEquals(tuple(msg.to), (email,))
+ self.assertEqual(tuple(msg.to), (email,))
def test_invalid_email(self):
body = {'email': 'asdfasdf@'}
@@ -296,7 +294,7 @@ def test_model_assignment(self):
'MapFeaturePhoto.delete_bioswalephoto']
self.request_updates(
- dict(zip(permissions, [True] * len(permissions))))
+ dict(list(zip(permissions, [True] * len(permissions)))))
for existing in permissions:
__, codename = dotted_split(existing, 2, maxsplit=1)
diff --git a/opentreemap/manage_treemap/tests/test_udf.py b/opentreemap/manage_treemap/tests/test_udf.py
index 3c1df2247..9a599ae8f 100644
--- a/opentreemap/manage_treemap/tests/test_udf.py
+++ b/opentreemap/manage_treemap/tests/test_udf.py
@@ -1,6 +1,4 @@
-from __future__ import division
-from __future__ import print_function
-from __future__ import unicode_literals
+
import datetime
import json
@@ -52,7 +50,7 @@ def setUp(self):
def _make_put_request(self, params):
request = RequestFactory().put(
'does/not/matter/', json.dumps(params),
- content_type=u'application/json')
+ content_type='application/json')
request.method = 'PUT'
setattr(request, 'user', self.user)
setattr(request, 'instance', self.instance)
@@ -152,7 +150,7 @@ def test_cant_delete_stewardship(self):
self.instance.config['plot_stewardship_udf_id'] = self.cudf.pk
self.instance.save()
resp = udf_delete(make_request(), self.instance, self.cudf.pk)
- self.assertEquals(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400)
def test_delete_udf_deletes_perms(self):
body = {'udf.name': 'cool udf',
@@ -189,7 +187,7 @@ def test_delete_scalar_udf(self):
.exists())
resp = udf_delete(make_request(), self.instance, self.udf.pk)
- self.assertEquals(resp.status_code, 200)
+ self.assertEqual(resp.status_code, 200)
self.assertFalse(Audit.objects.filter(instance=self.instance)
.filter(model=self.udf.model_type)
@@ -214,7 +212,7 @@ def test_cant_delete_collection_udf(self):
.exists())
resp = udf_delete(make_request(), self.instance, self.cudf.pk)
- self.assertEquals(resp.status_code, 400)
+ self.assertEqual(resp.status_code, 400)
self.assertTrue(Audit.objects.filter(instance=self.instance)
.filter(model='udf:%s' % self.cudf.pk)
diff --git a/opentreemap/manage_treemap/tests/test_units.py b/opentreemap/manage_treemap/tests/test_units.py
index 7b3ad1cd0..86425cd5b 100644
--- a/opentreemap/manage_treemap/tests/test_units.py
+++ b/opentreemap/manage_treemap/tests/test_units.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.test.utils import override_settings
diff --git a/opentreemap/manage_treemap/urls.py b/opentreemap/manage_treemap/urls.py
index d93f802db..f6a76d746 100644
--- a/opentreemap/manage_treemap/urls.py
+++ b/opentreemap/manage_treemap/urls.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/manage_treemap/views/__init__.py b/opentreemap/manage_treemap/views/__init__.py
index 862bf5c43..b85bcd213 100644
--- a/opentreemap/manage_treemap/views/__init__.py
+++ b/opentreemap/manage_treemap/views/__init__.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.exceptions import ValidationError
@@ -31,7 +29,7 @@ def update_instance_fields(request, instance, validation_fn=None):
def _update_instance_fields(json_data, instance, validation_fn=None,
should_update_universal_rev=False):
error_dict = {}
- for identifier, value in json_data.iteritems():
+ for identifier, value in json_data.items():
model, field_name = dotted_split(identifier, 2, maxsplit=1)
obj = instance
@@ -55,7 +53,7 @@ def _update_instance_fields(json_data, instance, validation_fn=None,
if should_update_universal_rev:
instance.update_universal_rev()
return {'ok': True}
- except ValidationError, ve:
+ except ValidationError as ve:
validation_error = ve
raise ValidationError(package_field_errors('instance', validation_error))
diff --git a/opentreemap/manage_treemap/views/fields.py b/opentreemap/manage_treemap/views/fields.py
index 3ae6de250..f76b6c868 100644
--- a/opentreemap/manage_treemap/views/fields.py
+++ b/opentreemap/manage_treemap/views/fields.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
@@ -76,7 +74,7 @@ def set_search_config(request, instance):
search_fields = json_from_request(request)
for prop in ('search_config', 'mobile_search_fields'):
config = deepcopy(getattr(instance, prop))
- for key, val in search_fields[prop].iteritems():
+ for key, val in search_fields[prop].items():
config[key] = search_fields[prop][key]
setattr(instance, prop, config)
@@ -202,7 +200,7 @@ def field_context(identifier):
if ALERT_IDENTIFIER_PATTERN.match(identifier):
return get_alert_field_info(identifier, instance)
else:
- return set_search_field_label(instance, {'identifier': field_name})
+ return set_search_field_label(instance, {'identifier': identifier})
return [field_context(field_name) for field_name in field_names]
diff --git a/opentreemap/manage_treemap/views/green_infrastructure.py b/opentreemap/manage_treemap/views/green_infrastructure.py
index a2e14709a..506fbabbd 100644
--- a/opentreemap/manage_treemap/views/green_infrastructure.py
+++ b/opentreemap/manage_treemap/views/green_infrastructure.py
@@ -45,7 +45,8 @@ def _get_form_fields(defaults, thing):
return form_fields
terminology_fields = {thing: _get_form_fields(defaults, thing)
- for thing, defaults in REPLACEABLE_TERMS.items()}
+ for thing, defaults
+ in list(REPLACEABLE_TERMS.items())}
__, annual_rainfall_display_value = get_display_value(
instance, 'greenInfrastructure', 'rainfall',
@@ -165,7 +166,7 @@ def _map_feature_cross_validator(field_name, value, instance):
def _terminology_validator(field_name, value, instance):
- acceptable_terms = REPLACEABLE_TERMS.keys() + [
+ acceptable_terms = list(REPLACEABLE_TERMS.keys()) + [
Cls.__name__ for Cls in _get_replaceable_models(instance)]
__, terms, term, form = dotted_split(field_name, 4, maxsplit=3)
@@ -219,7 +220,7 @@ def _set_map_feature_config(field_name, value, instance):
def _validate_and_set_individual_values(json_data, instance, error_dict):
errors = None
INVALID_KEY_MESSAGE = _("An invalid key was sent in the request")
- for identifier, value in json_data.iteritems():
+ for identifier, value in json_data.items():
if not '.' in identifier:
error_dict[identifier] = [INVALID_KEY_MESSAGE]
__, field_name = dotted_split(identifier, 2, maxsplit=1)
@@ -251,7 +252,7 @@ def _validate_and_set_individual_values(json_data, instance, error_dict):
# mutates error_dict
def _cross_validate_values(json_data, instance, error_dict):
errors = None
- for identifier, value in json_data.iteritems():
+ for identifier, value in json_data.items():
__, field_name = dotted_split(identifier, 2, maxsplit=1)
if field_name in error_dict:
continue
@@ -268,7 +269,7 @@ def green_infrastructure(request, instance):
json_data = json_from_request(request)
new_data = {}
increment_universal_rev = False
- for identifier, value in json_data.iteritems():
+ for identifier, value in json_data.items():
model, field_name = dotted_split(identifier, 2, maxsplit=1)
if field_name.startswith('config.map_feature_types') or \
field_name.startswith('config.map_feature_config'):
diff --git a/opentreemap/manage_treemap/views/management.py b/opentreemap/manage_treemap/views/management.py
index b2225bac3..dba50364e 100644
--- a/opentreemap/manage_treemap/views/management.py
+++ b/opentreemap/manage_treemap/views/management.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import locale
import re
@@ -243,9 +241,9 @@ def benefits_convs(request, instance):
pfx = ('' +
conv.currency_symbol + ' ')
- for group_title, fields in field_groups.iteritems():
+ for group_title, fields in field_groups.items():
fields_with_pfx = [((pfx + label), value)
- for label, value in fields.iteritems()]
+ for label, value in fields.items()]
field_groups[group_title] = fields_with_pfx
return {'benefitCurrencyConversion': conv,
@@ -271,7 +269,7 @@ def update_benefits(request, instance):
updated_values = json_from_request(request)
- for field, value in updated_values.iteritems():
+ for field, value in updated_values.items():
if field in valid_fields:
field_part = dotted_split(field, 2)[1]
setattr(conv, field_part, value)
diff --git a/opentreemap/manage_treemap/views/photo.py b/opentreemap/manage_treemap/views/photo.py
index 655dc9d16..64178bf4e 100644
--- a/opentreemap/manage_treemap/views/photo.py
+++ b/opentreemap/manage_treemap/views/photo.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.paginator import Paginator, EmptyPage
from django.db import transaction
diff --git a/opentreemap/manage_treemap/views/roles.py b/opentreemap/manage_treemap/views/roles.py
index 24c38719b..872b0d4dd 100644
--- a/opentreemap/manage_treemap/views/roles.py
+++ b/opentreemap/manage_treemap/views/roles.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
@@ -23,6 +21,7 @@
from treemap.plugin import get_instance_permission_spec
from manage_treemap.views import remove_udf_notification
+from functools import reduce
WRITE_PERM = (_('Full Write Access'),
@@ -70,19 +69,19 @@ def _update_perms_from_object(role_perms, instance):
roles_by_id = {role.pk:
role for role in Role.objects.filter(instance=instance)}
field_perms = {(role, perm.full_name): perm
- for role in roles_by_id.itervalues()
+ for role in roles_by_id.values()
for perm in deepcopy(role_field_permissions(role))}
- input_role_ids = [int(role_id) for role_id in role_perms.iterkeys()]
+ input_role_ids = [int(role_id) for role_id in role_perms.keys()]
for role_id in input_role_ids:
if role_id not in roles_by_id:
raise ValidationError("Unrecognized role id [%s]" % role_id)
input_roles = [roles_by_id[role_id] for role_id in input_role_ids]
- input_role_fields = zip(input_roles, [
- role_inputs['fields'] for role_inputs in role_perms.itervalues()])
- input_role_models = zip(input_roles, [
- role_inputs['models'] for role_inputs in role_perms.itervalues()])
+ input_role_fields = list(zip(input_roles, [
+ role_inputs['fields'] for role_inputs in role_perms.values()]))
+ input_role_models = list(zip(input_roles, [
+ role_inputs['models'] for role_inputs in role_perms.values()]))
def validate_model_name(model_name, valid_names):
if model_name not in valid_names:
@@ -91,7 +90,7 @@ def validate_model_name(model_name, valid_names):
(", ".join(valid_names), model_name))
def validate_and_save_field_perm(role, field_perm):
- for model_field_name, perm_type in field_perm.iteritems():
+ for model_field_name, perm_type in field_perm.items():
model_name, field_name = dotted_split(model_field_name, 2)
validate_model_name(model_name, valid_field_model_names)
@@ -145,7 +144,7 @@ def validate_permission_assignment(codename, should_be_assigned, Model):
def validate_and_save_model_perm(role, model_perm):
unassign = []
- for model_perm_name, should_be_assigned in model_perm.iteritems():
+ for model_perm_name, should_be_assigned in model_perm.items():
model_name, codename = dotted_split(model_perm_name, 2)
validate_model_name(
model_name, set(valid_perm_models_by_name.keys()))
@@ -235,8 +234,8 @@ def get_role_photo_perms(role, Model):
def get_instance_perms(roles):
def translated(spec):
- return {k: unicode(v) if isinstance(v, Promise) else v
- for k, v in spec.iteritems()}
+ return {k: str(v) if isinstance(v, Promise) else v
+ for k, v in spec.items()}
def combine(base_dict, additional_dict):
combination = deepcopy(base_dict)
@@ -263,13 +262,16 @@ def combine(base_dict, additional_dict):
for spec in specs]
def role_field_perms(Model):
- return zip(*[get_field_perms(role, Model) for role in roles])
+ return list(
+ zip(*[get_field_perms(role, Model) for role in roles]))
def role_model_perms(Model):
- return zip(*[get_role_model_perms(role, Model) for role in roles])
+ return list(
+ zip(*[get_role_model_perms(role, Model) for role in roles]))
def role_photo_perms(Model):
- return zip(*[get_role_photo_perms(role, Model) for role in roles])
+ return list(
+ zip(*[get_role_photo_perms(role, Model) for role in roles]))
groups = [{
'role_model_perms': role_model_perms(Model),
diff --git a/opentreemap/manage_treemap/views/udf.py b/opentreemap/manage_treemap/views/udf.py
index d2474f73c..70082ce45 100644
--- a/opentreemap/manage_treemap/views/udf.py
+++ b/opentreemap/manage_treemap/views/udf.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
@@ -66,7 +64,7 @@ def udf_bulk_update(request, instance):
choice_map = {int(param['id']): param['changes']
for param in choice_changes}
udfds = [udf for udf in udf_defs(instance)
- if udf.pk in choice_map.keys()]
+ if udf.pk in list(choice_map.keys())]
# Update one at a time rather than doing bulk_update.
# There won't be that many of them, and we need to go through
diff --git a/opentreemap/manage_treemap/views/user_roles.py b/opentreemap/manage_treemap/views/user_roles.py
index b801cbcf6..d6db7018d 100644
--- a/opentreemap/manage_treemap/views/user_roles.py
+++ b/opentreemap/manage_treemap/views/user_roles.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.paginator import Paginator, EmptyPage
@@ -34,7 +32,7 @@ def _extract_role_updates(post):
mapping them to the values
"""
updates = {}
- for key, value in post.iteritems():
+ for key, value in post.items():
if key.startswith("iuser_") and key.endswith("_role"):
iuser_id = key[6:-5]
updates[iuser_id] = value
@@ -190,7 +188,7 @@ def update_user_roles(request, instance):
(InstanceInvitation, 'invites')):
updates = role_updates.get(key, {})
- for pk, updated_info in updates.iteritems():
+ for pk, updated_info in updates.items():
model = Model.objects.get(pk=pk)
updated_role = int(updated_info.get('role', model.role_id))
diff --git a/opentreemap/modeling/migrations/0001_initial.py b/opentreemap/modeling/migrations/0001_initial.py
index 8489fe40b..f8ccc61c0 100644
--- a/opentreemap/modeling/migrations/0001_initial.py
+++ b/opentreemap/modeling/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/modeling/migrations/0002_remove_plan_currentscenarioid.py b/opentreemap/modeling/migrations/0002_remove_plan_currentscenarioid.py
index 13c759551..3bd3338aa 100644
--- a/opentreemap/modeling/migrations/0002_remove_plan_currentscenarioid.py
+++ b/opentreemap/modeling/migrations/0002_remove_plan_currentscenarioid.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/modeling/migrations/0003_plan_zoom_lat_lng.py b/opentreemap/modeling/migrations/0003_plan_zoom_lat_lng.py
index ab758bab3..76f4238d9 100644
--- a/opentreemap/modeling/migrations/0003_plan_zoom_lat_lng.py
+++ b/opentreemap/modeling/migrations/0003_plan_zoom_lat_lng.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
import treemap.json_field
diff --git a/opentreemap/modeling/migrations/0004_plan_revision.py b/opentreemap/modeling/migrations/0004_plan_revision.py
index b5588dc95..73188912e 100644
--- a/opentreemap/modeling/migrations/0004_plan_revision.py
+++ b/opentreemap/modeling/migrations/0004_plan_revision.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/modeling/models.py b/opentreemap/modeling/models.py
index 977fa28a0..b27c94aab 100644
--- a/opentreemap/modeling/models.py
+++ b/opentreemap/modeling/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.db import models
from django.core.exceptions import ValidationError
@@ -37,7 +35,7 @@ def to_json(self):
}
def update(self, plan_dict):
- for key, value in plan_dict.iteritems():
+ for key, value in plan_dict.items():
if key in ('revision', 'name', 'description', 'is_published',
'scenarios', 'zoom_lat_lng'):
setattr(self, key, value)
diff --git a/opentreemap/modeling/run_model/GrowthAndMortalityModel.py b/opentreemap/modeling/run_model/GrowthAndMortalityModel.py
index 5d46b5e60..8a5ec63c7 100644
--- a/opentreemap/modeling/run_model/GrowthAndMortalityModel.py
+++ b/opentreemap/modeling/run_model/GrowthAndMortalityModel.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import random
from copy import copy
diff --git a/opentreemap/modeling/run_model/GrowthModelUrbanTreeDatabase.py b/opentreemap/modeling/run_model/GrowthModelUrbanTreeDatabase.py
index 4a9ed7dea..728a87f3c 100644
--- a/opentreemap/modeling/run_model/GrowthModelUrbanTreeDatabase.py
+++ b/opentreemap/modeling/run_model/GrowthModelUrbanTreeDatabase.py
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
# flake8: noqa
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
from operator import itemgetter
@@ -99,7 +97,7 @@ def _get_species_for_planting(instance):
return []
itree_region = itree_regions[0]
- otm_codes = _growth_data[itree_region.code].keys()
+ otm_codes = list(_growth_data[itree_region.code].keys())
species = [species_for_otm_code(otm_code) for otm_code in otm_codes]
species = sorted(species, key=itemgetter('common_name'))
@@ -136,7 +134,6 @@ def bisect(f, x_lo, x_hi, y_target, max_iterations, tolerance):
raise Exception("Max iterations exceeded")
-
# Growth functions from TS4_Growth_eqn_forms.csv
# Note that 'mse' is 'mean-squared-error', which is listed in column 'c' of
# TS6_Growth_coefficients.csv
diff --git a/opentreemap/modeling/run_model/MortalityModelUrbanTreeDatabase.py b/opentreemap/modeling/run_model/MortalityModelUrbanTreeDatabase.py
index 5daa5eced..283e5db3c 100644
--- a/opentreemap/modeling/run_model/MortalityModelUrbanTreeDatabase.py
+++ b/opentreemap/modeling/run_model/MortalityModelUrbanTreeDatabase.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
from random import random
@@ -82,7 +80,7 @@ def init_tree(self, tree):
def kill_trees(self, trees, remainders):
categories = self._categorize(trees)
new_remainders = {}
- for key, c in categories.iteritems():
+ for key, c in categories.items():
remainder = remainders.get(key, 0)
float_to_kill = c.mortality * len(c.trees) + remainder
int_to_kill = int(round(float_to_kill))
diff --git a/opentreemap/modeling/run_model/Tree.py b/opentreemap/modeling/run_model/Tree.py
index f6f622f27..83bbe669a 100644
--- a/opentreemap/modeling/run_model/Tree.py
+++ b/opentreemap/modeling/run_model/Tree.py
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
class Tree(object):
diff --git a/opentreemap/modeling/run_model/schema_helpers.py b/opentreemap/modeling/run_model/schema_helpers.py
index 0dfdf5a1b..0b9ced22c 100644
--- a/opentreemap/modeling/run_model/schema_helpers.py
+++ b/opentreemap/modeling/run_model/schema_helpers.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
# Helpers for building a JSON schema
@@ -18,8 +16,9 @@ def obj(properties, optional_properties={}):
return {
'type': 'object',
'additionalProperties': False,
- 'required': properties.keys(),
- 'properties': dict(properties.items() + optional_properties.items())
+ 'required': list(properties.keys()),
+ 'properties':
+ dict(list(properties.items()) + list(optional_properties.items()))
}
diff --git a/opentreemap/modeling/tests.py b/opentreemap/modeling/tests.py
index ade817c9b..fa65186a0 100644
--- a/opentreemap/modeling/tests.py
+++ b/opentreemap/modeling/tests.py
@@ -59,7 +59,7 @@ def _delete_plan(self, user):
delete_plan(request, self.instance, self.plan_id)
def _assert_plans_match(self, spec, result):
- for key, value in spec.iteritems():
+ for key, value in spec.items():
self.assertEqual(value, result[key],
"Mismatch in plan field '%s'" % key)
@@ -207,7 +207,7 @@ def run_model(self, expected_n_trees=1, expected_n_years=1):
class TestBisect(SimpleTestCase):
def setUp(self):
- self.choices = range(10)
+ self.choices = list(range(10))
self.identity = lambda n: n
self.tolerance = 0
self.max_iterations = 15
diff --git a/opentreemap/modeling/urls.py b/opentreemap/modeling/urls.py
index 06ece43c9..4741d349c 100644
--- a/opentreemap/modeling/urls.py
+++ b/opentreemap/modeling/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/modeling/views.py b/opentreemap/modeling/views.py
index bee6a33b9..a13f29018 100644
--- a/opentreemap/modeling/views.py
+++ b/opentreemap/modeling/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.core.exceptions import PermissionDenied
diff --git a/opentreemap/opentreemap/__init__.py b/opentreemap/opentreemap/__init__.py
index ae51bd34f..648edb358 100644
--- a/opentreemap/opentreemap/__init__.py
+++ b/opentreemap/opentreemap/__init__.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import, unicode_literals
+
from .celery import app as celery_app # NOQA
diff --git a/opentreemap/opentreemap/celery.py b/opentreemap/opentreemap/celery.py
index 16a317f02..c839eb328 100644
--- a/opentreemap/opentreemap/celery.py
+++ b/opentreemap/opentreemap/celery.py
@@ -1,4 +1,4 @@
-from __future__ import absolute_import
+
import os
diff --git a/opentreemap/opentreemap/context_processors.py b/opentreemap/opentreemap/context_processors.py
index a48764aaa..0e595b7ea 100644
--- a/opentreemap/opentreemap/context_processors.py
+++ b/opentreemap/opentreemap/context_processors.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import copy
from datetime import datetime
diff --git a/opentreemap/opentreemap/urls.py b/opentreemap/opentreemap/urls.py
index e94ea4f8c..95742616c 100644
--- a/opentreemap/opentreemap/urls.py
+++ b/opentreemap/opentreemap/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.conf.urls import include, url
diff --git a/opentreemap/opentreemap/util.py b/opentreemap/opentreemap/util.py
index 8558f4851..56d0bfb04 100644
--- a/opentreemap/opentreemap/util.py
+++ b/opentreemap/opentreemap/util.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import logging
@@ -129,7 +127,7 @@ def extent_as_json(extent):
def extent_intersection(*extents):
- extents = zip(*extents)
+ extents = list(zip(*extents))
xmins, ymins, xmaxes, ymaxes = extents
return (max(xmins), max(ymins), min(xmaxes), min(ymaxes))
diff --git a/opentreemap/otm1_migrator/data_util.py b/opentreemap/otm1_migrator/data_util.py
index 29d623c44..17e907e97 100644
--- a/opentreemap/otm1_migrator/data_util.py
+++ b/opentreemap/otm1_migrator/data_util.py
@@ -71,7 +71,7 @@ def dict_to_model(config, model_name, data_dict, instance):
for field in (common_fields
.union(renamed_fields)
- .union(dependency_fields.values())):
+ .union(list(dependency_fields.values()))):
transform_fn = (config[model_name]
.get('value_transformers', {})
.get(field, None))
@@ -85,7 +85,7 @@ def dict_to_model(config, model_name, data_dict, instance):
model.udfs[transformed_field[4:]] = transformed_value
else:
suffix = ('_id'
- if transformed_field in dependency_fields.values()
+ if transformed_field in list(dependency_fields.values())
else '')
setattr(model, transformed_field + suffix, transformed_value)
@@ -128,7 +128,7 @@ def add_udfs_to_migration_rules(migration_rules, udfs, instance):
model_rules = migration_rules[model]
model_rules['removed_fields'] -= set(udfs[model].keys())
- for field, field_rules in udfs[model].items():
+ for field, field_rules in list(udfs[model].items()):
prefixed = 'udf:' + field_rules['udf.name']
model_rules['renamed_fields'][field] = prefixed
@@ -143,8 +143,8 @@ def add_udfs_to_migration_rules(migration_rules, udfs, instance):
def create_udfs(udfs, instance):
- for model, model_rules in udfs.items():
- for field, field_rules in model_rules.items():
+ for model, model_rules in list(udfs.items()):
+ for field, field_rules in list(model_rules.items()):
# convert the migrator udf schema
# to the udf-lib friendly schema
@@ -162,7 +162,7 @@ def create_udfs(udfs, instance):
}
if not udf_lib.udf_exists(udf_params, instance):
- print "Creating udf %s" % name
+ print("Creating udf %s" % name)
udf_lib.udf_create(udf_params, instance)
diff --git a/opentreemap/otm1_migrator/management/commands/perform_migration.py b/opentreemap/otm1_migrator/management/commands/perform_migration.py
index 5ead6598f..e408b64fb 100644
--- a/opentreemap/otm1_migrator/management/commands/perform_migration.py
+++ b/opentreemap/otm1_migrator/management/commands/perform_migration.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import os
import importlib
@@ -48,10 +46,9 @@ def save_objects(migration_rules, model_name, model_dicts, relic_ids,
if dict['pk'] not in model_key_map)
for model_dict in dicts_to_save:
- dependencies = (migration_rules
+ dependencies = (list(migration_rules
.get(model_name, {})
- .get('dependencies', {})
- .items())
+ .get('dependencies', {}).items()))
old_model_dict = model_dict.copy()
old_model_dict['fields'] = model_dict['fields'].copy()
@@ -145,7 +142,7 @@ def handle(self, *args, **options):
if options['config_file']:
config_data = json.load(open(options['config_file'], 'r'))
- for k, v in config_data.items():
+ for k, v in list(config_data.items()):
if not options.get(k, None):
options[k] = v
diff --git a/opentreemap/otm1_migrator/management/commands/post_migrate_validation.py b/opentreemap/otm1_migrator/management/commands/post_migrate_validation.py
index 1f9b660cc..7c6b54035 100644
--- a/opentreemap/otm1_migrator/management/commands/post_migrate_validation.py
+++ b/opentreemap/otm1_migrator/management/commands/post_migrate_validation.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
diff --git a/opentreemap/otm1_migrator/migration_rules/tampa.py b/opentreemap/otm1_migrator/migration_rules/tampa.py
index ff032869d..77b65b07b 100644
--- a/opentreemap/otm1_migrator/migration_rules/tampa.py
+++ b/opentreemap/otm1_migrator/migration_rules/tampa.py
@@ -62,9 +62,9 @@ def create_override(species_obj, species_dict):
itree_code = species_dict['fields'].get('itree_code', None)
if not itree_code:
sci_name = species_dict['fields'].get('scientific_name', '').lower()
- print('No itree_code for "%d: %s"' % (species_dict['pk'], sci_name))
+ print(('No itree_code for "%d: %s"' % (species_dict['pk'], sci_name)))
itree_code = meta_species.get(sci_name, '')
- print('Looked up meta species "%s"' % itree_code)
+ print(('Looked up meta species "%s"' % itree_code))
override = ITreeCodeOverride(
instance_species_id=species_obj.pk,
region=ITreeRegion.objects.get(code=TAMPA_ITREE_REGION_CODE),
diff --git a/opentreemap/otm1_migrator/migrations/0001_initial.py b/opentreemap/otm1_migrator/migrations/0001_initial.py
index ba310284a..57320c953 100644
--- a/opentreemap/otm1_migrator/migrations/0001_initial.py
+++ b/opentreemap/otm1_migrator/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/otm1_migrator/migrations/0002_auto_20150630_1556.py b/opentreemap/otm1_migrator/migrations/0002_auto_20150630_1556.py
index 79aa14a21..38ba48166 100644
--- a/opentreemap/otm1_migrator/migrations/0002_auto_20150630_1556.py
+++ b/opentreemap/otm1_migrator/migrations/0002_auto_20150630_1556.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/otm1_migrator/model_processors.py b/opentreemap/otm1_migrator/model_processors.py
index 47aa21d71..e6b4d65b8 100644
--- a/opentreemap/otm1_migrator/model_processors.py
+++ b/opentreemap/otm1_migrator/model_processors.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import os
import pytz
diff --git a/opentreemap/otm1_migrator/models.py b/opentreemap/otm1_migrator/models.py
index 65d5914c8..b7c97e1bf 100644
--- a/opentreemap/otm1_migrator/models.py
+++ b/opentreemap/otm1_migrator/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.exceptions import MultipleObjectsReturned
diff --git a/opentreemap/otm1_migrator/tests.py b/opentreemap/otm1_migrator/tests.py
index 26c0fca4c..19a1d7c2a 100644
--- a/opentreemap/otm1_migrator/tests.py
+++ b/opentreemap/otm1_migrator/tests.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from copy import copy
diff --git a/opentreemap/otm1_migrator/views.py b/opentreemap/otm1_migrator/views.py
index e434f1c9e..01c03573b 100644
--- a/opentreemap/otm1_migrator/views.py
+++ b/opentreemap/otm1_migrator/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import csv
@@ -10,7 +8,7 @@
from treemap.util import get_csv_response
from treemap.models import User
-from models import OTM1UserRelic
+from .models import OTM1UserRelic
# assumptions:
# * there are n userrelics and m users, such that n >= m
diff --git a/opentreemap/otm_comments/__init__.py b/opentreemap/otm_comments/__init__.py
index b6a6aa870..b0795e0cf 100644
--- a/opentreemap/otm_comments/__init__.py
+++ b/opentreemap/otm_comments/__init__.py
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
# The contrib.comments app will load whichever app is specified in the settings
diff --git a/opentreemap/otm_comments/forms.py b/opentreemap/otm_comments/forms.py
index 4b005cae3..83c73b28a 100644
--- a/opentreemap/otm_comments/forms.py
+++ b/opentreemap/otm_comments/forms.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from threadedcomments.forms import ThreadedCommentForm
diff --git a/opentreemap/otm_comments/migrations/0001_initial.py b/opentreemap/otm_comments/migrations/0001_initial.py
index 28abb58b7..198d65abe 100644
--- a/opentreemap/otm_comments/migrations/0001_initial.py
+++ b/opentreemap/otm_comments/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
import treemap.audit
diff --git a/opentreemap/otm_comments/migrations/0002_auto_20150630_1556.py b/opentreemap/otm_comments/migrations/0002_auto_20150630_1556.py
index ae1bdac14..547b0dc55 100644
--- a/opentreemap/otm_comments/migrations/0002_auto_20150630_1556.py
+++ b/opentreemap/otm_comments/migrations/0002_auto_20150630_1556.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/otm_comments/migrations/0003_auto_20160923_1413.py b/opentreemap/otm_comments/migrations/0003_auto_20160923_1413.py
index da9a256d3..b5db494d9 100644
--- a/opentreemap/otm_comments/migrations/0003_auto_20160923_1413.py
+++ b/opentreemap/otm_comments/migrations/0003_auto_20160923_1413.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/otm_comments/migrations/0004_auto_20170907_0937.py b/opentreemap/otm_comments/migrations/0004_auto_20170907_0937.py
index 020d51e6b..b563a28e6 100644
--- a/opentreemap/otm_comments/migrations/0004_auto_20170907_0937.py
+++ b/opentreemap/otm_comments/migrations/0004_auto_20170907_0937.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-07 14:37
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/otm_comments/models.py b/opentreemap/otm_comments/models.py
index 6684053bf..3dadf33b5 100644
--- a/opentreemap/otm_comments/models.py
+++ b/opentreemap/otm_comments/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from threadedcomments.models import ThreadedComment
diff --git a/opentreemap/otm_comments/tests.py b/opentreemap/otm_comments/tests.py
index 829a20083..0047f6c18 100644
--- a/opentreemap/otm_comments/tests.py
+++ b/opentreemap/otm_comments/tests.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from datetime import datetime, timedelta
diff --git a/opentreemap/otm_comments/uitests.py b/opentreemap/otm_comments/uitests.py
index 86e672452..5fc4eb5ca 100644
--- a/opentreemap/otm_comments/uitests.py
+++ b/opentreemap/otm_comments/uitests.py
@@ -1,8 +1,6 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from time import sleep
diff --git a/opentreemap/otm_comments/urls.py b/opentreemap/otm_comments/urls.py
index 0465a37de..609b036f8 100644
--- a/opentreemap/otm_comments/urls.py
+++ b/opentreemap/otm_comments/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/otm_comments/views.py b/opentreemap/otm_comments/views.py
index a868e7cd5..3456e8a22 100644
--- a/opentreemap/otm_comments/views.py
+++ b/opentreemap/otm_comments/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from functools import partial
diff --git a/opentreemap/registration_backend/urls.py b/opentreemap/registration_backend/urls.py
index 5f3958b07..0917f8d88 100644
--- a/opentreemap/registration_backend/urls.py
+++ b/opentreemap/registration_backend/urls.py
@@ -4,8 +4,8 @@
from django.views.generic.base import TemplateView
-from views import (RegistrationView, ActivationView, LoginForm,
- PasswordResetView)
+from .views import (RegistrationView, ActivationView, LoginForm,
+ PasswordResetView)
urlpatterns = [
diff --git a/opentreemap/registration_backend/views.py b/opentreemap/registration_backend/views.py
index 30c977263..7ca876022 100644
--- a/opentreemap/registration_backend/views.py
+++ b/opentreemap/registration_backend/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django import forms
from django.core.exceptions import ValidationError
@@ -32,7 +30,7 @@ class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
- for field_name, field in self.fields.items():
+ for field_name, field in list(self.fields.items()):
field.widget.attrs['class'] = 'input-xlarge form-control'
@@ -74,7 +72,7 @@ def __init__(self, *args, **kwargs):
self.fields['email'].label = _('Email')
self.fields['password2'].label = _('Confirm Password')
- for field_name, field in self.fields.items():
+ for field_name, field in list(self.fields.items()):
if not isinstance(field, forms.BooleanField):
field.widget.attrs['class'] = 'form-control'
diff --git a/opentreemap/stormwater/benefits.py b/opentreemap/stormwater/benefits.py
index 21fb4afd6..aa59666b9 100644
--- a/opentreemap/stormwater/benefits.py
+++ b/opentreemap/stormwater/benefits.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.db.models import Sum
from django.utils.translation import ugettext_lazy as _
diff --git a/opentreemap/stormwater/migrations/0001_initial.py b/opentreemap/stormwater/migrations/0001_initial.py
index 2f66cada4..323b8dc5d 100644
--- a/opentreemap/stormwater/migrations/0001_initial.py
+++ b/opentreemap/stormwater/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
import django.contrib.gis.db.models.fields
diff --git a/opentreemap/stormwater/migrations/0002_raingarden.py b/opentreemap/stormwater/migrations/0002_raingarden.py
index ba1789614..d2b40b624 100644
--- a/opentreemap/stormwater/migrations/0002_raingarden.py
+++ b/opentreemap/stormwater/migrations/0002_raingarden.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/stormwater/migrations/0003_rainbarrel.py b/opentreemap/stormwater/migrations/0003_rainbarrel.py
index c43ed9195..9f6c13498 100644
--- a/opentreemap/stormwater/migrations/0003_rainbarrel.py
+++ b/opentreemap/stormwater/migrations/0003_rainbarrel.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/stormwater/migrations/0004_auto_20151021_1600.py b/opentreemap/stormwater/migrations/0004_auto_20151021_1600.py
index 305b6921d..235632388 100644
--- a/opentreemap/stormwater/migrations/0004_auto_20151021_1600.py
+++ b/opentreemap/stormwater/migrations/0004_auto_20151021_1600.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/stormwater/migrations/0005_help_text_to_verbose_name.py b/opentreemap/stormwater/migrations/0005_help_text_to_verbose_name.py
index 404de2764..c1a8cdefb 100644
--- a/opentreemap/stormwater/migrations/0005_help_text_to_verbose_name.py
+++ b/opentreemap/stormwater/migrations/0005_help_text_to_verbose_name.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/stormwater/migrations/0006_stormwater_drainage_area.py b/opentreemap/stormwater/migrations/0006_stormwater_drainage_area.py
index 90cc108e6..93861db6a 100644
--- a/opentreemap/stormwater/migrations/0006_stormwater_drainage_area.py
+++ b/opentreemap/stormwater/migrations/0006_stormwater_drainage_area.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/stormwater/migrations/0007_drainage_area_permissions.py b/opentreemap/stormwater/migrations/0007_drainage_area_permissions.py
index 0d82c0b65..d14ccbeab 100644
--- a/opentreemap/stormwater/migrations/0007_drainage_area_permissions.py
+++ b/opentreemap/stormwater/migrations/0007_drainage_area_permissions.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
from django.db.models import F
diff --git a/opentreemap/stormwater/migrations/0008_benefits-calc-cache-flush.py b/opentreemap/stormwater/migrations/0008_benefits-calc-cache-flush.py
index 728234197..6f9001830 100644
--- a/opentreemap/stormwater/migrations/0008_benefits-calc-cache-flush.py
+++ b/opentreemap/stormwater/migrations/0008_benefits-calc-cache-flush.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
from django.db.models import F
diff --git a/opentreemap/stormwater/migrations/0009_drainage_area_imperial_units.py b/opentreemap/stormwater/migrations/0009_drainage_area_imperial_units.py
index 13d6257e2..2b4b53c3a 100644
--- a/opentreemap/stormwater/migrations/0009_drainage_area_imperial_units.py
+++ b/opentreemap/stormwater/migrations/0009_drainage_area_imperial_units.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
from django.db.models import F
diff --git a/opentreemap/stormwater/migrations/0010_stormwater_blank_true.py b/opentreemap/stormwater/migrations/0010_stormwater_blank_true.py
index 529d440e5..7125ac49e 100644
--- a/opentreemap/stormwater/migrations/0010_stormwater_blank_true.py
+++ b/opentreemap/stormwater/migrations/0010_stormwater_blank_true.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/stormwater/models.py b/opentreemap/stormwater/models.py
index d3a753934..2f2c57102 100644
--- a/opentreemap/stormwater/models.py
+++ b/opentreemap/stormwater/models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.contrib.gis.db import models
from django.db import connection
diff --git a/opentreemap/stormwater/routes.py b/opentreemap/stormwater/routes.py
index ec859e049..ab4bff834 100644
--- a/opentreemap/stormwater/routes.py
+++ b/opentreemap/stormwater/routes.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django_tinsel.decorators import json_api_call, route
from django_tinsel.utils import decorate as do
diff --git a/opentreemap/stormwater/tests.py b/opentreemap/stormwater/tests.py
index 538b30bcc..9f34eff74 100644
--- a/opentreemap/stormwater/tests.py
+++ b/opentreemap/stormwater/tests.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.ecobenefits import (FEET_SQ_PER_METER_SQ, FEET_PER_INCH,
GALLONS_PER_CUBIC_FT)
diff --git a/opentreemap/stormwater/urls.py b/opentreemap/stormwater/urls.py
index 3a05da2e1..db770966c 100644
--- a/opentreemap/stormwater/urls.py
+++ b/opentreemap/stormwater/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/stormwater/views.py b/opentreemap/stormwater/views.py
index 85a65d1ae..a0bfe16ca 100644
--- a/opentreemap/stormwater/views.py
+++ b/opentreemap/stormwater/views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.contrib.gis.geos import Point
diff --git a/opentreemap/treemap/DotDict.py b/opentreemap/treemap/DotDict.py
index 8dce65070..d48521ecc 100644
--- a/opentreemap/treemap/DotDict.py
+++ b/opentreemap/treemap/DotDict.py
@@ -41,10 +41,30 @@ def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
def __getitem__(self, key):
+ # An implementation note about the try blocks below.
+
+ # Django 1.11.17 calls `hasattr(a_dotdict_field, 'resolve_expression')`
+ # https://bit.ly/2ZWLoWF
+
+ # The Python 3 documentation says that this ends up calling `getattr`
+ # and returning False if an `AttributeError` is raised
+ # https://docs.python.org/3/library/functions.html#hasattr
+
+ # For dictionaries, `getattr` ends up calling `__getitem__`. Our
+ # implementation of `__getitem__` correctly raises KeyError, and we
+ # were relying on a bug in Python 2 where any exception raised during a
+ # `hasattr` check would result in False. Now that Python 3 explicitly
+ # checks for `AttributeError` we need this workaround
if '.' not in key:
- return dict.__getitem__(self, key)
+ try:
+ return dict.__getitem__(self, key)
+ except KeyError as ke:
+ raise AttributeError(ke)
myKey, restOfKey = key.split('.', 1)
- target = dict.__getitem__(self, myKey)
+ try:
+ target = dict.__getitem__(self, myKey)
+ except KeyError as ke:
+ raise AttributeError(ke)
self._ensure_dot_dict(target, restOfKey, myKey)
return target[restOfKey]
diff --git a/opentreemap/treemap/admin.py b/opentreemap/treemap/admin.py
index 5f3707b05..f94bec415 100644
--- a/opentreemap/treemap/admin.py
+++ b/opentreemap/treemap/admin.py
@@ -2,8 +2,8 @@
from django.contrib.auth import models as auth_models
from django.contrib.auth.signals import user_logged_in
-import models
-import udf
+from . import models
+from . import udf
user_logged_in.disconnect(auth_models.update_last_login)
diff --git a/opentreemap/treemap/audit.py b/opentreemap/treemap/audit.py
index fa59df7ff..1da7b390e 100644
--- a/opentreemap/treemap/audit.py
+++ b/opentreemap/treemap/audit.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import hashlib
@@ -84,7 +82,7 @@ def _reserve_model_id(model_class):
cursor.execute("select nextval('%s');" % id_seq_name)
results = cursor.fetchone()
model_id = results[0]
- assert(type(model_id) in [int, long])
+ assert(type(model_id) in [int, int])
except:
msg = "There was a database error while retrieving a unique audit ID."
raise IntegrityError(msg)
@@ -106,7 +104,7 @@ def _reserve_model_id_range(model_class, num):
{'seq': id_seq_name, 'num': num})
model_ids = [row[0] for row in cursor]
- assert(type(model_id) in [int, long] for model_id in model_ids)
+ assert(type(model_id) in [int, int] for model_id in model_ids)
except:
msg = "There was a database error while retrieving a unique audit ID."
raise IntegrityError(msg)
@@ -530,7 +528,7 @@ def as_dict(self):
@property
def hash(self):
- values = ['%s:%s' % (k, v) for (k, v) in self.as_dict().iteritems()]
+ values = ['%s:%s' % (k, v) for (k, v) in self.as_dict().items()]
string = '|'.join(values).encode('utf-8')
return hashlib.md5(string).hexdigest()
@@ -608,12 +606,12 @@ def tracked_fields(self):
def _direct_updates(self, updates, user):
pending_fields = self.get_pending_fields(user)
- return {key: val for key, val in updates.iteritems()
+ return {key: val for key, val in updates.items()
if key not in pending_fields}
def _pending_updates(self, updates, user):
pending_fields = self.get_pending_fields(user)
- return {key: val for key, val in updates.iteritems()
+ return {key: val for key, val in updates.items()
if key in pending_fields}
def _updated_fields(self):
@@ -668,7 +666,7 @@ def is_user_administrator(self, user):
return user.get_role(instance).name == Role.ADMINISTRATOR
def fields(self):
- return self.as_dict().keys()
+ return list(self.as_dict().keys())
def get_previous_state(self):
return self._previous_state
@@ -687,7 +685,7 @@ def populate_previous_state(self):
# "initial" state is empty so we clear it here
self.clear_previous_state()
else:
- self._previous_state = {k: v for k, v in self.as_dict().iteritems()
+ self._previous_state = {k: v for k, v in self.as_dict().items()
if k not in self._do_not_track}
def get_pending_fields(self, user=None):
@@ -1133,7 +1131,7 @@ def make_audit(field, prev_val, cur_val):
requires_auth=False,
ref=None)
- for [field, (prev_value, next_value)] in direct_updates.iteritems():
+ for [field, (prev_value, next_value)] in direct_updates.items():
yield make_audit(field, prev_value, next_value)
@property
@@ -1234,7 +1232,7 @@ def save_with_user(self, user, auth_bypass=False, *args, **kwargs):
# Before saving we need to restore any pending values to their
# previous state
- for pending_field, (old_val, __) in pending_updates.iteritems():
+ for pending_field, (old_val, __) in pending_updates.items():
try:
self.apply_change(pending_field, old_val)
except ValueError:
@@ -1289,7 +1287,7 @@ def make_pending_audit(field, prev_val, cur_val):
requires_auth=True,
ref=None)
- for [field, (prev_value, next_value)] in pending_updates.iteritems():
+ for [field, (prev_value, next_value)] in pending_updates.items():
yield make_pending_audit(field, prev_value, next_value)
@@ -1436,7 +1434,7 @@ def _deserialize_value(self, value):
if isinstance(field_cls, models.GeometryField):
field_modified_value = GEOSGeometry(field_modified_value)
elif isinstance(field_cls, models.ForeignKey):
- if isinstance(field_modified_value, (str, unicode)):
+ if isinstance(field_modified_value, str):
# sometimes audit records have descriptive string values
# stored in what should be a foreign key field.
# these cannot be resolved to foreign key models.
@@ -1577,7 +1575,7 @@ def dict(self):
'created': str(self.created)}
def __unicode__(self):
- return u"pk=%s - action=%s - %s.%s:(%s) - %s => %s" % \
+ return "pk=%s - action=%s - %s.%s:(%s) - %s => %s" % \
(self.pk, self.TYPES[self.action], self.model,
self.field, self.model_id,
self.previous_value, self.current_value)
@@ -1640,7 +1638,7 @@ def apply_adjustment(*audits):
elif not audit.requires_auth:
iuser.reputation += rm.direct_write_score
- for iuser in iusers.itervalues():
+ for iuser in iusers.values():
iuser.save_base()
@@ -1654,7 +1652,7 @@ def _get_model_class(class_dict, cls, model_name):
Convert a model name (as a string) into the model class
"""
if model_name.startswith('udf:'):
- from udf import UserDefinedCollectionValue
+ from .udf import UserDefinedCollectionValue
return UserDefinedCollectionValue
if not class_dict:
diff --git a/opentreemap/treemap/decorators.py b/opentreemap/treemap/decorators.py
index 6fd253c45..c5c12910d 100644
--- a/opentreemap/treemap/decorators.py
+++ b/opentreemap/treemap/decorators.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from functools import wraps
diff --git a/opentreemap/treemap/ecobackend.py b/opentreemap/treemap/ecobackend.py
index 0efcc60e1..6a02a2712 100644
--- a/opentreemap/treemap/ecobackend.py
+++ b/opentreemap/treemap/ecobackend.py
@@ -1,10 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
-import urllib2
-import urllib
+
+import urllib.request
+import urllib.parse
+import urllib.error
import json
import re
import sys
@@ -92,7 +91,7 @@ def json_benefits_call(endpoint, params, post=False, convert_params=True):
hexstring = ''.join('%02X' % ord(x) for x in bytestring)
v = "ST_GeomFromEWKT('%s')" % GEOSGeometry(hexstring).ewkt
- elif not isinstance(v, unicode):
+ elif not isinstance(v, str):
v = str(v)
if k == "param":
@@ -106,12 +105,11 @@ def json_benefits_call(endpoint, params, post=False, convert_params=True):
data = json.dumps(paramdata)
else:
data = json.dumps(params)
- req = urllib2.Request(url,
- data,
- {'Content-Type': 'application/json'})
+ req = urllib.request.Request(
+ url, data, {'Content-Type': 'application/json'})
else:
- paramString = "&".join(["%s=%s" % (urllib.quote_plus(str(name)),
- urllib.quote_plus(str(val)))
+ paramString = "&".join(["%s=%s" % (urllib.parse.quote_plus(str(name)),
+ urllib.parse.quote_plus(str(val)))
for (name, val) in params])
# A get request is assumed by urllib2
@@ -124,13 +122,15 @@ def json_benefits_call(endpoint, params, post=False, convert_params=True):
general_unhandled_struct = (None, UNKNOWN_ECO_FAILURE)
try:
- result = urllib2.urlopen(req).read()
+ result = urllib.request.urlopen(req).read()
if result:
result = json.loads(result)
return result, None
- except urllib2.HTTPError as e:
+ except urllib.error.HTTPError as e:
error_body = e.fp.read()
- for code, patterns in ECOBENEFIT_FAILURE_CODES_AND_PATTERNS.items():
+ codes_and_patterns = \
+ list(ECOBENEFIT_FAILURE_CODES_AND_PATTERNS.items())
+ for code, patterns in codes_and_patterns:
for pattern in patterns:
match = re.match(pattern, error_body)
if match:
@@ -162,6 +162,6 @@ def json_benefits_call(endpoint, params, post=False, convert_params=True):
LOG_FUNCTION_FOR_FAILURE_CODE[UNKNOWN_ECO_FAILURE](
"ECOBENEFIT FAILURE: " + error_body)
return general_unhandled_struct
- except urllib2.URLError:
+ except urllib.error.URLError:
logger.error("Error connecting to ecoservice", exc_info=sys.exc_info())
return general_unhandled_struct
diff --git a/opentreemap/treemap/ecobenefits.py b/opentreemap/treemap/ecobenefits.py
index 9e6b7fd31..52c5728d2 100644
--- a/opentreemap/treemap/ecobenefits.py
+++ b/opentreemap/treemap/ecobenefits.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis.geos.point import Point
@@ -113,7 +111,7 @@ def _make_sql_from_query(self, query):
# Returning a unicode SQL string ensures that any string
# replacements done to query string will not raise
# UnicodeDecodeError
- return unicode(cursor.mogrify(sql, params), 'utf-8')
+ return str(cursor.mogrify(sql, params), 'utf-8')
def benefits_for_filter(self, instance, item_filter):
from treemap.models import Plot, Tree
@@ -187,7 +185,7 @@ def benefits_for_filter(self, instance, item_filter):
'region': region_code or ""}
rawb, err = ecobackend.json_benefits_call(
- 'eco_summary.json', params.iteritems(), post=True)
+ 'eco_summary.json', iter(params.items()), post=True)
if err:
raise Exception(err)
@@ -237,7 +235,7 @@ def benefits_for_object(self, instance, plot):
'speciesid': tree.species.pk}
rawb, err = ecobackend.json_benefits_call(
- 'eco.json', params.iteritems())
+ 'eco.json', iter(params.items()))
if err:
rslt = {'error': err}
@@ -314,7 +312,7 @@ def compute_currency_and_transform_units(instance, benefits):
rslt = {}
- for group, (unit, keys) in groups.iteritems():
+ for group, (unit, keys) in groups.items():
valuetotal = currencytotal = 0
for key in keys:
@@ -343,7 +341,7 @@ def _sum_dict(d1, d2):
return d1
dsum = {}
- for k in d1.keys() + d2.keys():
+ for k in list(d1.keys()) + list(d2.keys()):
if k in d1 and k not in d2:
dsum[k] = d1[k]
elif k in d2 and k not in d1:
@@ -370,8 +368,8 @@ def _combine_benefit_basis(basis, new_basis_groups):
def _combine_grouped_benefits(benefits, new_benefit_groups):
- for group, ft_benefits in new_benefit_groups.iteritems():
- for ft_benefit_key, ft_benefit in ft_benefits.iteritems():
+ for group, ft_benefits in new_benefit_groups.items():
+ for ft_benefit_key, ft_benefit in ft_benefits.items():
if group not in benefits:
benefits[group] = {}
@@ -403,7 +401,7 @@ def _combine_grouped_benefits(benefits, new_benefit_groups):
def _annotate_basis_with_extra_stats(basis):
# Basis groups just have # calc and # discarded
# annotate with some more info
- for abasis in basis.values():
+ for abasis in list(basis.values()):
total = (abasis['n_objects_used'] +
abasis['n_objects_discarded'])
@@ -476,7 +474,7 @@ def _ensure_itree_codes_fetched():
_itree_codes_by_region = result['Codes']
_all_itree_codes = set(
- itertools.chain(*_itree_codes_by_region.values()))
+ itertools.chain(*list(_itree_codes_by_region.values())))
within_itree_regions_view = json_api_call(within_itree_regions)
diff --git a/opentreemap/treemap/ecocache.py b/opentreemap/treemap/ecocache.py
index ec93205a5..2b3a13c7b 100644
--- a/opentreemap/treemap/ecocache.py
+++ b/opentreemap/treemap/ecocache.py
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
+
import hashlib
from django.conf import settings
diff --git a/opentreemap/treemap/exceptions.py b/opentreemap/treemap/exceptions.py
index bc4505a85..1d084362d 100644
--- a/opentreemap/treemap/exceptions.py
+++ b/opentreemap/treemap/exceptions.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from django.http import HttpResponseForbidden
diff --git a/opentreemap/treemap/images.py b/opentreemap/treemap/images.py
index 1593a407b..f2909e850 100644
--- a/opentreemap/treemap/images.py
+++ b/opentreemap/treemap/images.py
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from PIL import Image
import hashlib
import os
-from cStringIO import StringIO
+from io import StringIO
from django.conf import settings
from django.core.exceptions import ValidationError
diff --git a/opentreemap/treemap/instance.py b/opentreemap/treemap/instance.py
index 667cdb741..3dd37c954 100644
--- a/opentreemap/treemap/instance.py
+++ b/opentreemap/treemap/instance.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
@@ -19,7 +17,7 @@
import hashlib
import json
-from urllib import urlencode
+from urllib.parse import urlencode
from opentreemap.util import extent_intersection, extent_as_json
@@ -455,7 +453,8 @@ def factor_conversions(self):
@property
def scss_query_string(self):
- scss_vars = ({k: val for k, val in self.scss_variables.items() if val}
+ scss_vars = ({k: val for k, val
+ in list(self.scss_variables.items()) if val}
if self.scss_variables else {})
return urlencode(scss_vars)
@@ -583,7 +582,7 @@ def add_map_feature_types(self, types):
for type, clz in zip(types, classes):
settings = (getattr(clz, 'udf_settings', {}))
- for udfc_name, udfc_settings in settings.items():
+ for udfc_name, udfc_settings in list(settings.items()):
if udfc_settings.get('defaults'):
get_or_create_udf(self, type, udfc_name)
@@ -725,7 +724,7 @@ def raise_errors(errors):
raise_errors([INSTANCE_FIELD_ERRORS['no_field_groups']])
for group in field_groups:
- if not _truthy_of_type(group.get('header'), basestring):
+ if not _truthy_of_type(group.get('header'), str):
errors.add(INSTANCE_FIELD_ERRORS['group_has_no_header'])
if ((not isinstance(group.get('collection_udf_keys'), list)
diff --git a/opentreemap/treemap/json_field.py b/opentreemap/treemap/json_field.py
index c1a224ffd..c5926c787 100644
--- a/opentreemap/treemap/json_field.py
+++ b/opentreemap/treemap/json_field.py
@@ -8,7 +8,7 @@
class JSONField(models.TextField):
def to_python(self, value):
- if isinstance(value, basestring):
+ if isinstance(value, str):
obj = json.loads(value or "{}")
return DotDict(obj) if isinstance(obj, dict) else obj
else:
diff --git a/opentreemap/treemap/lib/__init__.py b/opentreemap/treemap/lib/__init__.py
index 74eb39bba..153f05102 100644
--- a/opentreemap/treemap/lib/__init__.py
+++ b/opentreemap/treemap/lib/__init__.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import re
@@ -24,8 +22,8 @@ def format_benefits(instance, benefits, basis, digits=None):
# FYI: this mutates the underlying benefit dictionaries
total_currency = 0
- for benefit_group in benefits.values():
- for key, benefit in benefit_group.iteritems():
+ for benefit_group in list(benefits.values()):
+ for key, benefit in benefit_group.items():
if benefit['currency'] is not None:
# TODO: Use i18n/l10n to format currency
benefit['currency_saved'] = currency_symbol + number_format(
diff --git a/opentreemap/treemap/lib/external_link.py b/opentreemap/treemap/lib/external_link.py
index 0ebd3b75b..e128689b7 100644
--- a/opentreemap/treemap/lib/external_link.py
+++ b/opentreemap/treemap/lib/external_link.py
@@ -1,11 +1,10 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import re
from django.utils.translation import ugettext_lazy as _
+from functools import reduce
# Utilities for external links
@@ -34,7 +33,7 @@ def _re_group_count(compiled, text):
return reduce(
lambda ac, groupdict: {
k: v if groupdict[k] is None else v + 1
- for k, v in ac.iteritems()},
+ for k, v in ac.items()},
[m.groupdict() for m in compiled.finditer(text)],
totals)
@@ -48,4 +47,4 @@ def get_url_tokens_for_display(in_bold=False):
show = lambda t: ('#{%s}' if in_bold else '#{%s}') % t
return (', '.join(show(token) for token in _valid_url_tokens[:-1]) +
- unicode(_(' or ')) + show(_valid_url_tokens[-1]))
+ str(_(' or ')) + show(_valid_url_tokens[-1]))
diff --git a/opentreemap/treemap/lib/hide_at_zoom.py b/opentreemap/treemap/lib/hide_at_zoom.py
index 27a353c94..58134c435 100644
--- a/opentreemap/treemap/lib/hide_at_zoom.py
+++ b/opentreemap/treemap/lib/hide_at_zoom.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from math import floor
diff --git a/opentreemap/treemap/lib/map_feature.py b/opentreemap/treemap/lib/map_feature.py
index ba386ce3d..1d9daaa5b 100644
--- a/opentreemap/treemap/lib/map_feature.py
+++ b/opentreemap/treemap/lib/map_feature.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import datetime
from string import Template
@@ -278,7 +276,7 @@ class UrlTemplate(Template):
'feature_id': plot.pk}
if tree:
url_name = 'add_photo_to_tree'
- url_kwargs = dict(url_kwargs.items() + [('tree_id', tree.pk)])
+ url_kwargs = dict(list(url_kwargs.items()) + [('tree_id', tree.pk)])
else:
url_name = 'add_photo_to_plot'
diff --git a/opentreemap/treemap/lib/object_caches.py b/opentreemap/treemap/lib/object_caches.py
index 6e5d0d391..af327f763 100644
--- a/opentreemap/treemap/lib/object_caches.py
+++ b/opentreemap/treemap/lib/object_caches.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.db.models import F
diff --git a/opentreemap/treemap/lib/page_of_items.py b/opentreemap/treemap/lib/page_of_items.py
index 2995ed1f7..78ae8e525 100644
--- a/opentreemap/treemap/lib/page_of_items.py
+++ b/opentreemap/treemap/lib/page_of_items.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.urlresolvers import reverse
@@ -17,8 +15,8 @@ def params(self, *keys):
def url(self, *keys, **overrides):
params = self._params
if overrides:
- params = dict(params.items() + overrides.items())
- keys = params.keys()
+ params = dict(list(params.items()) + list(overrides.items()))
+ keys = list(params.keys())
return self._url + self._param_string(keys, params)
@staticmethod
diff --git a/opentreemap/treemap/lib/perms.py b/opentreemap/treemap/lib/perms.py
index c10fa6e37..8b461eb67 100644
--- a/opentreemap/treemap/lib/perms.py
+++ b/opentreemap/treemap/lib/perms.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import inspect
diff --git a/opentreemap/treemap/lib/photo.py b/opentreemap/treemap/lib/photo.py
index f1c1bea7d..5d7e462c3 100644
--- a/opentreemap/treemap/lib/photo.py
+++ b/opentreemap/treemap/lib/photo.py
@@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
-from urlparse import urlparse, urlunparse
+
+from urllib.parse import urlparse, urlunparse
from django.core.urlresolvers import reverse
diff --git a/opentreemap/treemap/lib/tree.py b/opentreemap/treemap/lib/tree.py
index fb9a84281..faf4d3bae 100644
--- a/opentreemap/treemap/lib/tree.py
+++ b/opentreemap/treemap/lib/tree.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.http import Http404
diff --git a/opentreemap/treemap/lib/user.py b/opentreemap/treemap/lib/user.py
index 2a9f87a13..b52c2283c 100644
--- a/opentreemap/treemap/lib/user.py
+++ b/opentreemap/treemap/lib/user.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.db.models import Q
diff --git a/opentreemap/treemap/management/commands/create_instance.py b/opentreemap/treemap/management/commands/create_instance.py
index 9a5dff2f5..1d3ba8a92 100755
--- a/opentreemap/treemap/management/commands/create_instance.py
+++ b/opentreemap/treemap/management/commands/create_instance.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import logging
diff --git a/opentreemap/treemap/management/commands/create_system_user.py b/opentreemap/treemap/management/commands/create_system_user.py
index 6b28f48e2..48beb8722 100644
--- a/opentreemap/treemap/management/commands/create_system_user.py
+++ b/opentreemap/treemap/management/commands/create_system_user.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.management.base import BaseCommand
from django.conf import settings
diff --git a/opentreemap/treemap/management/commands/delete_data.py b/opentreemap/treemap/management/commands/delete_data.py
index 88bcbcce7..0f88ccc96 100644
--- a/opentreemap/treemap/management/commands/delete_data.py
+++ b/opentreemap/treemap/management/commands/delete_data.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.management.util import InstanceDataCommand
diff --git a/opentreemap/treemap/management/commands/random_trees.py b/opentreemap/treemap/management/commands/random_trees.py
index ddc3b66bc..2f636d9b7 100644
--- a/opentreemap/treemap/management/commands/random_trees.py
+++ b/opentreemap/treemap/management/commands/random_trees.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import random
import math
@@ -74,7 +72,7 @@ def handle(self, *args, **options):
ct = 0
cp = 0
- for i in xrange(0, n):
+ for i in range(0, n):
mktree = random.random() < tree_prob
radius = random.gauss(0.0, max_radius)
theta = random.random() * 2.0 * math.pi
diff --git a/opentreemap/treemap/management/commands/set_mapfeature_updated_at.py b/opentreemap/treemap/management/commands/set_mapfeature_updated_at.py
index aaf407bf1..06688aee0 100644
--- a/opentreemap/treemap/management/commands/set_mapfeature_updated_at.py
+++ b/opentreemap/treemap/management/commands/set_mapfeature_updated_at.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.management.base import BaseCommand
diff --git a/opentreemap/treemap/management/commands/set_mapfeature_updated_by.py b/opentreemap/treemap/management/commands/set_mapfeature_updated_by.py
index e0e2dceaf..d69f7a0a0 100644
--- a/opentreemap/treemap/management/commands/set_mapfeature_updated_by.py
+++ b/opentreemap/treemap/management/commands/set_mapfeature_updated_by.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.management.base import BaseCommand
diff --git a/opentreemap/treemap/management/util.py b/opentreemap/treemap/management/util.py
index e474b1030..3c2036cad 100644
--- a/opentreemap/treemap/management/util.py
+++ b/opentreemap/treemap/management/util.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.core.management.base import BaseCommand
from django.db import connection, transaction
diff --git a/opentreemap/treemap/migrations/0001_initial.py b/opentreemap/treemap/migrations/0001_initial.py
index ca430dfab..e89841bcf 100644
--- a/opentreemap/treemap/migrations/0001_initial.py
+++ b/opentreemap/treemap/migrations/0001_initial.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
import re
diff --git a/opentreemap/treemap/migrations/0002_add_itree_regions_20150701_1809.py b/opentreemap/treemap/migrations/0002_add_itree_regions_20150701_1809.py
index 6da71bf1b..5903e8d2c 100644
--- a/opentreemap/treemap/migrations/0002_add_itree_regions_20150701_1809.py
+++ b/opentreemap/treemap/migrations/0002_add_itree_regions_20150701_1809.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.core.management import call_command
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0003_change_audit_id_to_big_int_20150708_1612.py b/opentreemap/treemap/migrations/0003_change_audit_id_to_big_int_20150708_1612.py
index 90ae9b23f..6d983b78a 100644
--- a/opentreemap/treemap/migrations/0003_change_audit_id_to_big_int_20150708_1612.py
+++ b/opentreemap/treemap/migrations/0003_change_audit_id_to_big_int_20150708_1612.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0004_auto_20150720_1523.py b/opentreemap/treemap/migrations/0004_auto_20150720_1523.py
index db189ff18..f042d542d 100644
--- a/opentreemap/treemap/migrations/0004_auto_20150720_1523.py
+++ b/opentreemap/treemap/migrations/0004_auto_20150720_1523.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0005_auto_20150729_1046.py b/opentreemap/treemap/migrations/0005_auto_20150729_1046.py
index da57a2c58..826cdc509 100644
--- a/opentreemap/treemap/migrations/0005_auto_20150729_1046.py
+++ b/opentreemap/treemap/migrations/0005_auto_20150729_1046.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0006_stop_tracking_polygonal_mapfeature_ptr.py b/opentreemap/treemap/migrations/0006_stop_tracking_polygonal_mapfeature_ptr.py
index fb95de372..125d5b32b 100644
--- a/opentreemap/treemap/migrations/0006_stop_tracking_polygonal_mapfeature_ptr.py
+++ b/opentreemap/treemap/migrations/0006_stop_tracking_polygonal_mapfeature_ptr.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0007_auto_20150902_1534.py b/opentreemap/treemap/migrations/0007_auto_20150902_1534.py
index 537fe45cc..1a54cdb78 100644
--- a/opentreemap/treemap/migrations/0007_auto_20150902_1534.py
+++ b/opentreemap/treemap/migrations/0007_auto_20150902_1534.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0008_instance_eco_rev.py b/opentreemap/treemap/migrations/0008_instance_eco_rev.py
index 577a95413..e14033b10 100644
--- a/opentreemap/treemap/migrations/0008_instance_eco_rev.py
+++ b/opentreemap/treemap/migrations/0008_instance_eco_rev.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0009_restructure_replaceable_terms.py b/opentreemap/treemap/migrations/0009_restructure_replaceable_terms.py
index f4a53b2fa..a24e903ec 100644
--- a/opentreemap/treemap/migrations/0009_restructure_replaceable_terms.py
+++ b/opentreemap/treemap/migrations/0009_restructure_replaceable_terms.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/treemap/migrations/0010_eliminate_warnings_fields_w340.py b/opentreemap/treemap/migrations/0010_eliminate_warnings_fields_w340.py
index c08de0a88..fd39ad74c 100644
--- a/opentreemap/treemap/migrations/0010_eliminate_warnings_fields_w340.py
+++ b/opentreemap/treemap/migrations/0010_eliminate_warnings_fields_w340.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from django.conf import settings
diff --git a/opentreemap/treemap/migrations/0011_instance_universal_rev.py b/opentreemap/treemap/migrations/0011_instance_universal_rev.py
index 4ebd903e7..fe3abe17d 100644
--- a/opentreemap/treemap/migrations/0011_instance_universal_rev.py
+++ b/opentreemap/treemap/migrations/0011_instance_universal_rev.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0012_help_text_to_verbose_name.py b/opentreemap/treemap/migrations/0012_help_text_to_verbose_name.py
index 76c59aa2f..dee7d6847 100644
--- a/opentreemap/treemap/migrations/0012_help_text_to_verbose_name.py
+++ b/opentreemap/treemap/migrations/0012_help_text_to_verbose_name.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
import django.utils.timezone
diff --git a/opentreemap/treemap/migrations/0013_mapfeature_hide_at_zoom.py b/opentreemap/treemap/migrations/0013_mapfeature_hide_at_zoom.py
index f16bf2cb8..909da4cc7 100644
--- a/opentreemap/treemap/migrations/0013_mapfeature_hide_at_zoom.py
+++ b/opentreemap/treemap/migrations/0013_mapfeature_hide_at_zoom.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0014_change_empty_multichoice_values.py b/opentreemap/treemap/migrations/0014_change_empty_multichoice_values.py
index 84551d661..8d1cfd94e 100644
--- a/opentreemap/treemap/migrations/0014_change_empty_multichoice_values.py
+++ b/opentreemap/treemap/migrations/0014_change_empty_multichoice_values.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
from treemap.udf import UDFDictionary
@@ -28,9 +28,9 @@ def set_empty_multichoice_values_to_none(apps, schema_editor):
super(UDFDictionary, obj.udfs).__setitem__(udfd.name, None)
obj.save_base()
if len(objs) > 0:
- print('Updated %s empty multichoice values for %s udf "%s" (%s)'
+ print(('Updated %s empty multichoice values for %s udf "%s" (%s)'
% (len(objs), udfd.model_type, udfd.name,
- udfd.instance.url_name))
+ udfd.instance.url_name)))
class Migration(migrations.Migration):
diff --git a/opentreemap/treemap/migrations/0015_add_separate_instance_bounds_model.py b/opentreemap/treemap/migrations/0015_add_separate_instance_bounds_model.py
index a25ff75df..4f6212e0e 100644
--- a/opentreemap/treemap/migrations/0015_add_separate_instance_bounds_model.py
+++ b/opentreemap/treemap/migrations/0015_add_separate_instance_bounds_model.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
import django.contrib.gis.db.models.fields
diff --git a/opentreemap/treemap/migrations/0015_instanceuser_last_seen.py b/opentreemap/treemap/migrations/0015_instanceuser_last_seen.py
index ebdea84a3..dad1dc605 100644
--- a/opentreemap/treemap/migrations/0015_instanceuser_last_seen.py
+++ b/opentreemap/treemap/migrations/0015_instanceuser_last_seen.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0016_make_bounds_nullable.py b/opentreemap/treemap/migrations/0016_make_bounds_nullable.py
index 92f520b1c..58a3ab044 100644
--- a/opentreemap/treemap/migrations/0016_make_bounds_nullable.py
+++ b/opentreemap/treemap/migrations/0016_make_bounds_nullable.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
import django.contrib.gis.db.models.fields
diff --git a/opentreemap/treemap/migrations/0017_copy_bounds_to_separate_model.py b/opentreemap/treemap/migrations/0017_copy_bounds_to_separate_model.py
index eae80f788..b6b07d5fb 100644
--- a/opentreemap/treemap/migrations/0017_copy_bounds_to_separate_model.py
+++ b/opentreemap/treemap/migrations/0017_copy_bounds_to_separate_model.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0018_add_species_field_names.py b/opentreemap/treemap/migrations/0018_add_species_field_names.py
index 4c90485cd..7002348e1 100644
--- a/opentreemap/treemap/migrations/0018_add_species_field_names.py
+++ b/opentreemap/treemap/migrations/0018_add_species_field_names.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0018_merge.py b/opentreemap/treemap/migrations/0018_merge.py
index 080559c3f..118fc8a1c 100644
--- a/opentreemap/treemap/migrations/0018_merge.py
+++ b/opentreemap/treemap/migrations/0018_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0019_merge.py b/opentreemap/treemap/migrations/0019_merge.py
index e684064e8..71aaed998 100644
--- a/opentreemap/treemap/migrations/0019_merge.py
+++ b/opentreemap/treemap/migrations/0019_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import models, migrations
diff --git a/opentreemap/treemap/migrations/0020_remove_instance_bounds.py b/opentreemap/treemap/migrations/0020_remove_instance_bounds.py
index 17e91080f..a3158d7f0 100644
--- a/opentreemap/treemap/migrations/0020_remove_instance_bounds.py
+++ b/opentreemap/treemap/migrations/0020_remove_instance_bounds.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0021_rename_bounds_obj_to_bounds.py b/opentreemap/treemap/migrations/0021_rename_bounds_obj_to_bounds.py
index 10cb29165..8782ef0d6 100644
--- a/opentreemap/treemap/migrations/0021_rename_bounds_obj_to_bounds.py
+++ b/opentreemap/treemap/migrations/0021_rename_bounds_obj_to_bounds.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0022_add_esri_basemap_type_choice.py b/opentreemap/treemap/migrations/0022_add_esri_basemap_type_choice.py
index ea8e051eb..da43270e3 100644
--- a/opentreemap/treemap/migrations/0022_add_esri_basemap_type_choice.py
+++ b/opentreemap/treemap/migrations/0022_add_esri_basemap_type_choice.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0022_remove_null_from_eco_rev.py b/opentreemap/treemap/migrations/0022_remove_null_from_eco_rev.py
index 7656473f3..1bafe358e 100644
--- a/opentreemap/treemap/migrations/0022_remove_null_from_eco_rev.py
+++ b/opentreemap/treemap/migrations/0022_remove_null_from_eco_rev.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0023_merge.py b/opentreemap/treemap/migrations/0023_merge.py
index d547cc4d5..0cc3e1b9b 100644
--- a/opentreemap/treemap/migrations/0023_merge.py
+++ b/opentreemap/treemap/migrations/0023_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0024_add_species_verbose_names.py b/opentreemap/treemap/migrations/0024_add_species_verbose_names.py
index 4e33c0b34..27d5a830a 100644
--- a/opentreemap/treemap/migrations/0024_add_species_verbose_names.py
+++ b/opentreemap/treemap/migrations/0024_add_species_verbose_names.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0025_remove_null_from_boundary_updated_at.py b/opentreemap/treemap/migrations/0025_remove_null_from_boundary_updated_at.py
index 534867f68..419fb0732 100644
--- a/opentreemap/treemap/migrations/0025_remove_null_from_boundary_updated_at.py
+++ b/opentreemap/treemap/migrations/0025_remove_null_from_boundary_updated_at.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0026_add_canopy_fields.py b/opentreemap/treemap/migrations/0026_add_canopy_fields.py
index 215ccedc6..cf7df4a7d 100644
--- a/opentreemap/treemap/migrations/0026_add_canopy_fields.py
+++ b/opentreemap/treemap/migrations/0026_add_canopy_fields.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0027_boundary_searchable.py b/opentreemap/treemap/migrations/0027_boundary_searchable.py
index bca42170c..d36df2f00 100644
--- a/opentreemap/treemap/migrations/0027_boundary_searchable.py
+++ b/opentreemap/treemap/migrations/0027_boundary_searchable.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0027_make_instance_canopy_fields_non_null.py b/opentreemap/treemap/migrations/0027_make_instance_canopy_fields_non_null.py
index b038c149c..5fe76e191 100644
--- a/opentreemap/treemap/migrations/0027_make_instance_canopy_fields_non_null.py
+++ b/opentreemap/treemap/migrations/0027_make_instance_canopy_fields_non_null.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0028_make_boundary_searchable_non_null.py b/opentreemap/treemap/migrations/0028_make_boundary_searchable_non_null.py
index 2763ce397..62364ed67 100644
--- a/opentreemap/treemap/migrations/0028_make_boundary_searchable_non_null.py
+++ b/opentreemap/treemap/migrations/0028_make_boundary_searchable_non_null.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0029_merge.py b/opentreemap/treemap/migrations/0029_merge.py
index cc3ba1a95..cba58e83c 100644
--- a/opentreemap/treemap/migrations/0029_merge.py
+++ b/opentreemap/treemap/migrations/0029_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0030_add_verbose_name_to_owner_orig_id.py b/opentreemap/treemap/migrations/0030_add_verbose_name_to_owner_orig_id.py
index f6ca218a5..9f2484d28 100644
--- a/opentreemap/treemap/migrations/0030_add_verbose_name_to_owner_orig_id.py
+++ b/opentreemap/treemap/migrations/0030_add_verbose_name_to_owner_orig_id.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0030_backfill_canopy_boundary_category_column.py b/opentreemap/treemap/migrations/0030_backfill_canopy_boundary_category_column.py
index 96f248fa4..9eb289cb7 100644
--- a/opentreemap/treemap/migrations/0030_backfill_canopy_boundary_category_column.py
+++ b/opentreemap/treemap/migrations/0030_backfill_canopy_boundary_category_column.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0031_add_custom_id_to_default_search_fields.py b/opentreemap/treemap/migrations/0031_add_custom_id_to_default_search_fields.py
index f96d8c29e..0e3e04efd 100644
--- a/opentreemap/treemap/migrations/0031_add_custom_id_to_default_search_fields.py
+++ b/opentreemap/treemap/migrations/0031_add_custom_id_to_default_search_fields.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from copy import deepcopy
@@ -8,7 +8,7 @@
from treemap.DotDict import DotDict
-identifier = u'plot.owner_orig_id'
+identifier = 'plot.owner_orig_id'
def update_config_property(apps, update_fn, *categories):
@@ -24,9 +24,9 @@ def add_to_config(config, *categories):
for category in categories:
lookup = '.'.join(['search_config', category])
specs = config.setdefault(lookup, [])
- if True not in [identifier in v for s in specs for v in s.values()]:
+ if True not in [identifier in v for s in specs for v in list(s.values())]:
# mutates config[lookup]
- specs.append({u'identifier': identifier})
+ specs.append({'identifier': identifier})
return config
@@ -42,7 +42,7 @@ def remove_from_config(config, *categories):
specs = config.get(lookup)
if specs:
for index, spec in enumerate(specs):
- if identifier in spec.values():
+ if identifier in list(spec.values()):
break
if index < len(specs):
specs.pop(index)
diff --git a/opentreemap/treemap/migrations/0032_add_udfs_to_web_detail_fields.py b/opentreemap/treemap/migrations/0032_add_udfs_to_web_detail_fields.py
index 01fa0cb39..a8ec9df08 100644
--- a/opentreemap/treemap/migrations/0032_add_udfs_to_web_detail_fields.py
+++ b/opentreemap/treemap/migrations/0032_add_udfs_to_web_detail_fields.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from copy import deepcopy
diff --git a/opentreemap/treemap/migrations/0032_rename_to_role_default_permission_level.py b/opentreemap/treemap/migrations/0032_rename_to_role_default_permission_level.py
index 72b0a716f..0b99460e2 100644
--- a/opentreemap/treemap/migrations/0032_rename_to_role_default_permission_level.py
+++ b/opentreemap/treemap/migrations/0032_rename_to_role_default_permission_level.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0033_instance_permissions.py b/opentreemap/treemap/migrations/0033_instance_permissions.py
index 239c462fe..90eb5ed57 100644
--- a/opentreemap/treemap/migrations/0033_instance_permissions.py
+++ b/opentreemap/treemap/migrations/0033_instance_permissions.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0034_add_permission_view_external_link.py b/opentreemap/treemap/migrations/0034_add_permission_view_external_link.py
index 14e83c876..bcf3a9dd5 100644
--- a/opentreemap/treemap/migrations/0034_add_permission_view_external_link.py
+++ b/opentreemap/treemap/migrations/0034_add_permission_view_external_link.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/treemap/migrations/0035_merge.py b/opentreemap/treemap/migrations/0035_merge.py
index f9121c53a..ae468fa47 100644
--- a/opentreemap/treemap/migrations/0035_merge.py
+++ b/opentreemap/treemap/migrations/0035_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0036_assign_role_add_delete_permissions.py b/opentreemap/treemap/migrations/0036_assign_role_add_delete_permissions.py
index 7145fd85e..c65653fb8 100644
--- a/opentreemap/treemap/migrations/0036_assign_role_add_delete_permissions.py
+++ b/opentreemap/treemap/migrations/0036_assign_role_add_delete_permissions.py
@@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
from django.db.models import Q
+from functools import reduce
_WRITE_DIRECTLY = 3
@@ -71,7 +72,7 @@ def remove_permission(apps, schema_editor):
ct_query = reduce(lambda q1, q2: q1 | q2, [
Q(app_label=label, model__in=app_models)
- for label, app_models in app_labels.iteritems()])
+ for label, app_models in app_labels.items()])
photo_query = Q(app_label='treemap', model='mapfeaturephoto')
diff --git a/opentreemap/treemap/migrations/0037_fix_plot_add_delete_permission_labels.py b/opentreemap/treemap/migrations/0037_fix_plot_add_delete_permission_labels.py
index ba9689c44..98fc55fed 100644
--- a/opentreemap/treemap/migrations/0037_fix_plot_add_delete_permission_labels.py
+++ b/opentreemap/treemap/migrations/0037_fix_plot_add_delete_permission_labels.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/treemap/migrations/0038_update_delete_perm_labels.py b/opentreemap/treemap/migrations/0038_update_delete_perm_labels.py
index 2dce0a829..e1a0afb72 100644
--- a/opentreemap/treemap/migrations/0038_update_delete_perm_labels.py
+++ b/opentreemap/treemap/migrations/0038_update_delete_perm_labels.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
diff --git a/opentreemap/treemap/migrations/0038_updated_by.py b/opentreemap/treemap/migrations/0038_updated_by.py
index 1cff830a2..a7dd24c37 100644
--- a/opentreemap/treemap/migrations/0038_updated_by.py
+++ b/opentreemap/treemap/migrations/0038_updated_by.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
from django.conf import settings
diff --git a/opentreemap/treemap/migrations/0039_merge.py b/opentreemap/treemap/migrations/0039_merge.py
index 24a183179..fd7d3e238 100644
--- a/opentreemap/treemap/migrations/0039_merge.py
+++ b/opentreemap/treemap/migrations/0039_merge.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0040_expand_itree_regions.py b/opentreemap/treemap/migrations/0040_expand_itree_regions.py
index d7dd33a98..49d5f79bb 100644
--- a/opentreemap/treemap/migrations/0040_expand_itree_regions.py
+++ b/opentreemap/treemap/migrations/0040_expand_itree_regions.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
import os
diff --git a/opentreemap/treemap/migrations/0041_search_by_user.py b/opentreemap/treemap/migrations/0041_search_by_user.py
index d6a7ce5cf..cf7a701be 100644
--- a/opentreemap/treemap/migrations/0041_search_by_user.py
+++ b/opentreemap/treemap/migrations/0041_search_by_user.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from copy import deepcopy
@@ -8,7 +8,7 @@
from treemap.DotDict import DotDict
-identifier = u'mapFeature.updated_by'
+identifier = 'mapFeature.updated_by'
def update_config_property(apps, update_fn, *categories):
@@ -24,9 +24,9 @@ def add_to_config(config, *categories):
for category in categories:
lookup = '.'.join(['search_config', category])
specs = config.setdefault(lookup, [])
- if 0 == len([v for s in specs for v in s.values() if v == identifier]):
+ if 0 == len([v for s in specs for v in list(s.values()) if v == identifier]):
# mutates config[lookup]
- specs.append({u'identifier': identifier})
+ specs.append({'identifier': identifier})
return config
@@ -42,7 +42,7 @@ def remove_from_config(config, *categories):
specs = config.get(lookup)
if specs:
find_index = [i for i, s in enumerate(specs)
- if identifier in s.values()]
+ if identifier in list(s.values())]
if 0 < len(find_index):
specs.pop(find_index[0])
diff --git a/opentreemap/treemap/migrations/0042_auto_20170112_1603.py b/opentreemap/treemap/migrations/0042_auto_20170112_1603.py
index c929c7c00..129900f36 100644
--- a/opentreemap/treemap/migrations/0042_auto_20170112_1603.py
+++ b/opentreemap/treemap/migrations/0042_auto_20170112_1603.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
from django.conf import settings
diff --git a/opentreemap/treemap/migrations/0043_species_not_udf_model.py b/opentreemap/treemap/migrations/0043_species_not_udf_model.py
index d842876ae..88efcddcd 100644
--- a/opentreemap/treemap/migrations/0043_species_not_udf_model.py
+++ b/opentreemap/treemap/migrations/0043_species_not_udf_model.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations, models
diff --git a/opentreemap/treemap/migrations/0043_udfs_default.py b/opentreemap/treemap/migrations/0043_udfs_default.py
index 9017cb0e0..450ba7cef 100644
--- a/opentreemap/treemap/migrations/0043_udfs_default.py
+++ b/opentreemap/treemap/migrations/0043_udfs_default.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
import treemap.udf
diff --git a/opentreemap/treemap/migrations/0044_hstorefield.py b/opentreemap/treemap/migrations/0044_hstorefield.py
index 3c1c53da4..d874bcfac 100644
--- a/opentreemap/treemap/migrations/0044_hstorefield.py
+++ b/opentreemap/treemap/migrations/0044_hstorefield.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import unicode_literals
+
from django.db import migrations
import treemap.udf
diff --git a/opentreemap/treemap/migrations/0045_add_modeling_permission.py b/opentreemap/treemap/migrations/0045_add_modeling_permission.py
index 697143c87..0952ee44f 100644
--- a/opentreemap/treemap/migrations/0045_add_modeling_permission.py
+++ b/opentreemap/treemap/migrations/0045_add_modeling_permission.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-28 15:47
-from __future__ import unicode_literals
+
from django.db import migrations
from django.db.utils import IntegrityError
diff --git a/opentreemap/treemap/migrations/0046_auto_20170907_0937.py b/opentreemap/treemap/migrations/0046_auto_20170907_0937.py
index aaaa95e61..602b58140 100644
--- a/opentreemap/treemap/migrations/0046_auto_20170907_0937.py
+++ b/opentreemap/treemap/migrations/0046_auto_20170907_0937.py
@@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-07 14:37
-from __future__ import unicode_literals
+
from django.db import migrations
import treemap.DotDict
diff --git a/opentreemap/treemap/migrations/0047_instance_itree_region_default_choices_to_list.py b/opentreemap/treemap/migrations/0047_instance_itree_region_default_choices_to_list.py
new file mode 100644
index 000000000..4bd438483
--- /dev/null
+++ b/opentreemap/treemap/migrations/0047_instance_itree_region_default_choices_to_list.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# Generated by Django 1.11.17 on 2020-01-08 19:01
+from __future__ import unicode_literals
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('treemap', '0046_auto_20170907_0937'),
+ ]
+
+ operations = [
+ migrations.AlterField(
+ model_name='instance',
+ name='itree_region_default',
+ field=models.CharField(blank=True, choices=[('CaNCCoJBK', 'Northern California Coast'), ('CenFlaXXX', 'Central Florida'), ('GulfCoCHS', 'Coastal Plain'), ('InlEmpCLM', 'Inland Empire'), ('InlValMOD', 'Inland Valleys'), ('InterWABQ', 'Interior West'), ('LoMidWXXX', 'Lower Midwest'), ('MidWstMSP', 'Midwest'), ('NMtnPrFNL', 'North'), ('NoEastXXX', 'Northeast'), ('PacfNWLOG', 'Pacific Northwest'), ('PiedmtCLT', 'South'), ('SoCalCSMA', 'Southern California Coast'), ('SWDsrtGDL', 'Southwest Desert'), ('TpIntWBOI', 'Temperate Interior West'), ('TropicPacXXX', 'Tropical')], max_length=20, null=True),
+ ),
+ ]
diff --git a/opentreemap/treemap/models.py b/opentreemap/treemap/models.py
index afd65ce06..a0c0562f4 100644
--- a/opentreemap/treemap/models.py
+++ b/opentreemap/treemap/models.py
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
import hashlib
@@ -235,7 +232,7 @@ def get_default_for_region(cls, region_code):
if config:
benefits_conversion = cls()
benefits_conversion.currency_symbol = '$'
- for field, conversion in config.iteritems():
+ for field, conversion in config.items():
setattr(benefits_conversion, field, conversion)
return benefits_conversion
else:
diff --git a/opentreemap/treemap/plugin.py b/opentreemap/treemap/plugin.py
index 35c2703c5..3b4019e09 100644
--- a/opentreemap/treemap/plugin.py
+++ b/opentreemap/treemap/plugin.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.db.models import Q
diff --git a/opentreemap/treemap/routes.py b/opentreemap/treemap/routes.py
index 99f9e22a8..b58f7d974 100644
--- a/opentreemap/treemap/routes.py
+++ b/opentreemap/treemap/routes.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from functools import partial
diff --git a/opentreemap/treemap/search.py b/opentreemap/treemap/search.py
index 54de5d5bc..77293cf04 100644
--- a/opentreemap/treemap/search.py
+++ b/opentreemap/treemap/search.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from json import loads
from datetime import datetime
@@ -133,7 +131,7 @@ def convert_filter_units(instance, filter_dict):
Convert the values in a filter dictionary from display units to database
units. Mutates the `filter_dict` argument and returns it.
"""
- for field_name, value in filter_dict.iteritems():
+ for field_name, value in filter_dict.items():
if field_name not in ['tree.diameter', 'tree.height',
'tree.canopy_height', 'plot.width',
'plot.length', 'bioswale.drainage_area',
@@ -245,7 +243,7 @@ def parse_scalar_predicate_pair(key, value, mapping):
query = {}
- for pred, props in props_by_pred.iteritems():
+ for pred, props in props_by_pred.items():
lookup_tail, rhs = _parse_prop(props, value, pred, value[pred])
@@ -260,7 +258,7 @@ def parse_scalar_predicate_pair(key, value, mapping):
return FilterContext(basekey=model, **query)
qs = [parse_scalar_predicate_pair(*kv, mapping=mapping)
- for kv in query.iteritems()]
+ for kv in query.items()]
return _apply_combinator('AND', qs)
@@ -284,7 +282,7 @@ def _parse_by_is_collection_udf(query_dict, mapping):
}
'''
query_dict_list = [dict(value=v, **_parse_by_key_type(k, mapping=mapping))
- for k, v in query_dict.items()]
+ for k, v in list(query_dict.items())]
grouped = groupby(sorted(query_dict_list, key=lambda qd: qd['type']),
lambda qd: qd['type'])
return {k: list(v) for k, v in grouped}
@@ -306,8 +304,8 @@ def _parse_by_key_type(key, mapping):
def _unparse_scalars(scalars):
- return dict(zip([qd['key'] for qd in scalars],
- [qd['value'] for qd in scalars]))
+ return dict(list(zip([qd['key'] for qd in scalars],
+ [qd['value'] for qd in scalars])))
def _parse_collections(by_type, mapping):
@@ -334,7 +332,7 @@ def parse_collection_subquery(identifier, field_parts, mapping):
return _apply_combinator(
'AND', [parse_collection_subquery(identifier, field_parts, mapping)
- for identifier, field_parts in by_type.items()])
+ for identifier, field_parts in list(by_type.items())])
def _parse_udf_collection(udfd_id, query_parts):
@@ -354,7 +352,7 @@ def parse_collection_udf_dict(key, value):
if isinstance(value, dict):
preds = parse_udf_dict_value(value)
query = {_lookup_key('data__', field, k):
- v for (k, v) in preds.iteritems()}
+ v for (k, v) in preds.items()}
else:
query = {_lookup_key('data__', field): value}
return query
@@ -415,7 +413,7 @@ def _parse_predicate_key(key, mapping):
if mapping_model not in mapping:
raise ModelParseException(
'Valid models are: %s or a collection UDF, not "%s"' %
- (mapping.keys(), model))
+ (list(mapping.keys()), model))
return model, mapping[mapping_model], field
@@ -594,7 +592,7 @@ def _parse_props(props, valuesdict):
params = {}
- for key, val in valuesdict.items():
+ for key, val in list(valuesdict.items()):
lookup, rhs = _parse_prop(props[key], valuesdict, key, val)
params[lookup] = rhs
@@ -606,12 +604,12 @@ def _parse_prop(predicate_props, valuesdict, key, val):
if not valid_values.issuperset(set(valuesdict.keys())):
raise ParseException(
'Cannot use these keys together: %s vs %s' %
- (valuesdict.keys(), valid_values))
+ (list(valuesdict.keys()), valid_values))
predicate_builder = predicate_props['predicate_builder']
param_pair = predicate_builder(val)
# Return a 2-tuple rather than a single-key dict
- return param_pair.items()[0]
+ return list(param_pair.items())[0]
def _parse_dict_props_for_mapping(mapping, valuesdict):
diff --git a/opentreemap/treemap/search_fields.py b/opentreemap/treemap/search_fields.py
index c0c2f9513..6d7dc672e 100644
--- a/opentreemap/treemap/search_fields.py
+++ b/opentreemap/treemap/search_fields.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.utils.encoding import force_text
from django.utils.translation import ugettext_lazy as _
@@ -151,7 +149,7 @@ def get_visible_fields(field_infos, user):
fields = copy.deepcopy(instance.search_config)
fields = {category: get_visible_fields(field_infos, user)
- for category, field_infos in fields.iteritems()}
+ for category, field_infos in fields.items()}
for field_info in fields.get('missing', []):
_set_missing_search_label(instance, field_info)
@@ -165,7 +163,7 @@ def get_visible_fields(field_infos, user):
for feature in sorted(instance.map_feature_types) if feature != 'Plot']
num = 0
- for filters in fields.itervalues():
+ for filters in fields.values():
for field in filters:
# It makes styling easier if every field has an identifier
id = "%s_%s" % (field.get('identifier', ''), num)
@@ -290,7 +288,7 @@ def get_udfc_search_fields(instance, user):
model_name = clz.__name__
if model_name not in ['Tree'] + instance.map_feature_types:
continue
- for k, v in clz.collection_udf_settings.items():
+ for k, v in list(clz.collection_udf_settings.items()):
udfds = (u for u in udf_defs(instance, model_name) if u.name == k)
for udfd in udfds:
if udf_write_level(iu, udfd) in (READ, WRITE):
diff --git a/opentreemap/treemap/species/codes.py b/opentreemap/treemap/species/codes.py
index f20f5c230..0800f4b6c 100644
--- a/opentreemap/treemap/species/codes.py
+++ b/opentreemap/treemap/species/codes.py
@@ -2,7 +2,7 @@
def all_itree_region_codes():
- return _CODES.keys()
+ return list(_CODES.keys())
def all_species_codes():
return species_codes_for_regions(all_itree_region_codes())
@@ -3518,4 +3518,4 @@ def get_itree_code(region_code, otm_code):
}
-ITREE_REGION_CHOICES = [(code, conf['name']) for code, conf in ITREE_REGIONS.items()]
+ITREE_REGION_CHOICES = [(code, conf['name']) for code, conf in list(ITREE_REGIONS.items())]
diff --git a/opentreemap/treemap/templatetags/auth_extras.py b/opentreemap/treemap/templatetags/auth_extras.py
index 1ec82eba3..2929a639d 100644
--- a/opentreemap/treemap/templatetags/auth_extras.py
+++ b/opentreemap/treemap/templatetags/auth_extras.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django import template
from django.conf import settings
@@ -182,7 +180,7 @@ def usercontent_tag(parser, token):
'expected format is: '
'usercontent for {user_identifier}')
- if isinstance(user_identifier, (int, long)):
+ if isinstance(user_identifier, int):
user_identifier = user_identifier
else:
if user_identifier[0] == '"'\
@@ -211,10 +209,10 @@ def render(self, context):
user_identifier = self.user_identifier
user_content = self.nodelist.render(context)
- if isinstance(user_identifier, (int, long)):
+ if isinstance(user_identifier, int):
if req_user.pk == user_identifier:
return user_content
- elif isinstance(user_identifier, basestring):
+ elif isinstance(user_identifier, str):
if req_user.username == user_identifier:
return user_content
else:
diff --git a/opentreemap/treemap/templatetags/form_extras.py b/opentreemap/treemap/templatetags/form_extras.py
index ec4da9ad7..5ac187646 100644
--- a/opentreemap/treemap/templatetags/form_extras.py
+++ b/opentreemap/treemap/templatetags/form_extras.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import re
@@ -55,24 +53,24 @@
FOREIGN_KEY_PREDICATE = 'IS'
-VALID_FIELD_KEYS = ','.join(FIELD_MAPPINGS.keys())
+VALID_FIELD_KEYS = ','.join(list(FIELD_MAPPINGS.keys()))
class Variable(Grammar):
- grammar = (G(b'"', WORD(b'^"'), b'"') | G(b"'", WORD(b"^'"), b"'")
- | WORD(b"a-zA-Z_", b"a-zA-Z0-9_."))
+ grammar = (G('"', WORD('^"'), '"') | G("'", WORD("^'"), "'")
+ | WORD("a-zA-Z_", "a-zA-Z0-9_."))
class Label(Grammar):
- grammar = (G(b'_("', WORD(b'^"'), b'")') | G(b"_('", WORD(b"^'"), b"')")
+ grammar = (G('_("', WORD('^"'), '")') | G("_('", WORD("^'"), "')")
| Variable)
class InlineEditGrammar(Grammar):
- grammar = (OR(G(OR(b"field", b"create"), OPTIONAL(Label)), b"search"),
- b"from", Variable, OPTIONAL(b"for", Variable),
- OPTIONAL(b"in", Variable), b"withtemplate", Variable,
- OPTIONAL(b"withhelp", Label))
+ grammar = (OR(G(OR("field", "create"), OPTIONAL(Label)), "search"),
+ "from", Variable, OPTIONAL("for", Variable),
+ OPTIONAL("in", Variable), "withtemplate", Variable,
+ OPTIONAL("withhelp", Label))
grammar_whitespace = True
@@ -333,7 +331,7 @@ def render(self, context):
field_template = get_template(_resolve_variable(
self.field_template, context)).template
- if not isinstance(identifier, basestring)\
+ if not isinstance(identifier, str)\
or not _identifier_regex.match(identifier):
raise template.TemplateSyntaxError(
'expected a string with the format "object_name.property" '
@@ -433,7 +431,7 @@ def _field_value(model, field_name, data_type):
elif data_type == 'float':
display_val = num_format(field_value)
else:
- display_val = unicode(field_value)
+ display_val = str(field_value)
context['field'] = {
'label': label,
@@ -535,7 +533,7 @@ def get_additional_context(self, field, model, field_name, search_query):
def update_field(settings):
# Identifier is lower-cased above to match the calling convention
# of update endpoints, so we shouldn't overwrite it :(
- field.update({k: v for k, v in settings.items()
+ field.update({k: v for k, v in list(settings.items())
if v is not None and k != 'identifier'})
search_settings = getattr(model, 'search_settings', {}).get(field_name)
diff --git a/opentreemap/treemap/templatetags/instance_config.py b/opentreemap/treemap/templatetags/instance_config.py
index 4f32fa92a..cf41cbd29 100644
--- a/opentreemap/treemap/templatetags/instance_config.py
+++ b/opentreemap/treemap/templatetags/instance_config.py
@@ -1,6 +1,4 @@
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
diff --git a/opentreemap/treemap/templatetags/urls.py b/opentreemap/treemap/templatetags/urls.py
index 129bd9176..aba48d6fe 100644
--- a/opentreemap/treemap/templatetags/urls.py
+++ b/opentreemap/treemap/templatetags/urls.py
@@ -1,4 +1,4 @@
-import urlparse
+import urllib.parse
from django import template
from django.http.request import QueryDict
@@ -9,13 +9,13 @@
class UrlHelper(object):
def __init__(self, full_path):
- url = urlparse.urlparse(full_path)
+ url = urllib.parse.urlparse(full_path)
self.path = url.path
self.fragment = url.fragment
self.query_dict = QueryDict(url.query, mutable=True)
def update_query_data(self, **kwargs):
- for key, val in kwargs.iteritems():
+ for key, val in kwargs.items():
if hasattr(val, '__iter__'):
self.query_dict.setlist(key, val)
else:
diff --git a/opentreemap/treemap/templatetags/util.py b/opentreemap/treemap/templatetags/util.py
index 50f14c526..59e248ccf 100644
--- a/opentreemap/treemap/templatetags/util.py
+++ b/opentreemap/treemap/templatetags/util.py
@@ -110,7 +110,7 @@ def audit_detail_link(audit):
"""
model = audit.model
- if model in MapFeature.subclass_dict().keys():
+ if model in list(MapFeature.subclass_dict().keys()):
model = 'mapfeature'
model = model.lower()
@@ -134,7 +134,7 @@ def terminology(model, instance):
@register.filter
def display_name(audit_or_model_or_name, instance=None):
audit = None
- if isinstance(audit_or_model_or_name, (Audit, basestring)):
+ if isinstance(audit_or_model_or_name, (Audit, str)):
if isinstance(audit_or_model_or_name, Audit):
audit = audit_or_model_or_name
name = audit.model
diff --git a/opentreemap/treemap/tests/__init__.py b/opentreemap/treemap/tests/__init__.py
index 02f1eeb5c..202856598 100644
--- a/opentreemap/treemap/tests/__init__.py
+++ b/opentreemap/treemap/tests/__init__.py
@@ -1,10 +1,8 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import logging
-from cStringIO import StringIO
+from io import StringIO
import subprocess
import shutil
import tempfile
@@ -432,7 +430,7 @@ def resource_path(self, name):
return path
def load_resource(self, name):
- return file(self.resource_path(name))
+ return open(self.resource_path(name))
def tearDown(self):
shutil.rmtree(self.photoDir)
diff --git a/opentreemap/treemap/tests/test_audit.py b/opentreemap/treemap/tests/test_audit.py
index 8b6a12e85..0a474f554 100644
--- a/opentreemap/treemap/tests/test_audit.py
+++ b/opentreemap/treemap/tests/test_audit.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import psycopg2
import json
@@ -92,12 +90,12 @@ def test_scope_model_method(self):
method_instance_2_trees = list(self.instance2.scope_model(Tree))
# Test that it returns the same as using the ORM
- self.assertEquals(orm_instance_1_trees, method_instance_1_trees)
- self.assertEquals(orm_instance_2_trees, method_instance_2_trees)
+ self.assertEqual(orm_instance_1_trees, method_instance_1_trees)
+ self.assertEqual(orm_instance_2_trees, method_instance_2_trees)
# Test that it didn't grab all trees
- self.assertNotEquals(list(all_trees), method_instance_1_trees)
- self.assertNotEquals(list(all_trees), method_instance_2_trees)
+ self.assertNotEqual(list(all_trees), method_instance_1_trees)
+ self.assertNotEqual(list(all_trees), method_instance_2_trees)
# Models that do not have any relation to Instance should
# raise an error if you attempt to scope them.
@@ -144,13 +142,13 @@ def assertAuditsEqual(self, exps, acts):
raise AssertionError('Missing audit record for %s' % act)
def make_audit(self, pk, field, old, new,
- action=Audit.Type.Insert, user=None, model=u'Tree'):
+ action=Audit.Type.Insert, user=None, model='Tree'):
if field:
- field = unicode(field)
+ field = str(field)
if old:
- old = unicode(old)
+ old = str(old)
if new:
- new = unicode(new)
+ new = str(new)
user = user or self.user1
@@ -531,7 +529,7 @@ def test_can_create_obj_even_if_some_fields_are_pending(self):
.filter(field_name__in=['id', 'geom', 'readonly'])\
.update(permission_level=FieldPermission.WRITE_DIRECTLY)
- self.assertEquals(Plot.objects.count(), 0)
+ self.assertEqual(Plot.objects.count(), 0)
# new_plot should be created, but there should be
# a pending record for length (and it should not be
@@ -542,7 +540,7 @@ def test_can_create_obj_even_if_some_fields_are_pending(self):
new_plot.save_with_user(self.pending_user)
- self.assertEquals(Plot.objects.count(), 1)
+ self.assertEqual(Plot.objects.count(), 1)
@skip("Insert pending approval not implemented at this time")
def test_insert_writes_when_approved(self):
@@ -553,8 +551,8 @@ def test_insert_writes_when_approved(self):
new_tree = Tree(plot=new_plot, instance=self.instance)
new_tree.save_with_user(self.pending_user)
- self.assertEquals(Plot.objects.count(), 0)
- self.assertEquals(Tree.objects.count(), 0)
+ self.assertEqual(Plot.objects.count(), 0)
+ self.assertEqual(Tree.objects.count(), 0)
approve_or_reject_audits_and_apply(
list(new_tree.audits()) + list(new_plot.audits()),
diff --git a/opentreemap/treemap/tests/test_auth.py b/opentreemap/treemap/tests/test_auth.py
index ecd9279e6..4098e2f02 100644
--- a/opentreemap/treemap/tests/test_auth.py
+++ b/opentreemap/treemap/tests/test_auth.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.tests import (RequestTestCase, make_instance,
make_user)
diff --git a/opentreemap/treemap/tests/test_cached_audit_info.py b/opentreemap/treemap/tests/test_cached_audit_info.py
index eda49634b..a4ec919eb 100644
--- a/opentreemap/treemap/tests/test_cached_audit_info.py
+++ b/opentreemap/treemap/tests/test_cached_audit_info.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import pytz
@@ -30,7 +28,7 @@ def setUp(self):
self.plot.save_with_user(self.user)
def max_audit_for_model_type(self, models):
- if isinstance(models, basestring):
+ if isinstance(models, str):
models = [models]
audits = Audit.objects.filter(model__in=models)\
.order_by('-created')
diff --git a/opentreemap/treemap/tests/test_dates.py b/opentreemap/treemap/tests/test_dates.py
index dc4bc5d99..d79e9f792 100644
--- a/opentreemap/treemap/tests/test_dates.py
+++ b/opentreemap/treemap/tests/test_dates.py
@@ -1,7 +1,4 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
from datetime import datetime
diff --git a/opentreemap/treemap/tests/test_ecobenefits.py b/opentreemap/treemap/tests/test_ecobenefits.py
index 6f6ed0ff7..db0cc6ae7 100644
--- a/opentreemap/treemap/tests/test_ecobenefits.py
+++ b/opentreemap/treemap/tests/test_ecobenefits.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
diff --git a/opentreemap/treemap/tests/test_hide_at_zoom.py b/opentreemap/treemap/tests/test_hide_at_zoom.py
index bbf09da32..a5e36b140 100644
--- a/opentreemap/treemap/tests/test_hide_at_zoom.py
+++ b/opentreemap/treemap/tests/test_hide_at_zoom.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.contrib.gis.geos import Point
from django.db.models import Count
diff --git a/opentreemap/treemap/tests/test_images.py b/opentreemap/treemap/tests/test_images.py
index b6da0468d..f06635a07 100644
--- a/opentreemap/treemap/tests/test_images.py
+++ b/opentreemap/treemap/tests/test_images.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from PIL import Image
diff --git a/opentreemap/treemap/tests/test_instance.py b/opentreemap/treemap/tests/test_instance.py
index e4bebf6be..1305106db 100644
--- a/opentreemap/treemap/tests/test_instance.py
+++ b/opentreemap/treemap/tests/test_instance.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
diff --git a/opentreemap/treemap/tests/test_json_field.py b/opentreemap/treemap/tests/test_json_field.py
index 0784ba468..e98194caf 100644
--- a/opentreemap/treemap/tests/test_json_field.py
+++ b/opentreemap/treemap/tests/test_json_field.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.tests import make_instance
from treemap.instance import Instance
@@ -58,8 +56,8 @@ def test_contains_lookup(self):
self.instance.config = ['a', 'b', 'c']
self.instance.save()
- self.assertEquals(set(Instance.objects.filter(config__contains='a')),
- {self.instance})
+ self.assertEqual(set(Instance.objects.filter(config__contains='a')),
+ {self.instance})
- self.assertEquals(set(Instance.objects.filter(config__contains='x')),
- set())
+ self.assertEqual(set(Instance.objects.filter(config__contains='x')),
+ set())
diff --git a/opentreemap/treemap/tests/test_management.py b/opentreemap/treemap/tests/test_management.py
index 763187fb8..0088d750b 100644
--- a/opentreemap/treemap/tests/test_management.py
+++ b/opentreemap/treemap/tests/test_management.py
@@ -1,9 +1,7 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
-from StringIO import StringIO
+
+from io import StringIO
from django.core.management import call_command
diff --git a/opentreemap/treemap/tests/test_map_feature.py b/opentreemap/treemap/tests/test_map_feature.py
index 019e6fa02..04b0590dc 100644
--- a/opentreemap/treemap/tests/test_map_feature.py
+++ b/opentreemap/treemap/tests/test_map_feature.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from contextlib import contextmanager
from unittest.case import skip
@@ -281,11 +279,12 @@ def test_all_ecobenefits(self):
plot_currencies = {
cat: benefit.get('currency', None)
- for cat, benefit in plot_benefits.items()}
+ for cat, benefit in list(plot_benefits.items())}
self.assertIsNotNone(min(plot_currencies.values()))
- expected_total_currency = sum(
- [benefit['currency'] for benefit in plot_benefits.values()]) - \
+ plot_benefits = [
+ benefit['currency'] for benefit in list(plot_benefits.values())]
+ expected_total_currency = sum(plot_benefits) - \
plot_benefits[BenefitCategory.CO2STORAGE]['currency'] + \
benefits['resource'][BenefitCategory.STORMWATER]['currency']
diff --git a/opentreemap/treemap/tests/test_middleware.py b/opentreemap/treemap/tests/test_middleware.py
index 1179fc7b0..102430340 100644
--- a/opentreemap/treemap/tests/test_middleware.py
+++ b/opentreemap/treemap/tests/test_middleware.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf import settings
from django.http import HttpResponseRedirect
@@ -27,7 +25,7 @@ def __init__(self, http_user_agent=None, path_info='/', other_params=None):
'PATH_INFO': path_info
}
if other_params:
- for k, v in other_params.items():
+ for k, v in list(other_params.items()):
self.META[k] = v
@@ -40,7 +38,7 @@ def _request_with_agent(self, *args, **kwargs):
def _assert_redirects(self, response, expected_url):
self.assertTrue(isinstance(response, HttpResponseRedirect))
- self.assertEquals(expected_url, response["Location"])
+ self.assertEqual(expected_url, response["Location"])
def test_detects_ie(self):
req, __ = self._request_with_agent(USER_AGENT_STRINGS.IE_7)
@@ -61,43 +59,43 @@ def test_sets_version_and_does_not_redirect_for_ie_11(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_11)
self.assertIsNone(res, 'Expected the middleware to return a None '
'response (no redirect) for IE 11')
- self.assertEquals(11, req.ie_version, 'Expected the middleware to '
- 'set "ie_version" to 11')
+ self.assertEqual(11, req.ie_version, 'Expected the middleware to '
+ 'set "ie_version" to 11')
def test_sets_version_and_redirects_ie_10(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_10)
self._assert_redirects(res,
settings.IE_VERSION_UNSUPPORTED_REDIRECT_PATH)
- self.assertEquals(10, req.ie_version, 'Expected the middleware to set '
- '"ie_version" to 10')
+ self.assertEqual(10, req.ie_version, 'Expected the middleware to set '
+ '"ie_version" to 10')
def test_sets_version_and_redirects_ie_9(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_9)
self._assert_redirects(res,
settings.IE_VERSION_UNSUPPORTED_REDIRECT_PATH)
- self.assertEquals(9, req.ie_version, 'Expected the middleware to set '
- '"ie_version" to 9')
+ self.assertEqual(9, req.ie_version, 'Expected the middleware to set '
+ '"ie_version" to 9')
def test_sets_version_and_redirects_ie_8(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_8)
self._assert_redirects(res,
settings.IE_VERSION_UNSUPPORTED_REDIRECT_PATH)
- self.assertEquals(8, req.ie_version, 'Expected the middleware to set '
- '"ie_version" to 8')
+ self.assertEqual(8, req.ie_version, 'Expected the middleware to set '
+ '"ie_version" to 8')
def test_sets_version_and_redirects_ie_7(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_7)
self._assert_redirects(res,
settings.IE_VERSION_UNSUPPORTED_REDIRECT_PATH)
- self.assertEquals(7, req.ie_version, 'Expected the middleware to set '
- '"ie_version" to 7')
+ self.assertEqual(7, req.ie_version, 'Expected the middleware to set '
+ '"ie_version" to 7')
def test_sets_version_and_redirects_ie_6(self):
req, res = self._request_with_agent(USER_AGENT_STRINGS.IE_6)
self._assert_redirects(res,
settings.IE_VERSION_UNSUPPORTED_REDIRECT_PATH)
- self.assertEquals(6, req.ie_version, 'Expected the middleware to set '
- '"ie_version" to 6')
+ self.assertEqual(6, req.ie_version, 'Expected the middleware to set '
+ '"ie_version" to 6')
def test_detects_json_and_does_not_redirect(self):
params = {'HTTP_ACCEPT': 'application/json;q=0.9,*/*;q=0.8'}
diff --git a/opentreemap/treemap/tests/test_models.py b/opentreemap/treemap/tests/test_models.py
index 3bb0eda35..02bb2a310 100644
--- a/opentreemap/treemap/tests/test_models.py
+++ b/opentreemap/treemap/tests/test_models.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.test import SimpleTestCase
from django.test.utils import override_settings
@@ -75,19 +73,19 @@ def test_changing_fields_changes_hash(self):
class SpeciesModelTests(OTMTestCase):
def test_scientific_name_genus(self):
s = Species(genus='Ulmus')
- self.assertEquals(s.scientific_name, 'Ulmus')
+ self.assertEqual(s.scientific_name, 'Ulmus')
def test_scientific_name_genus_species(self):
s = Species(genus='Ulmus', species='rubra')
- self.assertEquals(s.scientific_name, 'Ulmus rubra')
+ self.assertEqual(s.scientific_name, 'Ulmus rubra')
def test_scientific_name_genus_cultivar(self):
s = Species(genus='Ulmus', cultivar='Columella')
- self.assertEquals(s.scientific_name, "Ulmus 'Columella'")
+ self.assertEqual(s.scientific_name, "Ulmus 'Columella'")
def test_scientific_name_all(self):
s = Species(genus='Ulmus', species='rubra', cultivar='Columella')
- self.assertEquals(s.scientific_name, "Ulmus rubra 'Columella'")
+ self.assertEqual(s.scientific_name, "Ulmus rubra 'Columella'")
class ModelUnicodeTests(OTMTestCase):
@@ -142,42 +140,42 @@ def setUp(self):
self.reputation_metric.save_base()
def test_instance_model(self):
- self.assertEqual(unicode(self.instance), "Test Instance")
+ self.assertEqual(str(self.instance), "Test Instance")
def test_species_model(self):
self.assertEqual(
- unicode(self.species),
+ str(self.species),
"Test Common Name [Test Genus Test Species 'Test Cultivar']")
def test_user_model(self):
- self.assertEqual(unicode(self.user), 'commander')
+ self.assertEqual(str(self.user), 'commander')
def test_plot_model(self):
- self.assertEqual(unicode(self.plot),
+ self.assertEqual(str(self.plot),
'Plot (1.0, 1.0) 123 Main Street')
def test_tree_model(self):
- self.assertEqual(unicode(self.tree), '')
+ self.assertEqual(str(self.tree), '')
def test_boundary_model(self):
- self.assertEqual(unicode(self.boundary), 'Test Boundary')
+ self.assertEqual(str(self.boundary), 'Test Boundary')
def test_role_model(self):
- self.assertEqual(unicode(self.role), 'Test Role (%s)' % self.role.pk)
+ self.assertEqual(str(self.role), 'Test Role (%s)' % self.role.pk)
def test_field_permission_model(self):
- self.assertEqual(unicode(self.field_permission),
+ self.assertEqual(str(self.field_permission),
'Tree.readonly - Test Role (%s) - Read Only'
% self.role.pk)
def test_audit_model(self):
self.assertEqual(
- unicode(self.audit),
+ str(self.audit),
'pk=%s - action=Update - Tree.readonly:(1) - True => False'
% self.audit.pk)
def test_reputation_metric_model(self):
- self.assertEqual(unicode(self.reputation_metric),
+ self.assertEqual(str(self.reputation_metric),
'Test Instance - Tree - Test Action')
diff --git a/opentreemap/treemap/tests/test_perms.py b/opentreemap/treemap/tests/test_perms.py
index 41b371d4b..e619a5c0b 100644
--- a/opentreemap/treemap/tests/test_perms.py
+++ b/opentreemap/treemap/tests/test_perms.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
diff --git a/opentreemap/treemap/tests/test_search.py b/opentreemap/treemap/tests/test_search.py
index 8201c4e1a..3d6842f72 100644
--- a/opentreemap/treemap/tests/test_search.py
+++ b/opentreemap/treemap/tests/test_search.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import psycopg2
@@ -111,14 +109,14 @@ def _create_tree_and_plot(instance, user, point,
plot = Plot(geom=point, instance=instance)
if plotudfs:
- for k, v in plotudfs.iteritems():
+ for k, v in plotudfs.items():
plot.udfs[k] = v
plot.save_with_user(user)
tree = Tree(plot=plot, instance=instance)
if treeudfs:
- for k, v in treeudfs.iteritems():
+ for k, v in treeudfs.items():
tree.udfs[k] = v
tree.save_with_user(user)
@@ -528,14 +526,14 @@ def create_tree_and_plot(self, plotudfs=None, treeudfs=None):
plot = Plot(geom=self.p1, instance=self.instance)
if plotudfs:
- for k, v in plotudfs.iteritems():
+ for k, v in plotudfs.items():
plot.udfs[k] = v
plot.save_with_user(self.commander)
tree = Tree(plot=plot, instance=self.instance)
if treeudfs:
- for k, v in treeudfs.iteritems():
+ for k, v in treeudfs.items():
tree.udfs[k] = v
tree.save_with_user(self.commander)
diff --git a/opentreemap/treemap/tests/test_search_fields.py b/opentreemap/treemap/tests/test_search_fields.py
index 0403a4d11..1b924100c 100644
--- a/opentreemap/treemap/tests/test_search_fields.py
+++ b/opentreemap/treemap/tests/test_search_fields.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
@@ -19,17 +17,17 @@ def setUp(self):
def assert_search_present(self, **groups):
search = self.instance.advanced_search_fields(self.user)
- for group_name, field in groups.iteritems():
+ for group_name, field in groups.items():
self.assertIn(group_name, search)
search_group = search[group_name]
field_info = search_group[0]
if 'label' in field_info:
- field_info['label'] = unicode(field_info['label'])
+ field_info['label'] = str(field_info['label'])
if 'id' in field_info:
del field_info['id']
- self.assertEquals(field_info, field)
+ self.assertEqual(field_info, field)
def assert_search_absent(self, group_name):
search = self.instance.advanced_search_fields(self.user)
@@ -86,15 +84,15 @@ def setUp(self):
def assert_search_present(self, **groups):
search = mobile_search_fields(self.instance)
- for group_name, field in groups.iteritems():
+ for group_name, field in groups.items():
self.assertIn(group_name, search)
search_group = search[group_name]
field_info = search_group[0]
if 'label' in field_info:
- field_info['label'] = unicode(field_info['label'])
+ field_info['label'] = str(field_info['label'])
- self.assertEquals(field_info, field)
+ self.assertEqual(field_info, field)
def test_missing_filters(self):
self.instance.mobile_search_fields = {
diff --git a/opentreemap/treemap/tests/test_species.py b/opentreemap/treemap/tests/test_species.py
index e80f91c95..cdc0fbd9c 100644
--- a/opentreemap/treemap/tests/test_species.py
+++ b/opentreemap/treemap/tests/test_species.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.tests.base import OTMTestCase
from treemap.species import species_for_otm_code, species_for_scientific_name
diff --git a/opentreemap/treemap/tests/test_templatetags.py b/opentreemap/treemap/tests/test_templatetags.py
index 6291e778e..e51db8c6f 100644
--- a/opentreemap/treemap/tests/test_templatetags.py
+++ b/opentreemap/treemap/tests/test_templatetags.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from copy import deepcopy
import tempfile
@@ -619,11 +617,11 @@ def test_create_uses_new_model(self):
content = template.render(Context({
'request': {'user': self.observer, 'instance': self.instance}
})).strip()
- self.assertEqual(content, unicode(Plot().length))
+ self.assertEqual(content, str(Plot().length))
def test_search_uses_new_model(self):
self.assert_search_context_value(
- self.observer, 'field.value', unicode(Plot().length),
+ self.observer, 'field.value', str(Plot().length),
{'identifier': 'Plot.length'})
def test_search_adds_field_config(self):
@@ -646,7 +644,7 @@ def test_search_adds_field_config(self):
def test_search_gets_default_label_when_none_given(self):
self.assert_search_context_value(
self.observer, 'field.label',
- unicode(Plot._meta.get_field('length').verbose_name),
+ str(Plot._meta.get_field('length').verbose_name),
{'identifier': 'Plot.length', 'label': None})
def test_search_fields_get_added_only_for_valid_json_matches(self):
diff --git a/opentreemap/treemap/tests/test_udfs.py b/opentreemap/treemap/tests/test_udfs.py
index bf8621fe6..0e32a50d0 100644
--- a/opentreemap/treemap/tests/test_udfs.py
+++ b/opentreemap/treemap/tests/test_udfs.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
from random import shuffle
@@ -67,9 +65,9 @@ def setUp(self):
def test_set_item_to_none_removes_key(self):
self.d['Test choice'] = 'a'
- self.assertEqual(1, len(self.d.keys()))
+ self.assertEqual(1, len(list(self.d.keys())))
self.d['Test choice'] = None
- self.assertEqual(0, len(self.d.keys()))
+ self.assertEqual(0, len(list(self.d.keys())))
def test_setting_nonexistant_key_to_none_is_a_noop(self):
# Should not raise an error
@@ -147,7 +145,7 @@ def setUp(self):
def create_and_save_with_choice(c, n=1):
plots = []
- for i in xrange(n):
+ for i in range(n):
plot = Plot(geom=self.p, instance=self.instance)
plot.udfs['Test choice'] = c
plot.save_with_user(self.commander_user)
@@ -1200,7 +1198,7 @@ def test_can_delete(self):
all_new_stews = reloaded_plot.udfs['Stewardship']
# Keep only 'prune' (note that UDF collection values are unordered)
- new_stews = filter(lambda v: v['action'] == 'prune', all_new_stews)
+ new_stews = [v for v in all_new_stews if v['action'] == 'prune']
reloaded_plot.udfs['Stewardship'] = new_stews
reloaded_plot.save_with_user(self.commander_user)
@@ -1304,7 +1302,7 @@ def test_delete_udf_deletes_mobile_api_field(self):
udf_def.delete()
updated_instance = Instance.objects.get(pk=self.instance.pk)
- self.assertEquals(
+ self.assertEqual(
0, len(updated_instance.mobile_api_fields[0]['field_keys']))
def test_delete_cudf_deletes_mobile_api_field_group(self):
@@ -1341,13 +1339,13 @@ def test_delete_cudf_deletes_mobile_api_field_group(self):
tree_udf_def.delete()
updated_instance = Instance.objects.get(pk=self.instance.pk)
- self.assertEquals(1, len(
+ self.assertEqual(1, len(
updated_instance.mobile_api_fields[1]['collection_udf_keys']))
plot_udf_def.delete()
updated_instance = Instance.objects.get(pk=self.instance.pk)
- self.assertEquals(1, len(updated_instance.mobile_api_fields))
+ self.assertEqual(1, len(updated_instance.mobile_api_fields))
class UdfCRUTestCase(OTMTestCase):
diff --git a/opentreemap/treemap/tests/test_units.py b/opentreemap/treemap/tests/test_units.py
index c78c2e392..4e750c912 100644
--- a/opentreemap/treemap/tests/test_units.py
+++ b/opentreemap/treemap/tests/test_units.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.test.utils import override_settings
diff --git a/opentreemap/treemap/tests/test_urls.py b/opentreemap/treemap/tests/test_urls.py
index a47884a06..e76892091 100644
--- a/opentreemap/treemap/tests/test_urls.py
+++ b/opentreemap/treemap/tests/test_urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import os
import json
@@ -66,7 +64,7 @@ def assert_redirects_to_static_file(self, url, expected_url):
self.assert_static_file_exists(expected_url)
def assert_static_file_exists(self, url):
- self.assertEquals(url[:8], '/static/')
+ self.assertEqual(url[:8], '/static/')
path = os.path.join(STATIC_ROOT, url[8:])
self.assertTrue(os.path.exists(path))
diff --git a/opentreemap/treemap/tests/test_util.py b/opentreemap/treemap/tests/test_util.py
index 73c117a0e..20c2b385a 100644
--- a/opentreemap/treemap/tests/test_util.py
+++ b/opentreemap/treemap/tests/test_util.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.contrib.sessions.middleware import SessionMiddleware
from django.test.utils import override_settings
diff --git a/opentreemap/treemap/tests/test_views.py b/opentreemap/treemap/tests/test_views.py
index 32b26a9c1..7500df622 100644
--- a/opentreemap/treemap/tests/test_views.py
+++ b/opentreemap/treemap/tests/test_views.py
@@ -1,11 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import os
import json
-from StringIO import StringIO
+from io import StringIO
import psycopg2
from django.test.utils import override_settings
@@ -979,7 +977,7 @@ def test_plot_with_tree(self):
.has_itree_region()
context = plot_detail(request, self.instance, plot_w_tree.pk)
- self.assertEquals(plot_w_tree, context['plot'])
+ self.assertEqual(plot_w_tree, context['plot'])
self.assertIn('benefits', context)
def test_plot_without_tree(self):
@@ -988,7 +986,7 @@ def test_plot_without_tree(self):
context = self.get_plot_context(plot_wo_tree)
- self.assertEquals(plot_wo_tree, context['plot'])
+ self.assertEqual(plot_wo_tree, context['plot'])
self.assertNotIn('benefits', context)
def test_system_user_hidden_from_audit_history(self):
@@ -1056,8 +1054,8 @@ def test_progress_starts_at_25(self):
# Having a plot location counts at 25%
context = self.get_plot_context(self.plot_wo_tree)
- self.assertEquals(25, context['progress_percent'])
- self.assertEquals(4, len(context['progress_messages']))
+ self.assertEqual(25, context['progress_percent'])
+ self.assertEqual(4, len(context['progress_messages']))
def test_progress_messages_decrease_when_plot_has_tree(self):
wo_tree_context = self.get_plot_context(self.plot_wo_tree)
@@ -1327,7 +1325,7 @@ def _assert_dicts_equal(self, expected, actual):
self.assertEqual(len(expected), len(actual), "Number of dicts")
for expected, generated in zip(expected, actual):
- for k, v in expected.iteritems():
+ for k, v in expected.items():
self.assertEqual(v, generated[k], "key [%s]" % k)
def check_audits(self, url, dicts, user=None):
@@ -1714,11 +1712,11 @@ def setUp(self):
js_species['other_part_of_name'] = species.other_part_of_name
def test_get_species_list(self):
- self.assertEquals(species_list(make_request(), self.instance),
- self.species_json)
+ self.assertEqual(species_list(make_request(), self.instance),
+ self.species_json)
def test_get_species_list_max_items(self):
- self.assertEquals(
+ self.assertEqual(
species_list(make_request({'max_items': 3}), self.instance),
self.species_json[:3])
@@ -1735,11 +1733,11 @@ def setUp(self):
def test_get_by_username(self):
context = user(make_request(), self.joe.username)
- self.assertEquals(self.joe.username, context['user'].username,
- 'the user view should return a dict with user with '
- '"username" set to %s ' % self.joe.username)
- self.assertEquals(list, type(context['audits']),
- 'the user view should return a list of audits')
+ self.assertEqual(self.joe.username, context['user'].username,
+ 'the user view should return a dict with user with '
+ '"username" set to %s ' % self.joe.username)
+ self.assertEqual(list, type(context['audits']),
+ 'the user view should return a list of audits')
def test_get_with_invalid_username_returns_404(self):
self.assertRaises(Http404, user, make_request(),
@@ -1781,7 +1779,7 @@ def setUp(self):
def assertOk(self, response):
if (issubclass(response.__class__, HttpResponse)):
context = json.loads(response.content)
- self.assertEquals(200, response.status_code)
+ self.assertEqual(200, response.status_code)
else:
context = response
self.assertTrue('ok' in context)
@@ -1790,7 +1788,7 @@ def assertOk(self, response):
def assertBadRequest(self, response):
self.assertTrue(issubclass(response.__class__, HttpResponse))
- self.assertEquals(400, response.status_code)
+ self.assertEqual(400, response.status_code)
context = json.loads(response.content)
self.assertFalse('ok' in context)
self.assertTrue('globalErrors' in context)
@@ -1805,9 +1803,9 @@ def test_change_first_name(self):
update = b'{"user.first_name": "Joseph"}'
self.assertOk(update_user(
make_request(user=self.joe, body=update), self.joe))
- self.assertEquals('Joseph',
- User.objects.get(username='joe').first_name,
- 'The first_name was not updated')
+ self.assertEqual('Joseph',
+ User.objects.get(username='joe').first_name,
+ 'The first_name was not updated')
def test_expects_keys_prefixed_with_user(self):
self.joe.name = 'Joe'
@@ -1851,11 +1849,11 @@ def test_get_by_username_redirects(self):
self.commander.username)
expected_url = '/users/%s/?instance_id=%d' %\
(self.commander.username, self.instance.id)
- self.assertEquals(res.status_code, 302, "should be a 302 Found \
+ self.assertEqual(res.status_code, 302, "should be a 302 Found \
temporary redirect")
- self.assertEquals(expected_url, res['Location'],
- 'the view should redirect to %s not %s ' %
- (expected_url, res['Location']))
+ self.assertEqual(expected_url, res['Location'],
+ 'the view should redirect to %s not %s ' %
+ (expected_url, res['Location']))
def test_get_with_invalid_username_redirects(self):
test_username = 'no_way_username'
@@ -1864,11 +1862,11 @@ def test_get_with_invalid_username_redirects(self):
test_username)
expected_url = '/users/%s/?instance_id=%d' %\
(test_username, self.instance.id)
- self.assertEquals(res.status_code, 302, "should be a 302 Found \
+ self.assertEqual(res.status_code, 302, "should be a 302 Found \
temporary redirect")
- self.assertEquals(expected_url, res['Location'],
- 'the view should redirect to %s not %s ' %
- (expected_url, res['Location']))
+ self.assertEqual(expected_url, res['Location'],
+ 'the view should redirect to %s not %s ' %
+ (expected_url, res['Location']))
class SettingsJsViewTests(ViewTestCase):
@@ -1998,18 +1996,18 @@ def test_sends_email_for_existing_user(self):
resp = forgot_username(make_request({'email': self.user.email},
method='POST'))
- self.assertEquals(resp, {'email': self.user.email})
+ self.assertEqual(resp, {'email': self.user.email})
- self.assertEquals(len(mail.outbox), 1)
+ self.assertEqual(len(mail.outbox), 1)
self.assertIn(self.user.username, mail.outbox[0].body)
def test_no_email_if_doesnt_exist(self):
resp = forgot_username(make_request({'email': 'doesnt@exist.co.uk'},
method='POST'))
- self.assertEquals(resp, {'email': 'doesnt@exist.co.uk'})
+ self.assertEqual(resp, {'email': 'doesnt@exist.co.uk'})
- self.assertEquals(len(mail.outbox), 0)
+ self.assertEqual(len(mail.outbox), 0)
class UserInstancesViewTests(OTMTestCase):
@@ -2037,17 +2035,17 @@ def setUp(self):
def test_a_views_a(self):
# User a views their own instances
instances = get_user_instances(self.user_a, self.user_a, self.c)
- self.assertEquals(list(instances), [self.a, self.ab, self.c])
+ self.assertEqual(list(instances), [self.a, self.ab, self.c])
def test_a_views_b(self):
# User a views b's instances
instances = get_user_instances(self.user_a, self.user_b, self.c)
- self.assertEquals(list(instances), [self.ab, self.b_public])
+ self.assertEqual(list(instances), [self.ab, self.b_public])
def test_anonymous_views_b(self):
# User anonymous views b's instances
instances = get_user_instances(None, self.user_b, self.c)
- self.assertEquals(list(instances), [self.b_public])
+ self.assertEqual(list(instances), [self.b_public])
@override_settings(VIEWABLE_INSTANCES_FUNCTION=None)
diff --git a/opentreemap/treemap/tests/ui/__init__.py b/opentreemap/treemap/tests/ui/__init__.py
index 5a425853a..aae98e267 100644
--- a/opentreemap/treemap/tests/ui/__init__.py
+++ b/opentreemap/treemap/tests/ui/__init__.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import importlib
from time import sleep
@@ -179,7 +177,7 @@ def wait_for_input_value(self, element_or_selector, value, timeout=10):
return element
def _get_element(self, element_or_selector):
- if isinstance(element_or_selector, basestring):
+ if isinstance(element_or_selector, str):
return self.find(element_or_selector)
else:
return element_or_selector
@@ -188,7 +186,7 @@ def _get_element(self, element_or_selector):
@override_settings(**test_settings)
class TreemapUITestCase(UITestCase):
def assertElementVisibility(self, element, visible):
- if isinstance(element, basestring):
+ if isinstance(element, str):
element = self.find_id(element)
wait = (self.wait_until_visible if visible
else self.wait_until_invisible)
diff --git a/opentreemap/treemap/tests/ui/plot_detail/cases.py b/opentreemap/treemap/tests/ui/plot_detail/cases.py
index 8b244b025..bb3cd99ed 100644
--- a/opentreemap/treemap/tests/ui/plot_detail/cases.py
+++ b/opentreemap/treemap/tests/ui/plot_detail/cases.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from selenium.common.exceptions import ElementNotVisibleException
diff --git a/opentreemap/treemap/tests/ui/plot_detail/uitest_add.py b/opentreemap/treemap/tests/ui/plot_detail/uitest_add.py
index 66d63141e..8bfd131c3 100644
--- a/opentreemap/treemap/tests/ui/plot_detail/uitest_add.py
+++ b/opentreemap/treemap/tests/ui/plot_detail/uitest_add.py
@@ -1,11 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.models import Tree
-from cases import PlotDetailUITestCase
+from .cases import PlotDetailUITestCase
class PlotAddTest(PlotDetailUITestCase):
diff --git a/opentreemap/treemap/tests/ui/plot_detail/uitest_delete.py b/opentreemap/treemap/tests/ui/plot_detail/uitest_delete.py
index f561b85ec..585bc7905 100644
--- a/opentreemap/treemap/tests/ui/plot_detail/uitest_delete.py
+++ b/opentreemap/treemap/tests/ui/plot_detail/uitest_delete.py
@@ -1,13 +1,11 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from unittest.case import skip
from treemap.models import Tree
-from cases import PlotDetailDeleteUITestCase
+from .cases import PlotDetailDeleteUITestCase
class PlotEditDeleteTest(PlotDetailDeleteUITestCase):
diff --git a/opentreemap/treemap/tests/ui/plot_detail/uitest_edit.py b/opentreemap/treemap/tests/ui/plot_detail/uitest_edit.py
index 0d353d4e0..56df901df 100644
--- a/opentreemap/treemap/tests/ui/plot_detail/uitest_edit.py
+++ b/opentreemap/treemap/tests/ui/plot_detail/uitest_edit.py
@@ -1,11 +1,9 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from treemap.models import Plot, Tree
-from cases import PlotDetailUITestCase
+from .cases import PlotDetailUITestCase
class PlotEditTest(PlotDetailUITestCase):
diff --git a/opentreemap/treemap/tests/ui/ui_test_urls.py b/opentreemap/treemap/tests/ui/ui_test_urls.py
index 493f0a711..c26a4448b 100644
--- a/opentreemap/treemap/tests/ui/ui_test_urls.py
+++ b/opentreemap/treemap/tests/ui/ui_test_urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import include, url
from django.http import HttpResponse
diff --git a/opentreemap/treemap/tests/ui/uitest_map.py b/opentreemap/treemap/tests/ui/uitest_map.py
index 829a72919..3758897ec 100644
--- a/opentreemap/treemap/tests/ui/uitest_map.py
+++ b/opentreemap/treemap/tests/ui/uitest_map.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from time import sleep
from unittest.case import skip
diff --git a/opentreemap/treemap/tests/ui/uitest_registration_views.py b/opentreemap/treemap/tests/ui/uitest_registration_views.py
index 081535dba..bb0650bb6 100644
--- a/opentreemap/treemap/tests/ui/uitest_registration_views.py
+++ b/opentreemap/treemap/tests/ui/uitest_registration_views.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from time import sleep
from django.core.urlresolvers import reverse
diff --git a/opentreemap/treemap/tests/unit_test_urls.py b/opentreemap/treemap/tests/unit_test_urls.py
index 9043cb541..85a17fbe0 100644
--- a/opentreemap/treemap/tests/unit_test_urls.py
+++ b/opentreemap/treemap/tests/unit_test_urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import include, url
from django.template import Template, RequestContext
diff --git a/opentreemap/treemap/udf.py b/opentreemap/treemap/udf.py
index 862c66304..d02bbfbee 100644
--- a/opentreemap/treemap/udf.py
+++ b/opentreemap/treemap/udf.py
@@ -48,9 +48,6 @@
http://stackoverflow.com/a/43745677/14405
'''
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
import json
import copy
@@ -276,7 +273,7 @@ def as_dict(self, *args, **kwargs):
base_model_dict = super(
UserDefinedCollectionValue, self).as_dict(*args, **kwargs)
- for field, value in self.data.iteritems():
+ for field, value in self.data.items():
base_model_dict['udf:' + field] = value
return base_model_dict
@@ -323,7 +320,7 @@ def save_with_user(self, user, *args, **kwargs):
if field_perm.permission_level == FieldPermission.WRITE_WITH_AUDIT:
model_id = _reserve_model_id(UserDefinedCollectionValue)
pending = True
- for field, (oldval, __) in updated_fields.iteritems():
+ for field, (oldval, __) in updated_fields.items():
self.apply_change(field, oldval)
else:
pending = False
@@ -334,7 +331,7 @@ def save_with_user(self, user, *args, **kwargs):
if audit_type == Audit.Type.Insert:
updated_fields['id'] = [None, model_id]
- for field, (old_val, new_val) in updated_fields.iteritems():
+ for field, (old_val, new_val) in updated_fields.items():
Audit.objects.create(
current_value=new_val,
previous_value=old_val,
@@ -423,7 +420,7 @@ def _validate_and_update_choice(
self, datatype, old_choice_value, new_choice_value):
# Prevent validation errors when the choice value is numeric.
- old_choice_value = unicode(old_choice_value)
+ old_choice_value = str(old_choice_value)
if datatype['type'] not in ('choice', 'multichoice'):
raise ValidationError(
@@ -532,10 +529,8 @@ def _update_choices_on_audits(
def _list_replace_or_remove(self, l, old, new):
if l is None:
return None
- new_l = filter(
- None,
- [(new if choice == old else choice)
- for choice in l])
+ new_l = [_f for _f
+ in [(new if choice == old else choice) for choice in l] if _f]
return new_l or None
def add_choice(self, new_choice_value, name=None):
@@ -547,7 +542,7 @@ def add_choice(self, new_choice_value, name=None):
datatypes = {d['name']: d for d in self.datatype_dict}
datatypes[name]['choices'].append(new_choice_value)
- self.datatype = json.dumps(datatypes.values())
+ self.datatype = json.dumps(list(datatypes.values()))
self.save()
else:
if name is not None:
@@ -569,7 +564,7 @@ def replace_collection_field_choices(self, field_name, new_choices):
if choice not in new_choices:
self.delete_choice(choice, field_name)
field['choices'] = new_choices
- self.datatype = json.dumps(datatypes.values())
+ self.datatype = json.dumps(list(datatypes.values()))
self.save()
@transaction.atomic
@@ -590,7 +585,7 @@ def update_choice(
datatypes[name], old_choice_value, new_choice_value)
datatypes[name] = datatype
- self.datatype = json.dumps(datatypes.values())
+ self.datatype = json.dumps(list(datatypes.values()))
self.save()
vals = UserDefinedCollectionValue\
@@ -735,7 +730,7 @@ def _validate_single_datatype(self, datatype):
raise ValidationError(_('Missing choices key'))
for choice in choices:
- if not isinstance(choice, basestring):
+ if not isinstance(choice, str):
raise ValidationError(_('Choice must be a string'))
if choice is None or choice.strip() == '':
raise ValidationError(_('Empty choice is not allowed'))
@@ -976,11 +971,11 @@ def _validate(val):
fieldname=self.name)
if values is None:
return None
- if isinstance(values, basestring):
+ if isinstance(values, str):
# A single string is valid JSON. Wrap as a list for
# consistency
values = [values]
- map(_validate, values)
+ list(map(_validate, values))
return values
else:
return value
@@ -992,7 +987,7 @@ def clean_collection(self, data):
errors = {}
for entry in data:
- for subfield_name, subfield_val in entry.iteritems():
+ for subfield_name, subfield_val in entry.items():
if subfield_name == 'id':
continue
@@ -1087,7 +1082,7 @@ def get_prep_value(self, value):
return {key: udfds[key].reverse_clean(val)
for (key, val)
- in super(UDFDictionary, udf_dict).iteritems()}
+ in super(UDFDictionary, udf_dict).items()}
return value
@@ -1213,7 +1208,7 @@ def _prefixed_name(self, key):
def __contains__(self, key):
if super(UDFDictionary, self).__contains__(key):
return True
- return key in self.collection_fields.keys()
+ return key in list(self.collection_fields.keys())
def __getitem__(self, key):
udfd = self._get_udf_or_error(key)
@@ -1264,7 +1259,7 @@ def get(self, key, default, do_not_clean=False):
def iteritems(self):
model_instance = getattr(self, 'instance', None)
- for k, v in super(UDFDictionary, self).iteritems():
+ for k, v in super(UDFDictionary, self).items():
if v is not None:
yield k, v
if model_instance is not None:
@@ -1281,10 +1276,10 @@ def __repr__(self):
model_type = getattr(self, '_model_type',
self.__class__.__name__)
return '{}.udfs({})'.format(
- model_type, pformat(dict(self.items())))
+ model_type, pformat(dict(list(self.items()))))
-class UDFModel(UserTrackable, models.Model):
+class UDFModel(UserTrackable, models.Model, metaclass=UDFModelBase):
"""
Classes that extend this model gain support for scalar UDF
fields via the `udfs` field.
@@ -1294,8 +1289,6 @@ class UDFModel(UserTrackable, models.Model):
Authorizable mixins
"""
- __metaclass__ = UDFModelBase
-
udfs = UDFPostgresField(
db_index=True,
blank=True,
@@ -1471,7 +1464,7 @@ def visible_collection_udfs_audit_names(self, user):
def collection_udf_settings(cls):
return {
k: v for k, v in
- getattr(cls, 'udf_settings', {}).items()
+ list(getattr(cls, 'udf_settings', {}).items())
if v.get('iscollection')}
@property
@@ -1498,7 +1491,7 @@ def _format_value(value):
# For collection UDFs, we need to format each subvalue
# inside each dictionary
value = [{k: _format_value(val)
- for k, val in sub_dict.iteritems()}
+ for k, val in sub_dict.items()}
for sub_dict in value]
else:
value = _format_value(value)
@@ -1518,13 +1511,13 @@ def save_with_user(self, user, *args, **kwargs):
collection_fields = self.udfs._base_collection_fields(clean=False)
dirty_collection_values = {
field_name: values
- for field_name, values in collection_fields.iteritems()
+ for field_name, values in collection_fields.items()
if field_name in self.dirty_collection_udfs}
fields = {field.name: field
for field in self.get_user_defined_fields()}
- for field_name, values in dirty_collection_values.iteritems():
+ for field_name, values in dirty_collection_values.items():
field = fields[field_name]
ids_specified = []
@@ -1534,7 +1527,7 @@ def save_with_user(self, user, *args, **kwargs):
if udcv.data != value_dict:
udcv.data = {
key: field.reverse_clean(val, key=key)
- for key, val in value_dict.items()}
+ for key, val in list(value_dict.items())}
udcv.save_with_user(user)
ids_specified.append(udcv.pk)
@@ -1574,11 +1567,11 @@ def clean_udfs(self):
errors = {}
keys_to_delete = [
- key for key, field in scalar_fields.iteritems()
+ key for key, field in scalar_fields.items()
if field is None]
for key in keys_to_delete:
del self.udfs[key]
- for key, field in scalar_fields.iteritems():
+ for key, field in scalar_fields.items():
val = self.udfs.get(key, None, do_not_clean=True)
try:
field.clean_value(val)
@@ -1590,7 +1583,7 @@ def clean_udfs(self):
# without the attribute `collection_data_loaded`, so use `getattr`.
if getattr(self.udfs, 'collection_data_loaded', None):
collection_data = self.udfs.collection_fields
- for collection_field_name, data in collection_data.iteritems():
+ for collection_field_name, data in collection_data.items():
collection_field = collection_fields.get(
collection_field_name, None)
diff --git a/opentreemap/treemap/units.py b/opentreemap/treemap/units.py
index 4e4a9affd..65df7c907 100644
--- a/opentreemap/treemap/units.py
+++ b/opentreemap/treemap/units.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import copy
@@ -130,10 +128,10 @@ def convert_to_database_units(self):
"sq_m": {"sq_m": 1, "sq_ft": 10.7639}
}
_unit_conversions["ft"] = {u: v * 12 for (u, v)
- in _unit_conversions["in"].iteritems()}
+ in _unit_conversions["in"].items()}
_unit_conversions["sq_ft"] = {
u: v / _unit_conversions["sq_m"]["sq_ft"]
- for u, v in _unit_conversions["sq_m"].iteritems()}
+ for u, v in _unit_conversions["sq_m"].items()}
def get_unit_name(abbrev):
@@ -146,7 +144,7 @@ def get_unit_abbreviation(abbrev):
def get_convertible_units(category_name, value_name):
abbrev = _get_display_default(category_name, value_name, 'units')
- return _unit_conversions[abbrev].keys()
+ return list(_unit_conversions[abbrev].keys())
def _get_display_default(category_name, value_name, key):
@@ -212,7 +210,7 @@ def _is_configured_for(keys, category_name, value_name):
defaults = settings.DISPLAY_DEFAULTS
return (category_name in defaults
and value_name in defaults[category_name]
- and keys & defaults[category_name][value_name].viewkeys())
+ and keys & defaults[category_name][value_name].keys())
is_convertible_or_formattable = partial(_is_configured_for,
@@ -232,7 +230,7 @@ def storage_to_instance_units_factor(instance, category_name, value_name):
instance_unit = get_units(instance, category_name, value_name)
conversion_dict = _unit_conversions.get(storage_unit)
- if instance_unit not in conversion_dict.keys():
+ if instance_unit not in list(conversion_dict.keys()):
raise Exception("Cannot convert from [%s] to [%s]"
% (storage_unit, instance_unit))
diff --git a/opentreemap/treemap/urls.py b/opentreemap/treemap/urls.py
index a148d4a41..7c41acb5e 100644
--- a/opentreemap/treemap/urls.py
+++ b/opentreemap/treemap/urls.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
from django.conf.urls import url
diff --git a/opentreemap/treemap/util.py b/opentreemap/treemap/util.py
index e2ffc1d0c..8b2f57b93 100644
--- a/opentreemap/treemap/util.py
+++ b/opentreemap/treemap/util.py
@@ -1,12 +1,10 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import datetime
from collections import OrderedDict
-from urlparse import urlparse
+from urllib.parse import urlparse
from django.apps import apps
from django.shortcuts import get_object_or_404, resolve_url
@@ -74,7 +72,7 @@ def add_visited_instance(request, instance):
visited_instances[instance.pk] = stamp
# turn back into a list of tuples
- request.session['visited_instances'] = visited_instances.items()
+ request.session['visited_instances'] = list(visited_instances.items())
request.session.modified = True
@@ -134,7 +132,7 @@ def package_field_errors(model_name, validation_error):
Return a version keyed by "objectname.fieldname" instead of "fieldname".
"""
dict = {'%s.%s' % (to_object_name(model_name), field): msgs
- for (field, msgs) in validation_error.message_dict.iteritems()}
+ for (field, msgs) in validation_error.message_dict.items()}
return dict
@@ -193,7 +191,7 @@ def get_csv_response(filename):
# add BOM to support CSVs in MS Excel
# http://en.wikipedia.org/wiki/Byte_order_mark
- response.write(u'\ufeff'.encode('utf8'))
+ response.write('\ufeff'.encode('utf8'))
return response
diff --git a/opentreemap/treemap/views/map_feature.py b/opentreemap/treemap/views/map_feature.py
index b3cd7f007..31a9d0cd1 100644
--- a/opentreemap/treemap/views/map_feature.py
+++ b/opentreemap/treemap/views/map_feature.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import json
import hashlib
@@ -296,7 +294,7 @@ def skip_setting_value_on_tree(value, tree):
rev_updates = ['universal_rev']
old_geom = feature.geom
- for (identifier, value) in request_dict.iteritems():
+ for (identifier, value) in request_dict.items():
split_template = 'Malformed request - invalid field %s'
object_name, field = dotted_split(identifier, 2,
failure_format_string=split_template)
@@ -322,7 +320,7 @@ def skip_setting_value_on_tree(value, tree):
if field == 'species' and value:
value = get_object_or_404(Species,
instance=feature.instance, pk=value)
- elif field == 'plot' and value == unicode(feature.pk):
+ elif field == 'plot' and value == str(feature.pk):
value = feature
else:
raise ValueError(
diff --git a/opentreemap/treemap/views/misc.py b/opentreemap/treemap/views/misc.py
index 608bac6f7..2a1d66119 100644
--- a/opentreemap/treemap/views/misc.py
+++ b/opentreemap/treemap/views/misc.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import string
import re
@@ -181,7 +179,7 @@ def annotate_species_dict(sdict):
display_name = "%s [%s]" % (sdict['common_name'],
sci_name)
- tokens = tokenize(species)
+ tokens = tokenize(sdict)
sdict.update({
'scientific_name': sci_name,
@@ -207,7 +205,7 @@ def compile_scss(request):
scss = "$staticUrl: '/static/';\n"
# We can probably be a bit looser with what we allow here in the future if
# we need to, but we must do some checking so that libsass doesn't explode
- for key, value in request.GET.items():
+ for key, value in list(request.GET.items()):
if _SCSS_VAR_NAME_RE.match(key) and COLOR_RE.match(value):
scss += '$%s: #%s;\n' % (key, value)
elif key == 'url':
diff --git a/opentreemap/treemap/views/tree.py b/opentreemap/treemap/views/tree.py
index a70304a85..99b10c94c 100644
--- a/opentreemap/treemap/views/tree.py
+++ b/opentreemap/treemap/views/tree.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import hashlib
diff --git a/opentreemap/treemap/views/user.py b/opentreemap/treemap/views/user.py
index b7b731820..ea2f2c3ce 100644
--- a/opentreemap/treemap/views/user.py
+++ b/opentreemap/treemap/views/user.py
@@ -1,7 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import print_function
-from __future__ import unicode_literals
-from __future__ import division
+
import collections
@@ -227,7 +225,7 @@ def user(request, username):
public_fields = []
private_fields = []
- for field in USER_PROFILE_FIELDS.values():
+ for field in list(USER_PROFILE_FIELDS.values()):
field_tuple = (field['label'], field['identifier'],
field.get('template', "treemap/field/div.html"))
if field['visibility'] == 'public' and user.make_info_public is True:
diff --git a/requirements.txt b/requirements.txt
index 8affc6203..e9341d382 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -9,7 +9,7 @@ celery==4.1.0
certifi==2017.7.27.1
chardet==3.0.4
# https://docs.djangoproject.com/en/1.10/releases/#id2
-Django==1.11.16 # rq.filter: >=1.11,<1.12
+Django==1.11.17 # rq.filter: >=1.11,<1.12
django-apptemplates==1.3
django-contrib-comments==1.8.0
django-js-reverse==0.7.3
@@ -22,16 +22,14 @@ django-threadedcomments==1.1
django-tinsel==1.0.1
django-webpack-loader==0.5.0 # https://github.com/owais/django-webpack-loader/releases
flake8==2.0 # rq.filter: ==2.0
-functools32==3.2.3.post2
gunicorn==19.7.1 # http://docs.gunicorn.org/en/stable/news.html
hiredis==0.2.0
idna==2.5
jsonschema==2.6.0
-kombu==4.1.0
+kombu==4.2.0
libsass==0.11.2
mccabe==0.6.1
-# Modgrammar-py2 has a 0.9.2 release on PyPi, but no artifacts for the release
-modgrammar-py2==0.9.1 # rq.filter: !=0.9.2
+modgrammar==0.10
olefile==0.44
pep8==1.4.6 # rq.filter: ==1.4.6
Pillow==4.2.1
@@ -46,4 +44,3 @@ rollbar==0.13.12 # https://github.com/rollbar/pyrollbar/
six==1.10.0
unicodecsv==0.14.1
urllib3==1.23
-wsgiref==0.1.2