Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

fixed pylint/pep8 warnings

  • Loading branch information...
commit dfd3c9c2716c27b6772b3dd8f8f2f78c831210e1 1 parent f09ad8b
@trey0 trey0 authored
View
17 geocamLens/SearchAbstract.py
@@ -5,15 +5,16 @@
# __END_LICENSE__
import re
-import sys
from django.db.models import Q
from geocamUtil import TimeUtil
+
class BadQuery(Exception):
pass
+
class SearchAbstract:
# override these settings in derived classes
getAllFeatures = None
@@ -35,7 +36,7 @@ def filterFieldBefore(self, query, clause, field, term, negated):
except ValueError, msg:
raise BadQuery("Oops, %s in clause '%s' of search '%s'"
% (msg, clause, query))
- return Q(**{self.timeField+'__lte': utcDT})
+ return Q(**{self.timeField + '__lte': utcDT})
def filterFieldAfter(self, query, clause, field, term, negated):
if negated:
@@ -47,7 +48,7 @@ def filterFieldAfter(self, query, clause, field, term, negated):
except ValueError, msg:
raise BadQuery("Oops, %s in clause '%s' of search '%s'"
% (msg, clause, query))
- return Q(**{self.timeField+'__gte': utcDT})
+ return Q(**{self.timeField + '__gte': utcDT})
def filterFieldDefault(self, query, clause, field, term, negated):
if field == None:
@@ -66,7 +67,7 @@ def filterFieldDefault(self, query, clause, field, term, negated):
qfilter = Q()
for f in fields:
dbField = self.flookup[f]
- qAdd = Q(**{dbField+'__icontains': term})
+ qAdd = Q(**{dbField + '__icontains': term})
if negated:
qfilter = qfilter & ~qAdd
else:
@@ -75,12 +76,12 @@ def filterFieldDefault(self, query, clause, field, term, negated):
def filterField(self, query, clause, field, term, negated):
if field:
- filterFuncName = 'filterField'+field.capitalize()
+ filterFuncName = 'filterField' + field.capitalize()
if hasattr(self, filterFuncName):
filterFunc = getattr(self, filterFuncName)
return filterFunc(query, clause, field, term, negated)
return self.filterFieldDefault(query, clause, field, term, negated)
-
+
def filterClause(self, query, clause):
if clause.startswith('-'):
negated = True
@@ -132,7 +133,7 @@ def treeToFilter(self, query, queryTree):
termFilter = termFilter & clauseFilter
queryFilter = queryFilter | termFilter
return queryFilter
-
+
def searchFeatures0(self, startSet, query):
queryTree = self.parseQuery(query)
queryFilter = self.treeToFilter(query, queryTree)
@@ -142,4 +143,4 @@ def searchFeatures(self, startSet, query):
result = startSet
if query:
result = self.searchFeatures0(result, query)
- return result.distinct().order_by('-'+self.timeField)
+ return result.distinct().order_by('-' + self.timeField)
View
3  geocamLens/SearchSimple.py
@@ -8,11 +8,12 @@
from geocamLens.SearchAbstract import SearchAbstract
+
class SearchSimple(SearchAbstract):
def getAllFeatures(self):
return PointFeature.objects.filter(processed=True)
fields = ('name', 'user', 'notes', 'tags', 'uuid')
- timeField = 'timestamp' # FIX: handle features with non-zero time extent
+ timeField = 'timestamp' # FIX: handle features with non-zero time extent
# pairs (user-facing-field-name, django-field-name)
fieldAliases = (('user', 'author__username'),)
View
7 geocamLens/UploadClient.py
@@ -14,6 +14,7 @@
from geocamUtil import MimeMultipartFormData
+
class UploadClient:
def __init__(self, url, userName='root', password=''):
self.url = url
@@ -44,7 +45,7 @@ def uploadImage(self, imageName, attributes, downsampleFactor=1):
if downsampleFactor != 1:
im = PIL.Image.open(imageName)
w, h = im.size
- thRes = (w//downsampleFactor, h//downsampleFactor)
+ thRes = (w // downsampleFactor, h // downsampleFactor)
im.thumbnail(thRes, PIL.Image.ANTIALIAS)
fd, tmpName = tempfile.mkstemp('uploadImageThumb.jpg')
os.close(fd)
@@ -56,7 +57,7 @@ def uploadImage(self, imageName, attributes, downsampleFactor=1):
imageData = file(imageName, 'r').read()
#cookieProcessor = urllib2.HTTPCookieProcessor()
- opener = urllib2.build_opener() # (cookieProcessor)
+ opener = urllib2.build_opener() # (cookieProcessor)
headers = {'User-Agent': 'GeoCam Upload Tester'}
multipart = MimeMultipartFormData.MimeMultipartFormData()
@@ -83,7 +84,7 @@ def uploadTrack(self, url, trackName, attributes=None):
attributes = dict(trackUploadProtocolVersion='1.0')
#cookieProcessor = urllib2.HTTPCookieProcessor()
- opener = urllib2.build_opener() # (cookieProcessor)
+ opener = urllib2.build_opener() # (cookieProcessor)
headers = {'User-Agent': 'GeoCam Upload Tester'}
url = '%s/track' % self.url
View
6 geocamLens/ViewKml.py
@@ -18,10 +18,12 @@
CACHED_CSS = None
+
class BogusRequest:
def build_absolute_uri(self, text):
return text
+
class ViewKml(object):
def kmlGetStartSessionKml(self, request, sessionId):
urlPath = urlresolvers.reverse('geocamLens_kmlGetSessionResponse',
@@ -106,14 +108,14 @@ def kmlGetInitialKml(self, request, sessionId):
</Link>
</NetworkLink>
""" % dict(updateUrl=updateUrl))
-
+
result += ("""
%(allFeaturesFolder)s
</Document>
""" % dict(allFeaturesFolder=allFeaturesFolder))
return result
-
+
def kmlGetUpdateKml(self, request, sessionId):
# FIX: implement me -- can use old version of geocam for reference
return ''
View
46 geocamLens/ViewLensAbstract.py
@@ -6,28 +6,19 @@
# Create your views here.
-import math
import sys
-import datetime
import os
-import shutil
-import urllib
import tempfile
-import shutil
import PIL.Image
-import tagging
-from django.http import HttpResponse
+from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render_to_response
-from django.utils.safestring import mark_safe
from django.template import RequestContext
from django.contrib.auth.models import User
from geocamUtil import anyjson as json
from geocamUtil.icons import cacheIcons
-from geocamUtil.middleware.SecurityMiddleware import requestIsSecure
from geocamUtil.models.UuidField import makeUuid
-from geocamUtil.FileUtil import mkdirP
from geocamLens.models import Image
from geocamLens.forms import UploadImageForm, EditImageForm
@@ -38,6 +29,7 @@
cacheIcons(os.path.join(settings.MEDIA_ROOT, 'geocamLens', 'icons', 'map'))
cacheIcons(os.path.join(settings.MEDIA_ROOT, 'geocamLens', 'icons', 'mapr'))
+
class ViewLensAbstract(ViewKml):
# override in derived classes
search = None
@@ -54,9 +46,9 @@ def getMatchingFeatures(self, request):
def dumps(self, obj):
if 1:
- return json.dumps(obj, indent=4, sort_keys=True) # pretty print for debugging
+ return json.dumps(obj, indent=4, sort_keys=True) # pretty print for debugging
else:
- return json.dumps(obj, separators=(',',':')) # compact
+ return json.dumps(obj, separators=(',', ':')) # compact
def getFeaturesGeoJson(self, request):
try:
@@ -64,7 +56,7 @@ def getFeaturesGeoJson(self, request):
errorMessage = None
except BadQuery, e:
errorMessage = e.message
-
+
numFeaturesParam = request.GET.get('n')
if numFeaturesParam:
if numFeaturesParam == 'all':
@@ -116,9 +108,9 @@ def getExportSettings(self):
for f in exportedVars))
return json.dumps(exportDict)
- def editImage0(self, request, id, template):
- img = self.defaultImageModel.objects.get(id=id)
- ajax = request.POST.has_key('ajax')
+ def editImage0(self, request, imgId, template):
+ img = self.defaultImageModel.objects.get(id=imgId)
+ ajax = 'ajax' in request.POST
if request.method == 'POST':
form = EditImageForm(request.POST, instance=img)
if form.is_valid():
@@ -140,13 +132,13 @@ def editImage0(self, request, id, template):
(template,
dict(img=img,
form=form),
- context_instance = RequestContext(request)))
-
- def editImage(self, request, id):
- return self.editImage0(request, id, 'editImage.html')
+ context_instance=RequestContext(request)))
- def editImageWrapper(self, request, id):
- return self.editImage0(request, id, 'editImageWrapper.html')
+ def editImage(self, request, imgId):
+ return self.editImage0(request, imgId, 'editImage.html')
+
+ def editImageWrapper(self, request, imgId):
+ return self.editImage0(request, imgId, 'editImageWrapper.html')
def uploadImageAuth(self, request):
return self.uploadImage(request, request.user.username)
@@ -185,7 +177,7 @@ def uploadImage(self, request, userName):
newVersion = img.version + 1
else:
# create Image db record
- img = self.defaultImageModel()
+ img = self.defaultImageModel() # pylint: disable-msg=E1102
img.readImportVals(storePath=tempStorePath,
uploadImageFormData=form.cleaned_data)
@@ -196,7 +188,7 @@ def uploadImage(self, request, userName):
im = PIL.Image.open(tempStorePath, 'r')
newRes = im.size
del im
-
+
if sameUuid:
oldRes = (img.widthPixels, img.heightPixels)
if newRes > oldRes:
@@ -238,7 +230,7 @@ def uploadImage(self, request, userName):
userAgent = request.META.get('HTTP_USER_AGENT', '')
# swfupload user can't see errors in form response, best return an error code
if 'Flash' in userAgent:
- return http.HttpResponseBadRequest('<h1>400 Bad Request</h1>')
+ return HttpResponseBadRequest('<h1>400 Bad Request</h1>')
else:
form = UploadImageForm()
#print 'form:', form
@@ -250,8 +242,8 @@ def uploadImage(self, request, userName):
print >>sys.stderr, 'upload image end'
return resp
- def viewPhoto(self, request, id):
+ def viewPhoto(self, request, imgId):
# this is not very efficient
- img = Image.objects.get(id=id)
+ img = Image.objects.get(id=imgId)
imgData = file(img.getImagePath(), 'r').read()
return HttpResponse(imgData, mimetype='image/jpeg')
View
6 geocamLens/ViewLensSimple.py
@@ -4,14 +4,10 @@
# All Rights Reserved.
# __END_LICENSE__
-import os
-
-from geocamUtil.icons import cacheIcons
-
from geocamLens.ViewLensAbstract import ViewLensAbstract
from geocamLens.models import Photo
from geocamLens.SearchSimple import SearchSimple
-from geocamLens import settings
+
class ViewLensSimple(ViewLensAbstract):
search = SearchSimple()
View
3  geocamLens/__init__.py
@@ -22,12 +22,13 @@
'serial': 1
}
+
def get_version():
"""
Return the formatted version information
"""
vers = ["%(major)i.%(minor)i" % __version_info__, ]
-
+
if __version_info__['micro']:
vers.append(".%(micro)i" % __version_info__)
if __version_info__['releaselevel'] != 'final':
View
2  geocamLens/admin.py
@@ -6,7 +6,7 @@
from django.contrib import admin
-from geocamLens.models import *
+from geocamLens.models import * # pylint: disable-msg=W0401
admin.site.register(Snapshot)
admin.site.register(GoogleEarthSession)
View
5 geocamLens/forms.py
@@ -6,14 +6,13 @@
import datetime
-from django.core.exceptions import ValidationError
from django import forms
-from django.contrib.auth.models import User
from geocamUtil.forms.UuidField import UuidField
from geocamLens.models import Photo
+
# the field names in this form are currently retained for backward compatibility with old versions
# of GeoCam Mobile
class UploadImageForm(forms.Form):
@@ -33,6 +32,7 @@ class UploadImageForm(forms.Form):
uuid = UuidField(required=False)
folder = forms.CharField(max_length=32, required=False)
+
class EditImageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(EditImageForm, self).__init__(*args, **kwargs)
@@ -44,4 +44,3 @@ def __init__(self, *args, **kwargs):
class Meta:
model = Photo
fields = ('notes', 'tags', 'latitude', 'longitude', 'altitude', 'altitudeRef', 'yaw', 'yawRef', 'icon')
-
View
174 geocamLens/models.py
@@ -4,9 +4,12 @@
# All Rights Reserved.
# __END_LICENSE__
+"""
+Models for geocamLens app.
+"""
+
import os
import sys
-import glob
import shutil
import datetime
import random
@@ -18,19 +21,13 @@
import PIL.Image
from django.db import models
from django.utils.safestring import mark_safe
-from tagging.fields import TagField
-from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
-from django.core.cache import cache
from django.contrib.contenttypes import generic
import tagging
-from geocamUtil import anyjson as json
-from geocamUtil.models.ExtrasField import ExtrasField
from geocamUtil.models.UuidField import UuidField
from geocamUtil.models.managers import AbstractModelManager, FinalModelManager
-from geocamUtil.icons import ICON_URL_CACHE, getIconSize, getIconUrl
-from geocamUtil.gpx import TrackLog
+from geocamUtil.icons import ICON_URL_CACHE
from geocamUtil.Xmp import Xmp
from geocamUtil.TimeUtil import parseUploadTime
from geocamUtil.FileUtil import mkdirP
@@ -40,14 +37,10 @@
from geocamLens import settings
TIME_ZONES = None
-try:
- import pytz
-except ImportError:
- TIME_ZONES = ['US/Pacific'] # try to fail gracefully
-else:
- TOP_TIME_ZONES = ['US/Pacific', 'US/Eastern', 'US/Central', 'US/Mountain']
- TIME_ZONES = TOP_TIME_ZONES + [tz for tz in pytz.common_timezones if tz not in TOP_TIME_ZONES]
-TIME_ZONE_CHOICES = [(x,x) for x in TIME_ZONES]
+TOP_TIME_ZONES = ['US/Pacific', 'US/Eastern', 'US/Central', 'US/Mountain']
+TIME_ZONES = TOP_TIME_ZONES + [tz for tz in pytz.common_timezones
+ if tz not in TOP_TIME_ZONES]
+TIME_ZONE_CHOICES = [(x, x) for x in TIME_ZONES]
DEFAULT_TIME_ZONE = TIME_ZONES[0]
PERM_VIEW = 0
@@ -79,29 +72,39 @@
ALTITUDE_REF_LOOKUP[''] = None
DEFAULT_ALTITUDE_REF = ALTITUDE_REF_CHOICES[0][0]
-STATUS_CHOICES = (('p', 'pending'), # in db but not fully processed yet
- ('a', 'active'), # active, display this to user
- ('d', 'deleted'), # deleted but not purged yet
- )
-# define constants like STATUS_PENDING based on above choices
-for code, label in STATUS_CHOICES:
- globals()['STATUS_' + label.upper()] = code
+STATUS_PENDING = 'p'
+STATUS_ACTIVE = 'a'
+STATUS_DELETED = 'd'
+
+STATUS_CHOICES = (
+ # in db but not fully processed yet
+ (STATUS_PENDING, 'pending'),
+ # active, display this to user
+ (STATUS_ACTIVE, 'active'),
+ # deleted but not purged yet
+ (STATUS_DELETED, 'deleted'),
+ )
WF_NEEDS_EDITS = 0
WF_SUBMITTED_FOR_VALIDATION = 1
WF_VALID = 2
WF_REJECTED = 3
-WORKFLOW_STATUS_CHOICES = ((WF_NEEDS_EDITS, 'Needs edits'),
- (WF_SUBMITTED_FOR_VALIDATION, 'Submitted for validation'),
- (WF_VALID, 'Valid'),
- (WF_REJECTED, 'Rejected'),
- )
+WORKFLOW_STATUS_CHOICES = (
+ (WF_NEEDS_EDITS, 'Needs edits'),
+ (WF_SUBMITTED_FOR_VALIDATION, 'Submitted for validation'),
+ (WF_VALID, 'Valid'),
+ (WF_REJECTED, 'Rejected'),
+ )
DEFAULT_WORKFLOW_STATUS = WF_SUBMITTED_FOR_VALIDATION
CARDINAL_DIRECTIONS = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE',
'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW']
+
class Snapshot(models.Model):
+ """
+ A snapshot is a subframe of an image with an associated comment.
+ """
imgType = models.ForeignKey(ContentType, editable=False)
imgId = models.PositiveIntegerField()
uuid = UuidField()
@@ -111,7 +114,9 @@ class Snapshot(models.Model):
ymax = models.FloatField()
title = models.CharField(max_length=64)
comment = models.TextField()
- status = models.CharField(max_length=1, choices=STATUS_CHOICES, default=STATUS_ACTIVE)
+ status = models.CharField(max_length=1,
+ choices=STATUS_CHOICES,
+ default=STATUS_ACTIVE)
dateCreated = models.DateTimeField(null=True, blank=True)
dateUpdated = models.DateTimeField(null=True, blank=True)
@@ -129,13 +134,21 @@ def save(self, updateDate=True, **kwargs):
def __unicode__(self):
return self.title
+
class Image(coreModels.PointFeature):
- roll = models.FloatField(blank=True, null=True) # degrees, 0 is level, right-hand rotation about x in NED frame
- pitch = models.FloatField(blank=True, null=True) # degrees, 0 is level, right-hand rotation about y in NED frame
+ """
+ A geolocated image.
+ """
+ # degrees, 0 is level, right-hand rotation about x in NED frame
+ roll = models.FloatField(blank=True, null=True)
+ # degrees, 0 is level, right-hand rotation about y in NED frame
+ pitch = models.FloatField(blank=True, null=True)
# compass degrees, 0 = north, increase clockwise as viewed from above
yaw = models.FloatField(blank=True, null=True,
verbose_name='Heading')
- yawRef = models.CharField(blank=True, max_length=1, choices=YAW_REF_CHOICES, default=DEFAULT_YAW_REF,
+ yawRef = models.CharField(blank=True, max_length=1,
+ choices=YAW_REF_CHOICES,
+ default=DEFAULT_YAW_REF,
verbose_name='Heading ref.')
widthPixels = models.PositiveIntegerField()
heightPixels = models.PositiveIntegerField()
@@ -159,14 +172,15 @@ def getActiveSnapshots(self):
def getThumbnailPath(self, width):
return os.path.join(self.getDir(), 'th%d.jpg' % width)
- def calcThumbSize(self, fullWidth, fullHeight, maxOutWidth, maxOutHeight=None):
+ def calcThumbSize(self, fullWidth, fullHeight, maxOutWidth,
+ maxOutHeight=None):
if maxOutHeight == None:
maxOutHeight = (maxOutWidth * 3) // 4
if float(maxOutWidth) / fullWidth < float(maxOutHeight) / fullHeight:
thumbWidth = maxOutWidth
- thumbHeight = int(float(maxOutWidth)/fullWidth * fullHeight)
+ thumbHeight = int(float(maxOutWidth) / fullWidth * fullHeight)
else:
- thumbWidth = int(float(maxOutHeight)/fullHeight * fullWidth)
+ thumbWidth = int(float(maxOutHeight) / fullHeight * fullWidth)
thumbHeight = maxOutHeight
return (thumbWidth, thumbHeight)
@@ -192,10 +206,12 @@ def makeThumbnail0(self, previewOriginalPath, thumbSize):
im = PIL.Image.open(previewOriginalPath)
fullWidth, fullHeight = im.size
- thumbWidth, thumbHeight = self.calcThumbSize(fullWidth, fullHeight, maxOutWidth, maxOutHeight)
+ thumbWidth, thumbHeight = \
+ self.calcThumbSize(fullWidth, fullHeight,
+ maxOutWidth, maxOutHeight)
try:
im.thumbnail((thumbWidth, thumbHeight), PIL.Image.ANTIALIAS)
- except IOError, e:
+ except IOError:
# fall back to resize
im.resize((thumbWidth, thumbHeight), PIL.Image.ANTIALIAS)
mkdirP(self.getDir())
@@ -208,7 +224,11 @@ def makeThumbnail(self, thumbSize):
def galleryThumb(self):
w0, h0 = settings.GEOCAM_CORE_GALLERY_THUMB_SIZE
w, h = self.getThumbSize(w0)
- return mark_safe('<td style="vertical-align: top; width: %dpx; height: %dpx;"><img src="%s" width="%d" height="%d"/></td>' % (w0, h0, self.getThumbnailUrl(w0), w, h))
+ tmpl = """<td style="vertical-align: top; width: %dpx; height: %dpx;">
+ <img src="%s" width="%d" height="%d"/>
+ </td>"""
+ return mark_safe(tmpl
+ % (w0, h0, self.getThumbnailUrl(w0), w, h))
def getRotatedIconDict(self):
if self.yaw == None:
@@ -236,11 +256,13 @@ def getCaptionHtml(self):
def getBalloonHtml(self, request):
result = ['<div>\n']
result.append(self.getCaptionHeader())
-
+
viewerUrl = request.build_absolute_uri(self.getViewerUrl())
if self.widthPixels != 0:
dw, dh = self.getThumbSize(settings.GEOCAM_CORE_DESC_THUMB_SIZE[0])
- thumbnailUrl = request.build_absolute_uri(self.getThumbnailUrl(settings.GEOCAM_CORE_DESC_THUMB_SIZE[0]))
+ thumbnailUrl = (request.build_absolute_uri
+ (self.getThumbnailUrl
+ (settings.GEOCAM_CORE_DESC_THUMB_SIZE[0])))
result.append("""
<a href="%(viewerUrl)s"
title="Show high-res view">
@@ -271,8 +293,8 @@ def getXmpVals(self, storePath):
def getUploadImageFormVals(self, formData):
yaw, yawRef = Xmp.normalizeYaw(formData.get('yaw', None),
formData.get('yawRef', None))
- altitude, altitudeRef = Xmp.normalizeYaw(formData.get('altitude', None),
- formData.get('altitudeRef', None))
+ Xmp.normalizeYaw(formData.get('altitude', None),
+ formData.get('altitudeRef', None))
folderName = formData.get('folder', None)
folder = None
@@ -284,17 +306,20 @@ def getUploadImageFormVals(self, formData):
folder = coreModels.Folder.objects.get(id=1)
# FIX figure out what time zone to show
- tz = pytz.timezone(settings.TIME_ZONE)
+ tzone = pytz.timezone(settings.TIME_ZONE)
timestampStr = Xmp.checkMissing(formData.get('cameraTime', None))
if timestampStr == None:
timestampUtc = None
else:
timestampLocal = parseUploadTime(timestampStr)
if timestampLocal.tzinfo == None:
- timestampLocal = tz.localize(timestampLocal)
- timestampUtc = timestampLocal.astimezone(pytz.utc).replace(tzinfo=None)
+ timestampLocal = tzone.localize(timestampLocal)
+ timestampUtc = (timestampLocal
+ .astimezone(pytz.utc)
+ .replace(tzinfo=None))
- # special case: remove 'default' tag inserted by older versions of GeoCam Mobile
+ # special case: remove 'default' tag inserted by older versions
+ # of GeoCam Mobile
tagsOrig = formData.get('tags', None)
tagsList = [t for t in tagging.utils.parse_tag_input(tagsOrig)
if t != 'default']
@@ -321,7 +346,7 @@ def getUploadImageFormVals(self, formData):
def makeTagsString(tagsList):
tagsList = list(set(tagsList))
tagsList.sort()
-
+
# modeled on tagging.utils.edit_string_for_tags
names = []
useCommas = False
@@ -338,13 +363,13 @@ def makeTagsString(tagsList):
return ' '.join(names)
def processVals(self, vals):
- if vals.has_key('tags'):
+ if 'tags' in vals:
tagsList = tagging.utils.parse_tag_input(vals['tags'])
else:
tagsList = []
# find any '#foo' hashtags in notes and add them to the tags field
- if vals.has_key('notes'):
+ if 'notes' in vals:
for hashtag in re.finditer('\#([\w0-9_]+)', vals['notes']):
tagsList.append(hashtag.group(1))
vals['tags'] = self.makeTagsString(tagsList)
@@ -360,12 +385,13 @@ def getImportVals(self, storePath=None, uploadImageFormData=None):
if storePath != None:
xmpVals = self.getXmpVals(storePath)
- print >>sys.stderr, 'getImportVals: exif/xmp data:', xmpVals
+ print >> sys.stderr, 'getImportVals: exif/xmp data:', xmpVals
vals.update(xmpVals)
if uploadImageFormData != None:
formVals = self.getUploadImageFormVals(uploadImageFormData)
- print >>sys.stderr, 'getImportVals: UploadImageForm data:', formVals
+ print >> sys.stderr, 'getImportVals: UploadImageForm data:', \
+ formVals
vals.update(formVals)
self.processVals(vals)
@@ -385,7 +411,7 @@ def getKmlAdvanced(self):
<Style>
<IconStyle><Icon></Icon></IconStyle>
<BalloonStyle>
- <displayMode>hide</displayMode><!-- suppress confusing description balloon -->
+ <displayMode>hide</displayMode><!-- no balloon -->
</BalloonStyle>
</Style>
<Camera>
@@ -397,7 +423,7 @@ def getKmlAdvanced(self):
<roll>{{ self.cameraRotation.rollDegrees }}</roll>
</Camera>
<Icon>
- <href>{{ self.hrefBase }}s/photos/{{ self.rollName }}/{{ self.imageFile }}</href>
+ <href>...</href>
</Icon>
<Point>
<coordinates>{{ billboardLonLatAlt.commaString }}</coordinates>
@@ -431,9 +457,12 @@ def getCaptionTimeStamp(self):
if self.timestamp == None:
return '(unknown)'
else:
- tz = self.getCaptionTimeZone()
+ tzone = self.getCaptionTimeZone()
tzName = settings.DEFAULT_TIME_ZONE['name']
- localizedDt = pytz.utc.localize(self.timestamp).astimezone(tz).replace(tzinfo=None)
+ localizedDt = (pytz.utc
+ .localize(self.timestamp)
+ .astimezone(tzone)
+ .replace(tzinfo=None))
return '%s %s' % (str(localizedDt), tzName)
def getCaptionFieldLatLon(self):
@@ -449,12 +478,12 @@ def getCaptionFieldHeading(self):
else:
dirIndex = int(round(self.yaw / 22.5)) % 16
cardinal = CARDINAL_DIRECTIONS[dirIndex]
-
+
if self.yawRef == None:
yawStr = 'unknown'
else:
yawStr = YAW_REF_LOOKUP[self.yawRef]
-
+
val = ('%s %d&deg; (ref. %s)'
% (cardinal, round(self.yaw), yawStr))
return ['heading', val]
@@ -477,12 +506,14 @@ def getCaptionHeader(self):
if self.timestamp == None:
tsVal = '(unknown)'
else:
- tsVal = TimeUtil.getTimeShort(self.timestamp, tz=self.getCaptionTimeZone())
+ tsVal = (TimeUtil
+ .getTimeShort(self.timestamp,
+ tz=self.getCaptionTimeZone()))
if self.name == None:
nameVal = '(untitled)'
else:
nameVal = self.name
- tsColor = '#000077' # dark blue
+ tsColor = '#000077' # dark blue
return ("""
<div style="padding-top: 5px; padding-bottom: 5px;">
<span class="geocamCaption_name">%(nameVal)s</span>
@@ -495,19 +526,30 @@ def getCaptionInfoTable(self):
out.write('<table>')
for field in self.getCaptionFields():
label, val = self.getCaptionField(field)
- out.write('<tr><td class="geocamCaption_fieldLabel">%s</td><td>%s</td></tr>' % (label, val))
+ out.write(('<tr>'
+ '<td class="geocamCaption_fieldLabel">%s</td>'
+ '<td>%s</td>'
+ '</tr>')
+ % (label, val))
out.write('</table>')
return out.getvalue()
+
class Photo(Image):
objects = FinalModelManager(parentModel=Image)
+
class GoogleEarthSession(models.Model):
- """Session state for a Google Earth client that is requesting periodic updates."""
+ """
+ Session state for a Google Earth client that is requesting periodic
+ updates.
+ """
sessionId = models.CharField(max_length=256)
- query = models.CharField(max_length=128, default='', help_text="User's query when session was initiated")
+ query = models.CharField(max_length=128, default='',
+ help_text="User's query when session was initiated")
utime = models.DateTimeField(help_text="The last time we sent an update to the client.")
- extras = models.TextField(max_length=1024, default='{}', help_text="A place to add extra fields if we need them but for some reason can't modify the table schema. Expressed as a JSON-encoded dict.")
+ extras = models.TextField(max_length=1024, default='{}',
+ help_text="A place for extra fields if we can't change the schema")
@staticmethod
def getSessionId(searchQuery=None):
@@ -515,11 +557,12 @@ def getSessionId(searchQuery=None):
if searchQuery:
MAX_SEARCH_LEN = 200
if len(searchQuery) > MAX_SEARCH_LEN:
- raise Exception('due to limitations of current db schema, search queries are limited to %d chars' % MAX_SEARCH_LEN)
+ raise Exception('due to limitations of current db schema, search queries are limited to %d chars'
+ % MAX_SEARCH_LEN)
return '%s-%s' % (randomPart, searchQuery)
else:
return randomPart
-
+
def getSearchQuery(self):
if '-' in self.sessionId:
return self.sessionId.split('-', 1)[1]
@@ -528,6 +571,7 @@ def getSearchQuery(self):
def __unicode__(self):
return u'<Session %s (%s)>' % (self.sessionId, self.utime)
+
class Meta:
verbose_name = 'Google Earth session'
ordering = ['utime']
View
3  geocamLens/tests.py
@@ -11,9 +11,10 @@
Replace these with more appropriate tests for your application.
"""
+from xml.dom import minidom
from django.test import TestCase
from django.test.client import Client
-from xml.dom import minidom
+
class ValidKmlTest(TestCase):
def testStartSessionValid(self):
View
10 geocamLens/urls.py
@@ -4,7 +4,7 @@
# All Rights Reserved.
# __END_LICENSE__
-from django.conf.urls.defaults import *
+from django.conf.urls.defaults import patterns
from geocamUtil.FileUtil import importModuleByName
@@ -23,13 +23,13 @@
{'challenge': 'digest',
'readOnly': True},
'geocamLens_kmlGetSessionResponse'),
-
+
# features
(r'^features.json', views.featuresJson, {'readOnly': True}),
(r'^featuresJson.js', views.featuresJsonJs, {'readOnly': True}),
(r'^galleryDebug.html', views.galleryDebug, {'readOnly': True}),
- (r'^photo/(?P<id>[^/]+)/(?:[^/]+)?$', views.viewPhoto,
+ (r'^photo/(?P<imgId>[^/]+)/(?:[^/]+)?$', views.viewPhoto,
{'readOnly': True}),
(r'^upload/$', views.uploadImageAuth),
@@ -37,8 +37,8 @@
(r'^upload-m/$', views.uploadImageAuth,
{'challenge': 'basic'}),
- (r'^edit/photo/(?P<id>[^/]+)/$', views.editImageWrapper),
- (r'^editWidget/photo/(?P<id>[^/]+)/$', views.editImage),
+ (r'^edit/photo/(?P<imgId>[^/]+)/$', views.editImageWrapper),
+ (r'^editWidget/photo/(?P<imgId>[^/]+)/$', views.editImage),
# legacy URLs, compatible with the old version of GeoCam
# Mobile *if* user authentication is off (not recommended!).
Please sign in to comment.
Something went wrong with that request. Please try again.