PEP8 and general cleanups

This commit is contained in:
Roberto Rosario
2012-02-22 11:57:00 -04:00
parent af9be90849
commit f484e1a9c3
19 changed files with 44 additions and 49 deletions

View File

@@ -178,7 +178,7 @@ class GPG(object):
self.keyservers = keyservers self.keyservers = keyservers
self.gpg = gnupg.GPG(**kwargs) self.gpg = gnupg.GPG(**kwargs)
def verify_file(self, file_input, detached_signature=None, fetch_key=False): def verify_file(self, file_input, detached_signature=None, fetch_key=False):
""" """
Verify the signature of a file. Verify the signature of a file.

View File

@@ -1,6 +1,5 @@
from django import forms from django import forms
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext
class KeySearchForm(forms.Form): class KeySearchForm(forms.Form):

View File

@@ -8,6 +8,6 @@ from .conf.settings import KEYSERVERS, GPG_HOME
try: try:
gpg = GPG(home=GPG_HOME, keyservers=KEYSERVERS) gpg = GPG(home=GPG_HOME, keyservers=KEYSERVERS)
except Exception, e: except Exception, e:
gpg = GPG(keyservers=KEYSERVERS) gpg = GPG(keyservers=KEYSERVERS)
sys.stderr.write(u'ERROR: GPG initialization error: %s\n' % e) sys.stderr.write(u'ERROR: GPG initialization error: %s\n' % e)
sys.stderr.write(u'INFO: Initializating GPG with system default home\n') sys.stderr.write(u'INFO: Initializating GPG with system default home\n')

View File

@@ -9,12 +9,11 @@ from django.template import RequestContext
from django.contrib import messages from django.contrib import messages
from permissions.models import Permission from permissions.models import Permission
from common.utils import (urlquote, encapsulate) from common.utils import encapsulate
from .api import Key, SIGNATURE_STATES from .api import Key
from .runtime import gpg from .runtime import gpg
from .exceptions import (GPGVerificationError, KeyFetchingError, from .exceptions import KeyFetchingError, KeyImportError
KeyImportError)
from .forms import KeySearchForm from .forms import KeySearchForm
from .permissions import (PERMISSION_KEY_VIEW, PERMISSION_KEY_DELETE, from .permissions import (PERMISSION_KEY_VIEW, PERMISSION_KEY_DELETE,
PERMISSION_KEYSERVER_QUERY, PERMISSION_KEY_RECEIVE) PERMISSION_KEYSERVER_QUERY, PERMISSION_KEY_RECEIVE)
@@ -40,7 +39,7 @@ def key_receive(request, key_id):
except (KeyImportError, KeyError, TypeError), e: except (KeyImportError, KeyError, TypeError), e:
messages.error( messages.error(
request, request,
_(u'Unable to import key id: %(key_id)s; %(error)s') % _(u'Unable to import key id: %(key_id)s; %(error)s') %
{ {
'key_id': key_id, 'key_id': key_id,
'error': e, 'error': e,

View File

@@ -34,7 +34,7 @@ def comment_delete(request, comment_id=None, comment_id_list=None):
if not comments: if not comments:
messages.error(request, _(u'Must provide at least one comment.')) messages.error(request, _(u'Must provide at least one comment.'))
return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', '/'))) previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', '/')))
next = request.POST.get('next', request.GET.get('next', post_action_redirect if post_action_redirect else request.META.get('HTTP_REFERER', '/'))) next = request.POST.get('next', request.GET.get('next', post_action_redirect if post_action_redirect else request.META.get('HTTP_REFERER', '/')))

View File

@@ -2,13 +2,11 @@ from __future__ import absolute_import
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext from django.utils.translation import ugettext
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
from metadata.classes import MetadataClass from metadata.classes import MetadataClass
from .models import (Index, IndexTemplateNode, IndexInstanceNode, from .models import Index, IndexInstanceNode, DocumentRenameCount
DocumentRenameCount)
from .conf.settings import (AVAILABLE_INDEXING_FUNCTIONS, from .conf.settings import (AVAILABLE_INDEXING_FUNCTIONS,
MAX_SUFFIX_COUNT, SLUGIFY_PATHS) MAX_SUFFIX_COUNT, SLUGIFY_PATHS)
from .filesystem import (fs_create_index_directory, from .filesystem import (fs_create_index_directory,
@@ -94,7 +92,7 @@ def cascade_eval(eval_dict, document, template_node, parent_index_instance=None)
fs_create_index_directory(index_instance) fs_create_index_directory(index_instance)
except Exception, exc: except Exception, exc:
warnings.append(_(u'Error updating document index, expression: %(expression)s; %(exception)s') % { warnings.append(_(u'Error updating document index, expression: %(expression)s; %(exception)s') % {
'expression': template_node.expression, 'exception': exc}) 'expression': template_node.expression, 'exception': exc})
if template_node.link_documents: if template_node.link_documents:
suffix = find_lowest_available_suffix(index_instance, document) suffix = find_lowest_available_suffix(index_instance, document)
@@ -109,7 +107,7 @@ def cascade_eval(eval_dict, document, template_node, parent_index_instance=None)
fs_create_document_link(index_instance, document, suffix) fs_create_document_link(index_instance, document, suffix)
except Exception, exc: except Exception, exc:
warnings.append(_(u'Error updating document index, expression: %(expression)s; %(exception)s') % { warnings.append(_(u'Error updating document index, expression: %(expression)s; %(exception)s') % {
'expression': template_node.expression, 'exception': exc}) 'expression': template_node.expression, 'exception': exc})
index_instance.documents.add(document) index_instance.documents.add(document)

View File

@@ -10,7 +10,7 @@ from .api import update_indexes
def do_rebuild_all_indexes(): def do_rebuild_all_indexes():
for index in Index.objects.all(): for index in Index.objects.all():
fs_delete_directory_recusive(index) fs_delete_directory_recusive(index)
IndexInstanceNode.objects.all().delete() IndexInstanceNode.objects.all().delete()
DocumentRenameCount.objects.all().delete() DocumentRenameCount.objects.all().delete()
for document in Document.objects.all(): for document in Document.objects.all():

View File

@@ -1,8 +1,7 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import absolute_import from __future__ import absolute_import
#from django.utils.safestring import mark_safe from django.utils.html import mark_safe
from django.utils.html import conditional_escape, mark_safe
from .models import IndexInstanceNode from .models import IndexInstanceNode
@@ -73,7 +72,7 @@ def get_breadcrumbs(index_instance, simple=False, single_link=False, include_cou
else: else:
output.insert(0, u' / '.join(result)) output.insert(0, u' / '.join(result))
return mark_safe(u' '.join(output)) return mark_safe(u' '.join(output))
def node_level(x): def node_level(x):
""" """

View File

@@ -69,7 +69,7 @@ class DocumentVersionSignatureManager(models.Manager):
document_descriptor.close() document_descriptor.close()
if detached_signature: if detached_signature:
detached_signature.close() detached_signature.close()
def clear_detached_signature(self, document): def clear_detached_signature(self, document):
document_signature = self.get_document_signature(document) document_signature = self.get_document_signature(document)
if not document_signature.signature_file: if not document_signature.signature_file:
@@ -77,4 +77,4 @@ class DocumentVersionSignatureManager(models.Manager):
document_signature.delete_detached_signature_file() document_signature.delete_detached_signature_file()
document_signature.signature_file = None document_signature.signature_file = None
document_signature.save() document_signature.save()

View File

@@ -1,12 +1,10 @@
from __future__ import absolute_import from __future__ import absolute_import
from django import forms from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import ugettext from django.utils.translation import ugettext
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.template.defaultfilters import capfirst from django.template.defaultfilters import capfirst
from django.conf import settings
from documents.widgets import document_html_widget from documents.widgets import document_html_widget
from tags.widgets import get_tags_inline_widget from tags.widgets import get_tags_inline_widget

View File

@@ -127,7 +127,6 @@ def smart_link_list(request):
except PermissionDenied: except PermissionDenied:
qs = AccessEntry.objects.filter_objects_by_access(PERMISSION_SMART_LINK_VIEW, request.user, qs) qs = AccessEntry.objects.filter_objects_by_access(PERMISSION_SMART_LINK_VIEW, request.user, qs)
return render_to_response('generic_list.html', { return render_to_response('generic_list.html', {
'title': _(u'smart links'), 'title': _(u'smart links'),
'object_list': qs, 'object_list': qs,

View File

@@ -83,10 +83,11 @@ def get_error_icon_file_path():
else: else:
return os.path.join(settings.STATIC_ROOT, MIMETYPE_ICONS_DIRECTORY_NAME, ERROR_FILE_NAME) return os.path.join(settings.STATIC_ROOT, MIMETYPE_ICONS_DIRECTORY_NAME, ERROR_FILE_NAME)
def get_error_icon_url(): def get_error_icon_url():
return os.path.join(MIMETYPE_ICONS_DIRECTORY_NAME, ERROR_FILE_NAME) return os.path.join(MIMETYPE_ICONS_DIRECTORY_NAME, ERROR_FILE_NAME)
def get_mimetype(file_description, filepath, mimetype_only=False): def get_mimetype(file_description, filepath, mimetype_only=False):
""" """
Determine a file's mimetype by calling the system's libmagic Determine a file's mimetype by calling the system's libmagic

View File

@@ -95,6 +95,7 @@ def document_post_save(sender, instance, **kwargs):
# logger.debug('got call_queue signal: %s' % kwargs) # logger.debug('got call_queue signal: %s' % kwargs)
# task_process_document_queues() # task_process_document_queues()
@receiver(post_syncdb, dispatch_uid='create_default_queue', sender=ocr_models) @receiver(post_syncdb, dispatch_uid='create_default_queue', sender=ocr_models)
def create_default_queue_signal_handler(sender, **kwargs): def create_default_queue_signal_handler(sender, **kwargs):
create_default_queue() create_default_queue()

View File

@@ -1,7 +1,5 @@
from __future__ import absolute_import from __future__ import absolute_import
import socket
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404 from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext from django.template import RequestContext

View File

@@ -10,4 +10,4 @@ class Command(collectstatic.Command):
def handle_noargs(self, *args, **kwargs): def handle_noargs(self, *args, **kwargs):
pre_collectstatic.send(sender=self) pre_collectstatic.send(sender=self)
super(Command, self).handle_noargs(*args, **kwargs) super(Command, self).handle_noargs(*args, **kwargs)

View File

@@ -1,10 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
import os, sys import os
import sys
from optparse import make_option from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, LabelCommand from django.core.management.base import BaseCommand, CommandError, LabelCommand
from django.utils.simplejson import loads, dumps from django.utils.simplejson import loads
from metadata.api import convert_dict_to_dict_list from metadata.api import convert_dict_to_dict_list
from documents.models import DocumentType from documents.models import DocumentType
@@ -25,7 +26,7 @@ class Command(LabelCommand):
make_option('--document_type', action='store', dest='document_type_name', make_option('--document_type', action='store', dest='document_type_name',
help='The document type to apply to the uploaded documents.'), help='The document type to apply to the uploaded documents.'),
) )
def handle_label(self, label, **options): def handle_label(self, label, **options):
if not os.access(label, os.R_OK): if not os.access(label, os.R_OK):
raise CommandError("File '%s' is not readable." % label) raise CommandError("File '%s' is not readable." % label)
@@ -53,10 +54,10 @@ class Command(LabelCommand):
print 'Using the metadata values:' print 'Using the metadata values:'
for key, value in metadata_dict.items(): for key, value in metadata_dict.items():
print '%s: %s' % (key, value) print '%s: %s' % (key, value)
if document_type: if document_type:
print 'Uploaded document will be of type: %s' % options['document_type_name'] print 'Uploaded document will be of type: %s' % options['document_type_name']
source = OutOfProcess() source = OutOfProcess()
fd = open(label) fd = open(label)
try: try:
@@ -71,7 +72,7 @@ class Command(LabelCommand):
else: else:
print 'Cancelled.' print 'Cancelled.'
def _confirm(interactive): def _confirm(interactive):
if not interactive: if not interactive:
return 'yes' return 'yes'

View File

@@ -9,7 +9,6 @@ from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic from django.contrib.contenttypes import generic
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.db import transaction from django.db import transaction
from django.db.utils import DatabaseError
from converter.api import get_available_transformations_choices from converter.api import get_available_transformations_choices
from converter.literals import DIMENSION_SEPARATOR from converter.literals import DIMENSION_SEPARATOR
@@ -91,7 +90,7 @@ class BaseModel(models.Model):
@transaction.commit_on_success @transaction.commit_on_success
def upload_single_file(self, file_object, filename=None, use_file_name=False, document_type=None, metadata_dict_list=None, user=None, document=None, new_version_data=None): def upload_single_file(self, file_object, filename=None, use_file_name=False, document_type=None, metadata_dict_list=None, user=None, document=None, new_version_data=None):
new_document = not document new_document = not document
if not document: if not document:
document = Document() document = Document()
if document_type: if document_type:
@@ -99,7 +98,7 @@ class BaseModel(models.Model):
document.save() document.save()
apply_default_acls(document, user) apply_default_acls(document, user)
if user: if user:
document.add_as_recent_document_for_user(user) document.add_as_recent_document_for_user(user)
create_history(HISTORY_DOCUMENT_CREATED, document, {'user': user}) create_history(HISTORY_DOCUMENT_CREATED, document, {'user': user})
@@ -113,7 +112,7 @@ class BaseModel(models.Model):
if not new_version_data: if not new_version_data:
new_version_data = {} new_version_data = {}
try: try:
new_version = document.new_version(file=file_object, **new_version_data) new_version = document.new_version(file=file_object, **new_version_data)
except Exception: except Exception:
@@ -121,7 +120,7 @@ class BaseModel(models.Model):
# document.delete() # document.delete()
transaction.rollback() transaction.rollback()
raise raise
if filename: if filename:
document.rename(filename) document.rename(filename)
@@ -129,11 +128,11 @@ class BaseModel(models.Model):
new_version.apply_default_transformations(transformations) new_version.apply_default_transformations(transformations)
#TODO: new HISTORY for version updates #TODO: new HISTORY for version updates
if metadata_dict_list and new_document: if metadata_dict_list and new_document:
# Only do for new documents # Only do for new documents
save_metadata_list(metadata_dict_list, document, create=True) save_metadata_list(metadata_dict_list, document, create=True)
warnings = update_indexes(document) warnings = update_indexes(document)
class Meta: class Meta:
ordering = ('title',) ordering = ('title',)
@@ -288,6 +287,7 @@ class SourceTransformation(models.Model):
class OutOfProcess(BaseModel): class OutOfProcess(BaseModel):
is_interactive = False is_interactive = False
class Meta(BaseModel.Meta): class Meta(BaseModel.Meta):
verbose_name = _(u'out of process') verbose_name = _(u'out of process')
verbose_name_plural = _(u'out of process') verbose_name_plural = _(u'out of process')

View File

@@ -165,13 +165,13 @@ def upload_interactive(request, source_type=None, source_id=None, document_pk=No
else: else:
if result['is_compressed'] == None: if result['is_compressed'] == None:
messages.success(request, _(u'File uploaded successfully.')) messages.success(request, _(u'File uploaded successfully.'))
if result['is_compressed'] == True: if result['is_compressed'] == True:
messages.success(request, _(u'File uncompressed successfully and uploaded as individual files.')) messages.success(request, _(u'File uncompressed successfully and uploaded as individual files.'))
if result['is_compressed'] == False: if result['is_compressed'] == False:
messages.warning(request, _(u'File was not a compressed file, uploaded as it was.')) messages.warning(request, _(u'File was not a compressed file, uploaded as it was.'))
return HttpResponseRedirect(request.get_full_path()) return HttpResponseRedirect(request.get_full_path())
except Exception, e: except Exception, e:
if settings.DEBUG: if settings.DEBUG:
@@ -240,7 +240,7 @@ def upload_interactive(request, source_type=None, source_id=None, document_pk=No
if result['is_compressed'] == True: if result['is_compressed'] == True:
messages.success(request, _(u'Staging file: %s, uncompressed successfully and uploaded as individual files.') % staging_file.filename) messages.success(request, _(u'Staging file: %s, uncompressed successfully and uploaded as individual files.') % staging_file.filename)
if result['is_compressed'] == False: if result['is_compressed'] == False:
messages.warning(request, _(u'Staging file: %s, was not compressed, uploaded as a single file.') % staging_file.filename) messages.warning(request, _(u'Staging file: %s, was not compressed, uploaded as a single file.') % staging_file.filename)

View File

@@ -1,10 +1,11 @@
from __future__ import absolute_import from __future__ import absolute_import
import csv, os, sys import csv
import os
import sys
from optparse import make_option from optparse import make_option
from django.core.management.base import BaseCommand, CommandError, LabelCommand from django.core.management.base import BaseCommand, CommandError, LabelCommand
from django.utils.simplejson import loads, dumps
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.db.utils import IntegrityError from django.db.utils import IntegrityError
@@ -17,11 +18,12 @@ def unicode_csv_reader(unicode_csv_data, dialect=csv.excel, **kwargs):
# decode UTF-8 back to Unicode, cell by cell: # decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, 'utf-8') for cell in row] yield [unicode(cell, 'utf-8') for cell in row]
def utf_8_encoder(unicode_csv_data): def utf_8_encoder(unicode_csv_data):
for line in unicode_csv_data: for line in unicode_csv_data:
yield line.encode('utf-8') yield line.encode('utf-8')
class Command(LabelCommand): class Command(LabelCommand):
args = '<filename>' args = '<filename>'
help = 'Import users from a CSV file with the field order: username, firstname, lastname, email.' help = 'Import users from a CSV file with the field order: username, firstname, lastname, email.'
@@ -34,7 +36,7 @@ class Command(LabelCommand):
make_option('--skip-repeated', action='store_true', dest='skip_repeated', make_option('--skip-repeated', action='store_true', dest='skip_repeated',
default=False, help='Don\'t exit if the user already exists.'), default=False, help='Don\'t exit if the user already exists.'),
) )
def handle_label(self, label, **options): def handle_label(self, label, **options):
if not os.access(label, os.R_OK): if not os.access(label, os.R_OK):
raise CommandError("File '%s' is not readable." % label) raise CommandError("File '%s' is not readable." % label)
@@ -68,7 +70,7 @@ class Command(LabelCommand):
sys.exit() sys.exit()
except csv.Error, e: except csv.Error, e:
sys.exit('file %s, line %d: %s' % (label, reader.line_num, e)) sys.exit('file %s, line %d: %s' % (label, reader.line_num, e))
else: else:
print 'Finish.' print 'Finish.'
else: else: