PEP8 and Pylint cleanups
This commit is contained in:
@@ -2,9 +2,8 @@ import os
|
||||
import subprocess
|
||||
|
||||
from django.utils.importlib import import_module
|
||||
from django.core.exceptions import ImproperlyConfigured
|
||||
from django.template.defaultfilters import slugify
|
||||
|
||||
from django.core.exceptions import ObjectDoesNotExist
|
||||
|
||||
from converter.conf.settings import UNPAPER_PATH
|
||||
from converter.conf.settings import OCR_OPTIONS
|
||||
@@ -14,7 +13,7 @@ from converter.conf.settings import HIGH_QUALITY_OPTIONS
|
||||
from converter.conf.settings import GRAPHICS_BACKEND
|
||||
|
||||
from exceptions import UnpaperError
|
||||
|
||||
|
||||
#from converter.conf.settings import UNOCONV_PATH
|
||||
from common import TEMPORARY_DIRECTORY
|
||||
from converter import TRANFORMATION_CHOICES
|
||||
@@ -24,26 +23,30 @@ QUALITY_DEFAULT = 'quality_default'
|
||||
QUALITY_LOW = 'quality_low'
|
||||
QUALITY_HIGH = 'quality_high'
|
||||
|
||||
QUALITY_SETTINGS = {QUALITY_DEFAULT:DEFAULT_OPTIONS, QUALITY_LOW:LOW_QUALITY_OPTIONS,
|
||||
QUALITY_HIGH:HIGH_QUALITY_OPTIONS}
|
||||
QUALITY_SETTINGS = {QUALITY_DEFAULT: DEFAULT_OPTIONS,
|
||||
QUALITY_LOW: LOW_QUALITY_OPTIONS, QUALITY_HIGH: HIGH_QUALITY_OPTIONS}
|
||||
|
||||
|
||||
def _lazy_load(fn):
|
||||
_cached = []
|
||||
|
||||
def _decorated():
|
||||
if not _cached:
|
||||
_cached.append(fn())
|
||||
return _cached[0]
|
||||
return _decorated
|
||||
|
||||
|
||||
@_lazy_load
|
||||
def _get_backend():
|
||||
return import_module(GRAPHICS_BACKEND)
|
||||
|
||||
try:
|
||||
try:
|
||||
backend = _get_backend()
|
||||
except ImportError:
|
||||
raise ImportError('Missing or incorrect converter backend: %s' % GRAPHICS_BACKEND)
|
||||
|
||||
|
||||
def cleanup(filename):
|
||||
''' tries to remove the given filename. Ignores non-existent files '''
|
||||
try:
|
||||
@@ -51,6 +54,7 @@ def cleanup(filename):
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
def execute_unpaper(input_filepath, output_filepath):
|
||||
command = []
|
||||
command.append(UNPAPER_PATH)
|
||||
@@ -73,7 +77,7 @@ def execute_unoconv(input_filepath, output_filepath, arguments=''):
|
||||
return (proc.wait(), proc.stderr.read())
|
||||
"""
|
||||
|
||||
|
||||
|
||||
def cache_cleanup(input_filepath, size, quality=QUALITY_DEFAULT, page=0, format='jpg', extra_options=''):
|
||||
filepath = create_image_cache_filename(input_filepath, size=size, page=page, format=format, quality=quality, extra_options=extra_options)
|
||||
try:
|
||||
@@ -90,20 +94,22 @@ def create_image_cache_filename(input_filepath, *args, **kwargs):
|
||||
final_filepath = []
|
||||
[final_filepath.append(str(arg)) for arg in args]
|
||||
final_filepath.extend(['%s_%s' % (key, value) for key, value in kwargs.items()])
|
||||
|
||||
|
||||
temp_path += slugify('_'.join(final_filepath))
|
||||
|
||||
return temp_path
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def in_image_cache(input_filepath, size, page=0, format='jpg', quality=QUALITY_DEFAULT, extra_options=''):
|
||||
output_filepath = create_image_cache_filename(input_filepath, size=size, page=page, format=format, quality=quality, extra_options=extra_options)
|
||||
if os.path.exists(output_filepath):
|
||||
return output_filepath
|
||||
else:
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def convert(input_filepath, size, quality=QUALITY_DEFAULT, cache=True, page=0, format='jpg', extra_options='', mimetype=None, extension=None, cleanup_files=True):
|
||||
unoconv_output = None
|
||||
output_filepath = create_image_cache_filename(input_filepath, size=size, page=page, format=format, quality=quality, extra_options=extra_options)
|
||||
@@ -116,7 +122,7 @@ def convert(input_filepath, size, quality=QUALITY_DEFAULT, cache=True, page=0, f
|
||||
status, error_string = execute_unoconv(input_filepath, unoconv_output, arguments='-f pdf')
|
||||
if status:
|
||||
errors = get_errors(error_string)
|
||||
raise ConvertError(status, errors)
|
||||
raise ConvertError(status, errors)
|
||||
cleanup(input_filepath)
|
||||
input_filepath = unoconv_output
|
||||
'''
|
||||
@@ -129,9 +135,10 @@ def convert(input_filepath, size, quality=QUALITY_DEFAULT, cache=True, page=0, f
|
||||
cleanup(input_filepath)
|
||||
if unoconv_output:
|
||||
cleanup(unoconv_output)
|
||||
|
||||
|
||||
return output_filepath
|
||||
|
||||
|
||||
def get_page_count(input_filepath):
|
||||
try:
|
||||
return int(backend.execute_identify(input_filepath, '-format %n'))
|
||||
@@ -139,10 +146,11 @@ def get_page_count(input_filepath):
|
||||
#TODO: send to other page number identifying program
|
||||
return 1
|
||||
|
||||
|
||||
def convert_document_for_ocr(document, page=0, format='tif'):
|
||||
#Extract document file
|
||||
input_filepath = document_save_to_temp_dir(document, document.uuid)
|
||||
|
||||
|
||||
#Convert for OCR
|
||||
temp_filename, separator = os.path.splitext(os.path.basename(input_filepath))
|
||||
temp_path = os.path.join(TEMPORARY_DIRECTORY, temp_filename)
|
||||
@@ -150,13 +158,13 @@ def convert_document_for_ocr(document, page=0, format='tif'):
|
||||
unpaper_input_file = '%s_unpaper_in%s%spnm' % (temp_path, page, os.extsep)
|
||||
unpaper_output_file = '%s_unpaper_out%s%spnm' % (temp_path, page, os.extsep)
|
||||
convert_output_file = '%s_ocr%s%s%s' % (temp_path, page, os.extsep, format)
|
||||
|
||||
|
||||
input_arg = '%s[%s]' % (input_filepath, page)
|
||||
|
||||
transformation_list = []
|
||||
try:
|
||||
#Catch invalid or non existing pages
|
||||
document_page = document.documentpage_set.get(document=document, page_number=page+1)
|
||||
document_page = document.documentpage_set.get(document=document, page_number=page + 1)
|
||||
for page_transformation in document_page.documentpagetransformation_set.all():
|
||||
if page_transformation.transformation in TRANFORMATION_CHOICES:
|
||||
output = TRANFORMATION_CHOICES[page_transformation.transformation] % eval(page_transformation.arguments)
|
||||
|
||||
@@ -7,6 +7,7 @@ from converter.exceptions import ConvertError, UnknownFormat, IdentifyError
|
||||
|
||||
CONVERTER_ERROR_STRING_NO_DECODER = 'No decode delegate for this image format'
|
||||
|
||||
|
||||
def execute_identify(input_filepath, arguments):
|
||||
command = []
|
||||
command.append(GM_PATH)
|
||||
@@ -19,7 +20,8 @@ def execute_identify(input_filepath, arguments):
|
||||
if return_code != 0:
|
||||
raise IdentifyError(proc.stderr.readline())
|
||||
return proc.stdout.read()
|
||||
|
||||
|
||||
|
||||
def execute_convert(input_filepath, output_filepath, quality=QUALITY_DEFAULT, arguments=None):
|
||||
command = []
|
||||
command.append(GM_PATH)
|
||||
|
||||
@@ -9,6 +9,7 @@ from converter.exceptions import ConvertError, UnknownFormat, \
|
||||
|
||||
CONVERTER_ERROR_STRING_NO_DECODER = 'no decode delegate for this image format'
|
||||
|
||||
|
||||
def execute_identify(input_filepath, arguments):
|
||||
command = []
|
||||
command.append(IM_IDENTIFY_PATH)
|
||||
@@ -20,7 +21,8 @@ def execute_identify(input_filepath, arguments):
|
||||
if return_code != 0:
|
||||
raise IdentifyError(proc.stderr.readline())
|
||||
return proc.stdout.read()
|
||||
|
||||
|
||||
|
||||
def execute_convert(input_filepath, output_filepath, quality=QUALITY_DEFAULT, arguments=None):
|
||||
command = []
|
||||
command.append(IM_CONVERT_PATH)
|
||||
|
||||
@@ -15,9 +15,9 @@ HIGH_QUALITY_OPTIONS = getattr(settings, 'CONVERTER_HIGH_QUALITY_OPTIONS', u'-de
|
||||
|
||||
|
||||
setting_description = {
|
||||
'CONVERTER_IM_CONVERT_PATH':_(u'File path to imagemagick\'s convert program.'),
|
||||
'CONVERTER_IM_IDENTIFY_PATH':_(u'File path to imagemagick\'s identify program.'),
|
||||
'CONVERTER_GM_PATH':_(u'File path to graphicsmagick\'s program.'),
|
||||
'CONVERTER_UNPAPER_PATH':_(u'File path to unpaper program.'),
|
||||
'CONVERTER_GRAPHICS_BACKEND':_(u'Graphics conversion backend to use. Options are: converter.backends.imagemagick and converter.backends.graphicsmagick.'),
|
||||
'CONVERTER_IM_CONVERT_PATH': _(u'File path to imagemagick\'s convert program.'),
|
||||
'CONVERTER_IM_IDENTIFY_PATH': _(u'File path to imagemagick\'s identify program.'),
|
||||
'CONVERTER_GM_PATH': _(u'File path to graphicsmagick\'s program.'),
|
||||
'CONVERTER_UNPAPER_PATH': _(u'File path to unpaper program.'),
|
||||
'CONVERTER_GRAPHICS_BACKEND': _(u'Graphics conversion backend to use. Options are: converter.backends.imagemagick and converter.backends.graphicsmagick.'),
|
||||
}
|
||||
|
||||
@@ -14,16 +14,16 @@ class UnpaperError(ConvertError):
|
||||
'''Raised by upaper
|
||||
'''
|
||||
pass
|
||||
|
||||
|
||||
|
||||
|
||||
class IdentifyError(ConvertError):
|
||||
'''Raised by identify
|
||||
'''
|
||||
pass
|
||||
|
||||
|
||||
|
||||
class UnkownConvertError(ConvertError):
|
||||
'''Raised when an error is found but there is no disernible way to
|
||||
'''Raised when an error is found but there is no disernible way to
|
||||
identify the kind of error
|
||||
'''
|
||||
pass
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python
|
||||
def copyfile(source, dest, buffer_size=1024*1024):
|
||||
|
||||
|
||||
def copyfile(source, dest, buffer_size=1024 * 1024):
|
||||
"""
|
||||
Copy a file from source to dest. source and dest
|
||||
can either be strings or any object with a read or
|
||||
|
||||
@@ -14,7 +14,7 @@ from models import DocumentMetadataIndex, Document
|
||||
|
||||
if SLUGIFY_PATHS == False:
|
||||
#Do not slugify path or filenames and extensions
|
||||
slugify = lambda x:x
|
||||
slugify = lambda x: x
|
||||
|
||||
|
||||
def document_create_fs_links(document):
|
||||
@@ -22,9 +22,9 @@ def document_create_fs_links(document):
|
||||
if FILESERVING_ENABLE:
|
||||
if not document.exists():
|
||||
raise Exception(_(u'Not creating metadata indexing, document not found in document storage'))
|
||||
metadata_dict = {'document':document}
|
||||
metadata_dict = {'document': document}
|
||||
metadata_dict.update(dict([(metadata.metadata_type.name, slugify(metadata.value)) for metadata in document.documentmetadata_set.all()]))
|
||||
|
||||
|
||||
for metadata_index in document.document_type.metadataindex_set.all():
|
||||
if metadata_index.enabled:
|
||||
try:
|
||||
@@ -35,9 +35,8 @@ def document_create_fs_links(document):
|
||||
except OSError, exc:
|
||||
if exc.errno == errno.EEXIST:
|
||||
pass
|
||||
else:
|
||||
else:
|
||||
raise OSError(_(u'Unable to create metadata indexing directory: %s') % exc)
|
||||
|
||||
|
||||
next_available_filename(document, metadata_index, target_directory, slugify(document.file_filename), slugify(document.file_extension))
|
||||
except NameError, exc:
|
||||
@@ -50,6 +49,7 @@ def document_create_fs_links(document):
|
||||
|
||||
return warnings
|
||||
|
||||
|
||||
def document_delete_fs_links(document):
|
||||
if FILESERVING_ENABLE:
|
||||
for document_metadata_index in document.documentmetadataindex_set.all():
|
||||
@@ -60,11 +60,11 @@ def document_delete_fs_links(document):
|
||||
if exc.errno == errno.ENOENT:
|
||||
#No longer exits, so delete db entry anyway
|
||||
document_metadata_index.delete()
|
||||
else:
|
||||
else:
|
||||
raise OSError(_(u'Unable to delete metadata indexing symbolic link: %s') % exc)
|
||||
|
||||
|
||||
path, filename = os.path.split(document_metadata_index.filename)
|
||||
|
||||
|
||||
#Cleanup directory of dead stuff
|
||||
#Delete siblings that are dead links
|
||||
try:
|
||||
@@ -84,19 +84,18 @@ def document_delete_fs_links(document):
|
||||
try:
|
||||
os.removedirs(path)
|
||||
except:
|
||||
pass
|
||||
pass
|
||||
except OSError, exc:
|
||||
pass
|
||||
|
||||
|
||||
#Remove the directory if it is empty
|
||||
try:
|
||||
os.removedirs(path)
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
def next_available_filename(document, metadata_index, path, filename, extension, suffix=0):
|
||||
|
||||
def next_available_filename(document, metadata_index, path, filename, extension, suffix=0):
|
||||
target = filename
|
||||
if suffix:
|
||||
target = '_'.join([filename, unicode(suffix)])
|
||||
@@ -117,23 +116,22 @@ def next_available_filename(document, metadata_index, path, filename, extension,
|
||||
#Try again with same suffix
|
||||
return next_available_filename(document, metadata_index, path, filename, extension, suffix)
|
||||
except Exception, exc:
|
||||
raise Exception(_(u'Unable to create symbolic link, filename clash: %(filepath)s; %(exc)s') % {'filepath':filepath, 'exc':exc})
|
||||
|
||||
raise Exception(_(u'Unable to create symbolic link, filename clash: %(filepath)s; %(exc)s') % {'filepath': filepath, 'exc': exc})
|
||||
else:
|
||||
raise OSError(_(u'Unable to create symbolic link: %(filepath)s; %(exc)s') % {'filepath':filepath, 'exc':exc})
|
||||
|
||||
raise OSError(_(u'Unable to create symbolic link: %(filepath)s; %(exc)s') % {'filepath': filepath, 'exc': exc})
|
||||
|
||||
return filepath
|
||||
else:
|
||||
if suffix > MAX_RENAME_COUNT:
|
||||
raise Exception(_(u'Maximum rename count reached, not creating symbolic link'))
|
||||
return next_available_filename(document, metadata_index, path, filename, extension, suffix+1)
|
||||
return next_available_filename(document, metadata_index, path, filename, extension, suffix + 1)
|
||||
|
||||
|
||||
#TODO: diferentiate between evaluation error and filesystem errors
|
||||
def do_recreate_all_links(raise_exception=True):
|
||||
errors = []
|
||||
warnings = []
|
||||
|
||||
|
||||
for document in Document.objects.all():
|
||||
try:
|
||||
document_delete_fs_links(document)
|
||||
@@ -153,7 +151,7 @@ def do_recreate_all_links(raise_exception=True):
|
||||
raise Exception(e)
|
||||
else:
|
||||
errors.append('%s: %s' % (document, e))
|
||||
|
||||
|
||||
for warning in create_warnings:
|
||||
warnings.append('%s: %s' % (document, e))
|
||||
warnings.append('%s: %s' % (document, warning))
|
||||
return errors, warnings
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
'''Configuration options for the filesystem_serving app
|
||||
'''
|
||||
|
||||
from django.conf import settings
|
||||
|
||||
from common.utils import proper_name
|
||||
|
||||
available_indexing_functions = {
|
||||
'proper_name':proper_name
|
||||
'proper_name': proper_name
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -17,21 +17,21 @@ def recreate_all_links(request):
|
||||
|
||||
previous = request.POST.get('previous', request.GET.get('previous', request.META.get('HTTP_REFERER', None)))
|
||||
next = request.POST.get('next', request.GET.get('next', request.META.get('HTTP_REFERER', None)))
|
||||
|
||||
|
||||
if request.method != 'POST':
|
||||
return render_to_response('generic_confirm.html', {
|
||||
'previous':previous,
|
||||
'next':next,
|
||||
'message':_(u'On large databases this operation may take some time to execute.'),
|
||||
'previous': previous,
|
||||
'next': next,
|
||||
'message': _(u'On large databases this operation may take some time to execute.'),
|
||||
}, context_instance=RequestContext(request))
|
||||
else:
|
||||
else:
|
||||
try:
|
||||
errors, warnings = do_recreate_all_links()
|
||||
messages.success(request, _(u'Filesystem links re-creation completed successfully.'))
|
||||
for warning in warnings:
|
||||
messages.warning(request, warning)
|
||||
|
||||
|
||||
except Exception, e:
|
||||
messages.error(request, _(u'Filesystem links re-creation error: %s') % e)
|
||||
|
||||
|
||||
return HttpResponseRedirect(next)
|
||||
|
||||
@@ -8,24 +8,24 @@ model_list_columns = {}
|
||||
|
||||
def register_multi_item_links(src, links, menu_name=None):
|
||||
if menu_name in multi_object_navigation:
|
||||
if hasattr(src, '__iter__'):
|
||||
if hasattr(src, '__iter__'):
|
||||
for one_src in src:
|
||||
if one_src in object_navigation[menu_name]:
|
||||
multi_object_navigation[menu_name][one_src]['links'].extend(links)
|
||||
else:
|
||||
multi_object_navigation[menu_name][one_src] = {'links':copy.copy(links)}
|
||||
multi_object_navigation[menu_name][one_src] = {'links': copy.copy(links)}
|
||||
else:
|
||||
if src in multi_object_navigation[menu_name]:
|
||||
multi_object_navigation[menu_name][src]['links'].extend(links)
|
||||
else:
|
||||
multi_object_navigation[menu_name][src] = {'links':links}
|
||||
multi_object_navigation[menu_name][src] = {'links': links}
|
||||
else:
|
||||
multi_object_navigation[menu_name] = {}
|
||||
if hasattr(src, '__iter__'):
|
||||
for one_src in src:
|
||||
multi_object_navigation[menu_name][one_src] = {'links':links}
|
||||
multi_object_navigation[menu_name][one_src] = {'links': links}
|
||||
else:
|
||||
multi_object_navigation[menu_name] = {src:{'links':links}}
|
||||
multi_object_navigation[menu_name] = {src: {'links': links}}
|
||||
|
||||
|
||||
def register_links(src, links, menu_name=None):
|
||||
@@ -35,26 +35,26 @@ def register_links(src, links, menu_name=None):
|
||||
if one_src in object_navigation[menu_name]:
|
||||
object_navigation[menu_name][one_src]['links'].extend(links)
|
||||
else:
|
||||
object_navigation[menu_name][one_src] = {'links':copy.copy(links)}
|
||||
object_navigation[menu_name][one_src] = {'links': copy.copy(links)}
|
||||
else:
|
||||
if src in object_navigation[menu_name]:
|
||||
object_navigation[menu_name][src]['links'].extend(links)
|
||||
else:
|
||||
object_navigation[menu_name][src] = {'links':links}
|
||||
object_navigation[menu_name][src] = {'links': links}
|
||||
else:
|
||||
object_navigation[menu_name] = {}
|
||||
object_navigation[menu_name] = {}
|
||||
if hasattr(src, '__iter__'):
|
||||
for one_src in src:
|
||||
object_navigation[menu_name][one_src] = {'links':links}
|
||||
object_navigation[menu_name][one_src] = {'links': links}
|
||||
else:
|
||||
object_navigation[menu_name] = {src:{'links':links}}
|
||||
|
||||
object_navigation[menu_name] = {src: {'links': links}}
|
||||
|
||||
|
||||
def register_menu(links):
|
||||
for link in links:
|
||||
menu_links.append(link)
|
||||
|
||||
menu_links.sort(lambda x, y: 1 if x>y else -1, lambda x:x['position'] if 'position' in x else 1)
|
||||
|
||||
menu_links.sort(lambda x, y: 1 if x > y else -1, lambda x: x['position'] if 'position' in x else 1)
|
||||
|
||||
|
||||
def register_model_list_columns(model, columns):
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
from django import forms
|
||||
from django import forms
|
||||
from django.utils.translation import ugettext as _
|
||||
from django.template.defaultfilters import capfirst
|
||||
|
||||
|
||||
class MultiItemForm(forms.Form):
|
||||
@@ -9,5 +10,5 @@ class MultiItemForm(forms.Form):
|
||||
choices = [('', '------')]
|
||||
choices.extend([(action[0], capfirst(action[1])) for action in actions])
|
||||
self.fields['action'].choices = choices
|
||||
|
||||
|
||||
action = forms.ChoiceField(label=_(u'Multi item action'))
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import copy
|
||||
import copy
|
||||
import re
|
||||
|
||||
from django.core.urlresolvers import reverse, NoReverseMatch
|
||||
@@ -32,24 +32,22 @@ def process_links(links, view_name, url):
|
||||
child_url = 'url' in child_link and child_link['url']
|
||||
if view_name == child_view or url == child_url:
|
||||
active = True
|
||||
active_item = item
|
||||
|
||||
items.append(
|
||||
{
|
||||
'first':count==0,
|
||||
'active':active,
|
||||
'url':item_view and reverse(item_view) or item_url or '#',
|
||||
'text':unicode(item['text']),
|
||||
'famfam':'famfam' in item and item['famfam'],
|
||||
}
|
||||
)
|
||||
active_item = item
|
||||
|
||||
items.append({
|
||||
'first': count == 0,
|
||||
'active': active,
|
||||
'url': item_view and reverse(item_view) or item_url or '#',
|
||||
'text': unicode(item['text']),
|
||||
'famfam': 'famfam' in item and item['famfam'],
|
||||
})
|
||||
return items, active_item
|
||||
|
||||
|
||||
class NavigationNode(Node):
|
||||
def __init__(self, navigation, *args, **kwargs):
|
||||
self.navigation = navigation
|
||||
|
||||
|
||||
def render(self, context):
|
||||
request = Variable('request').resolve(context)
|
||||
view_name = resolve_to_name(request.META['PATH_INFO'])
|
||||
@@ -59,7 +57,7 @@ class NavigationNode(Node):
|
||||
if active_item and 'links' in active_item:
|
||||
secondary_links, active_item = process_links(links=active_item['links'], view_name=view_name, url=request.META['PATH_INFO'])
|
||||
context['navigation_secondary_links'] = secondary_links
|
||||
return ''
|
||||
return ''
|
||||
|
||||
|
||||
@register.tag
|
||||
@@ -69,13 +67,14 @@ def main_navigation(parser, token):
|
||||
# if len(args) != 3 or args[1] != 'as':
|
||||
# raise TemplateSyntaxError("'get_all_states' requires 'as variable' (got %r)" % args)
|
||||
|
||||
#return NavigationNode(variable=args[2], navigation=navigation)
|
||||
return NavigationNode(navigation=menu_navigation)
|
||||
#return NavigationNode(variable=args[2], navigation=navigation)
|
||||
return NavigationNode(navigation=menu_navigation)
|
||||
|
||||
|
||||
#http://www.djangosnippets.org/snippets/1378/
|
||||
__all__ = ('resolve_to_name',)
|
||||
|
||||
|
||||
def _pattern_resolve_to_name(self, path):
|
||||
match = self.regex.search(path)
|
||||
if match:
|
||||
@@ -88,6 +87,7 @@ def _pattern_resolve_to_name(self, path):
|
||||
name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
|
||||
return name
|
||||
|
||||
|
||||
def _resolver_resolve_to_name(self, path):
|
||||
tried = []
|
||||
match = self.regex.search(path)
|
||||
@@ -109,13 +109,16 @@ def _resolver_resolve_to_name(self, path):
|
||||
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
|
||||
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name
|
||||
|
||||
|
||||
def resolve_to_name(path, urlconf=None):
|
||||
return get_resolver(urlconf).resolve_to_name(path)
|
||||
|
||||
|
||||
@register.filter
|
||||
def resolve_url_name(value):
|
||||
return resolve_to_name(value)
|
||||
|
||||
|
||||
def resolve_arguments(context, src_args):
|
||||
args = []
|
||||
kwargs = {}
|
||||
@@ -132,10 +135,10 @@ def resolve_arguments(context, src_args):
|
||||
else:
|
||||
val = resolve_template_variable(context, src_args)
|
||||
if val:
|
||||
args.append(val)
|
||||
args.append(val)
|
||||
|
||||
return args, kwargs
|
||||
|
||||
|
||||
|
||||
def resolve_links(context, links, current_view, current_path):
|
||||
context_links = []
|
||||
@@ -145,11 +148,11 @@ def resolve_links(context, links, current_view, current_path):
|
||||
args, kwargs = resolve_arguments(context, link.get('args', {}))
|
||||
except VariableDoesNotExist:
|
||||
args = []
|
||||
kwargs = {}
|
||||
|
||||
kwargs = {}
|
||||
|
||||
if 'view' in link:
|
||||
new_link['active'] = link['view'] == current_view
|
||||
|
||||
|
||||
try:
|
||||
if kwargs:
|
||||
new_link['url'] = reverse(link['view'], kwargs=kwargs)
|
||||
@@ -166,25 +169,25 @@ def resolve_links(context, links, current_view, current_path):
|
||||
new_link['url'] = link['url'] % args
|
||||
else:
|
||||
new_link['active'] = False
|
||||
context_links.append(new_link)
|
||||
context_links.append(new_link)
|
||||
return context_links
|
||||
|
||||
|
||||
def _get_object_navigation_links(context, menu_name=None, links_dict=object_navigation):
|
||||
current_path = Variable('request').resolve(context).META['PATH_INFO']
|
||||
current_view = resolve_to_name(current_path)#.get_full_path())
|
||||
context_links = []
|
||||
current_view = resolve_to_name(current_path)
|
||||
context_links = []
|
||||
|
||||
try:
|
||||
object_name = Variable('navigation_object_name').resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
object_name = 'object'
|
||||
|
||||
|
||||
try:
|
||||
obj = Variable(object_name).resolve(context)
|
||||
except VariableDoesNotExist:
|
||||
obj = None
|
||||
|
||||
|
||||
try:
|
||||
links = links_dict[menu_name][current_view]['links']
|
||||
for link in resolve_links(context, links, current_view, current_path):
|
||||
@@ -233,19 +236,19 @@ def get_object_navigation_links(parser, token):
|
||||
if not m:
|
||||
raise TemplateSyntaxError("%r tag had invalid arguments" % tag_name)
|
||||
|
||||
menu_name, var_name = m.groups()
|
||||
menu_name, var_name = m.groups()
|
||||
return GetNavigationLinks(menu_name=menu_name, var_name=var_name)
|
||||
|
||||
|
||||
|
||||
|
||||
@register.inclusion_tag('generic_navigation.html', takes_context=True)
|
||||
def object_navigation_template(context):
|
||||
return {
|
||||
'request':context['request'],
|
||||
'horizontal':True,
|
||||
'object_navigation_links':_get_object_navigation_links(context)
|
||||
'request': context['request'],
|
||||
'horizontal': True,
|
||||
'object_navigation_links': _get_object_navigation_links(context)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@register.tag
|
||||
def get_multi_item_links(parser, token):
|
||||
tag_name, arg = token.contents.split(None, 1)
|
||||
@@ -261,9 +264,9 @@ def get_multi_item_links(parser, token):
|
||||
def get_multi_item_links_form(context):
|
||||
new_context = copy.copy(context)
|
||||
new_context.update({
|
||||
'form':MultiItemForm(actions=[(link['url'], link['text']) for link in _get_object_navigation_links(context, links_dict=multi_object_navigation)]),
|
||||
'title':_(u'Selected item actions:'),
|
||||
'form_action':reverse('multi_object_action_view'),
|
||||
'submit_method':'get',
|
||||
'form': MultiItemForm(actions=[(link['url'], link['text']) for link in _get_object_navigation_links(context, links_dict=multi_object_navigation)]),
|
||||
'title': _(u'Selected item actions:'),
|
||||
'form_action': reverse('multi_object_action_view'),
|
||||
'submit_method': 'get',
|
||||
})
|
||||
return new_context
|
||||
|
||||
@@ -5,7 +5,7 @@ from django.shortcuts import get_object_or_404
|
||||
from django.contrib.contenttypes.models import ContentType
|
||||
from django.utils.translation import ugettext_lazy as _
|
||||
from django.utils.translation import ugettext
|
||||
from django.core.exceptions import PermissionDenied
|
||||
from django.core.exceptions import PermissionDenied
|
||||
|
||||
from permissions import PERMISSION_ROLE_VIEW, PERMISSION_ROLE_EDIT, \
|
||||
PERMISSION_ROLE_CREATE, PERMISSION_ROLE_DELETE, \
|
||||
@@ -13,6 +13,7 @@ from permissions import PERMISSION_ROLE_VIEW, PERMISSION_ROLE_EDIT, \
|
||||
|
||||
from models import Permission, Role
|
||||
|
||||
|
||||
def register_permissions(namespace, permissions):
|
||||
if permissions:
|
||||
for permission in permissions:
|
||||
@@ -25,18 +26,19 @@ def register_permissions(namespace, permissions):
|
||||
#Special case for ./manage.py syncdb
|
||||
pass
|
||||
|
||||
|
||||
#TODO: Handle anonymous users
|
||||
def check_permissions(requester, namespace, permission_list):
|
||||
if isinstance(requester, User):
|
||||
if requester.is_superuser:
|
||||
return True
|
||||
|
||||
|
||||
for permission_item in permission_list:
|
||||
permission = get_object_or_404(Permission,
|
||||
namespace=namespace, name=permission_item)
|
||||
if check_permission(requester, permission):
|
||||
return True
|
||||
|
||||
|
||||
raise PermissionDenied(ugettext(u'Insufficient permissions.'))
|
||||
|
||||
|
||||
@@ -44,13 +46,13 @@ def check_permission(requester, permission):
|
||||
for permission_holder in permission.permissionholder_set.all():
|
||||
if check_requester(requester, permission_holder):
|
||||
return True
|
||||
|
||||
|
||||
|
||||
|
||||
def check_requester(requester, permission_holder):
|
||||
ct = ContentType.objects.get_for_model(requester)
|
||||
if permission_holder.holder_type == ct and permission_holder.holder_id == requester.id:
|
||||
return True
|
||||
|
||||
|
||||
if isinstance(permission_holder.holder_object, Role):
|
||||
requester_list = [role_member.member_object for role_member in permission_holder.holder_object.rolemember_set.all()]
|
||||
if check_elements(requester, requester_list):
|
||||
@@ -71,10 +73,10 @@ def check_elements(requester, requester_list):
|
||||
|
||||
|
||||
register_permissions('permissions', [
|
||||
{'name':PERMISSION_ROLE_VIEW, 'label':_(u'View roles')},
|
||||
{'name':PERMISSION_ROLE_EDIT, 'label':_(u'Edit roles')},
|
||||
{'name':PERMISSION_ROLE_CREATE, 'label':_(u'Create roles')},
|
||||
{'name':PERMISSION_ROLE_DELETE, 'label':_(u'Delete roles')},
|
||||
{'name':PERMISSION_PERMISSION_GRANT, 'label':_(u'Grant permissions')},
|
||||
{'name':PERMISSION_PERMISSION_REVOKE, 'label':_(u'Revoke permissions')},
|
||||
{'name': PERMISSION_ROLE_VIEW, 'label':_(u'View roles')},
|
||||
{'name': PERMISSION_ROLE_EDIT, 'label':_(u'Edit roles')},
|
||||
{'name': PERMISSION_ROLE_CREATE, 'label':_(u'Create roles')},
|
||||
{'name': PERMISSION_ROLE_DELETE, 'label':_(u'Delete roles')},
|
||||
{'name': PERMISSION_PERMISSION_GRANT, 'label':_(u'Grant permissions')},
|
||||
{'name': PERMISSION_PERMISSION_REVOKE, 'label':_(u'Revoke permissions')},
|
||||
])
|
||||
|
||||
@@ -4,10 +4,12 @@ from django.core.files.storage import FileSystemStorage
|
||||
|
||||
from storage.conf.settings import FILESTORAGE_LOCATION
|
||||
|
||||
|
||||
class FileBasedStorage(FileSystemStorage):
|
||||
'''Simple wrapper for the stock Django FileSystemStorage class
|
||||
'''
|
||||
separator = os.path.sep
|
||||
|
||||
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(FileBasedStorage, self).__init__(*args, **kwargs)
|
||||
self.location = FILESTORAGE_LOCATION
|
||||
|
||||
|
||||
@@ -20,4 +20,3 @@ os.environ['CELERY_LOADER'] = 'django'
|
||||
|
||||
from django.core.handlers.wsgi import WSGIHandler
|
||||
application = WSGIHandler()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user