Commit 791888ee by Russell Jones Committed by benjaoming

Add changes suggested by python-modernize

parent a559f734
...@@ -28,6 +28,7 @@ Options: ...@@ -28,6 +28,7 @@ Options:
--version Show version. --version Show version.
""" """
from __future__ import print_function
from docopt import docopt from docopt import docopt
import os import os
import re import re
...@@ -74,7 +75,7 @@ if __name__ == '__main__': ...@@ -74,7 +75,7 @@ if __name__ == '__main__':
contents = f.read() contents = f.read()
f.close() f.close()
if RE_FK_LABEL.search(contents) or RE_META_STRING.search(contents) or RE_AUTH_MODEL.search(contents) or RE_FK_LABEL.search(contents): if RE_FK_LABEL.search(contents) or RE_META_STRING.search(contents) or RE_AUTH_MODEL.search(contents) or RE_FK_LABEL.search(contents):
print "Refactoring {0}".format(fname) print("Refactoring {0}".format(fname))
f = open(full_path, 'w') f = open(full_path, 'w')
contents = RE_CLASS_NAME.sub(INSERT_AT_TOP_OF_MIGRATION + r"\2", contents = RE_CLASS_NAME.sub(INSERT_AT_TOP_OF_MIGRATION + r"\2",
contents) contents)
...@@ -85,6 +86,6 @@ if __name__ == '__main__': ...@@ -85,6 +86,6 @@ if __name__ == '__main__':
f.write(contents) f.write(contents)
f.close() f.close()
else: else:
print "Skipping {0}".format(fname) print("Skipping {0}".format(fname))
if RE_TEST_OK.search(contents): if RE_TEST_OK.search(contents):
print " WARNING! Still found occurrences of auth.User. Fix manually!" print(" WARNING! Still found occurrences of auth.User. Fix manually!")
...@@ -22,7 +22,7 @@ from django.contrib.contenttypes.models import ContentType ...@@ -22,7 +22,7 @@ from django.contrib.contenttypes.models import ContentType
from django.db.models import Model from django.db.models import Model
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
import models from . import models
_disable_notifications = False _disable_notifications = False
......
from __future__ import print_function
import os import os
import sys import sys
import time import time
...@@ -62,7 +63,7 @@ class Command(BaseCommand): ...@@ -62,7 +63,7 @@ class Command(BaseCommand):
self.logger.info("Starting django_notify e-mail dispatcher") self.logger.info("Starting django_notify e-mail dispatcher")
if not notify_settings.SEND_EMAILS: if not notify_settings.SEND_EMAILS:
print "E-mails disabled - quitting." print("E-mails disabled - quitting.")
sys.exit() sys.exit()
...@@ -79,14 +80,14 @@ class Command(BaseCommand): ...@@ -79,14 +80,14 @@ class Command(BaseCommand):
pid_file.write(str(fpid)) pid_file.write(str(fpid))
pid_file.close() pid_file.close()
sys.exit(0) sys.exit(0)
except OSError, e: except OSError as e:
sys.stderr.write("fork failed: %d (%s)\n" % (e.errno, e.strerror)) sys.stderr.write("fork failed: %d (%s)\n" % (e.errno, e.strerror))
sys.exit(1) sys.exit(1)
try: try:
self.send_loop() self.send_loop()
except KeyboardInterrupt: except KeyboardInterrupt:
print "\nQuitting..." print("\nQuitting...")
# deactivate the language # deactivate the language
deactivate() deactivate()
......
from __future__ import print_function
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
# #
# django-wiki documentation build configuration file, created by # django-wiki documentation build configuration file, created by
...@@ -57,7 +58,7 @@ sys.path = [os.path.join(path, 'wiki')] + sys.path ...@@ -57,7 +58,7 @@ sys.path = [os.path.join(path, 'wiki')] + sys.path
import wiki import wiki
print wiki.__file__ print(wiki.__file__)
# The version info for the project you're documenting, acts as replacement for # The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the # |version| and |release|, also used in various other places throughout the
......
...@@ -4,8 +4,8 @@ from django.utils.translation import ugettext_lazy as _ ...@@ -4,8 +4,8 @@ from django.utils.translation import ugettext_lazy as _
from mptt.admin import MPTTModelAdmin from mptt.admin import MPTTModelAdmin
from django import forms from django import forms
import models from . import models
import editors from . import editors
class ArticleObjectAdmin(GenericTabularInline): class ArticleObjectAdmin(GenericTabularInline):
model = models.ArticleForObject model = models.ArticleForObject
...@@ -73,4 +73,4 @@ class URLPathAdmin(MPTTModelAdmin): ...@@ -73,4 +73,4 @@ class URLPathAdmin(MPTTModelAdmin):
admin.site.register(models.URLPath, URLPathAdmin) admin.site.register(models.URLPath, URLPathAdmin)
admin.site.register(models.Article, ArticleAdmin) admin.site.register(models.Article, ArticleAdmin)
admin.site.register(models.ArticleRevision, ArticleRevisionAdmin) admin.site.register(models.ArticleRevision, ArticleRevisionAdmin)
\ No newline at end of file
...@@ -5,6 +5,7 @@ https://github.com/ojii/django-load. ...@@ -5,6 +5,7 @@ https://github.com/ojii/django-load.
Thanks for the technique! Thanks for the technique!
""" """
from __future__ import print_function
from django.conf import settings from django.conf import settings
from django.utils.importlib import import_module from django.utils.importlib import import_module
...@@ -15,14 +16,14 @@ def get_module(app, modname, verbose, failfast): ...@@ -15,14 +16,14 @@ def get_module(app, modname, verbose, failfast):
module_name = '%s.%s' % (app, modname) module_name = '%s.%s' % (app, modname)
try: try:
module = import_module(module_name) module = import_module(module_name)
except ImportError, e: except ImportError as e:
if failfast: if failfast:
raise e raise e
elif verbose: elif verbose:
print "Could not load %r from %r: %s" % (modname, app, e) print("Could not load %r from %r: %s" % (modname, app, e))
return None return None
if verbose: if verbose:
print "Loaded %r from %r" % (modname, app) print("Loaded %r from %r" % (modname, app))
return module return module
def load(modname, verbose=False, failfast=False): def load(modname, verbose=False, failfast=False):
......
...@@ -72,7 +72,7 @@ def get_article(func=None, can_read=True, can_write=False, ...@@ -72,7 +72,7 @@ def get_article(func=None, can_read=True, can_write=False,
""" """
def wrapper(request, *args, **kwargs): def wrapper(request, *args, **kwargs):
import models from . import models
path = kwargs.pop('path', None) path = kwargs.pop('path', None)
article_id = kwargs.pop('article_id', None) article_id = kwargs.pop('article_id', None)
...@@ -112,7 +112,8 @@ def get_article(func=None, can_read=True, can_write=False, ...@@ -112,7 +112,8 @@ def get_article(func=None, can_read=True, can_write=False,
article = get_object_or_404(articles, id=article_id) article = get_object_or_404(articles, id=article_id)
try: try:
urlpath = models.URLPath.objects.get(articles__article=article) urlpath = models.URLPath.objects.get(articles__article=article)
except models.URLPath.DoesNotExist, models.URLPath.MultipleObjectsReturned: except models.URLPath.DoesNotExist as noarticle:
models.URLPath.MultipleObjectsReturned = noarticle
urlpath = None urlpath = None
......
...@@ -43,6 +43,7 @@ options: ...@@ -43,6 +43,7 @@ options:
-e, --inheritance -e, --inheritance
show inheritance arrows. show inheritance arrows.
""" """
from __future__ import print_function
__version__ = "0.99" __version__ = "0.99"
__svnid__ = "$Id$" __svnid__ = "$Id$"
__license__ = "Python" __license__ = "Python"
...@@ -406,8 +407,8 @@ class Command(BaseCommand): ...@@ -406,8 +407,8 @@ class Command(BaseCommand):
def handle(self, *args, **options): def handle(self, *args, **options):
if not args and not options.get('all_applications', False): if not args and not options.get('all_applications', False):
print __doc__ print(__doc__)
sys.exit() sys.exit()
print generate_dot(args, **options) print(generate_dot(args, **options))
...@@ -5,10 +5,11 @@ from django.core.exceptions import ImproperlyConfigured ...@@ -5,10 +5,11 @@ from django.core.exceptions import ImproperlyConfigured
import warnings import warnings
# TODO: Don't use wildcards # TODO: Don't use wildcards
from article import * from .article import *
from urlpath import * from .urlpath import *
# TODO: Should the below stuff be executed a more logical place? # TODO: Should the below stuff be executed a more logical place?
# Follow Django's default_settings.py / settings.py pattern and put these in d_s.py? That might be confusing, though.
###################### ######################
# Configuration stuff # Configuration stuff
......
...@@ -24,7 +24,7 @@ There are three kinds of plugin base models: ...@@ -24,7 +24,7 @@ There are three kinds of plugin base models:
""" """
from article import ArticleRevision, BaseRevisionMixin from .article import ArticleRevision, BaseRevisionMixin
from wiki.conf import settings from wiki.conf import settings
class ArticlePlugin(models.Model): class ArticlePlugin(models.Model):
......
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
from __future__ import print_function
#^was before coding line, is this required?
import logging import logging
from django.contrib.contenttypes import generic from django.contrib.contenttypes import generic
...@@ -6,7 +8,14 @@ from django.contrib.contenttypes.models import ContentType ...@@ -6,7 +8,14 @@ from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.db import models from django.db import models, transaction
from six.moves import filter
#Django 1.6 transaction API, required for 1.8+
try:
notrans=transaction.non_atomic_requests
except:
notrans=transaction.commit_manually
from django.db.models.signals import post_save, pre_delete from django.db.models.signals import post_save, pre_delete
from django.utils.translation import ugettext_lazy as _, ugettext from django.utils.translation import ugettext_lazy as _, ugettext
...@@ -117,9 +126,16 @@ class URLPath(MPTTModel): ...@@ -117,9 +126,16 @@ class URLPath(MPTTModel):
NB! This deletes this urlpath, its children, and ALL of the related NB! This deletes this urlpath, its children, and ALL of the related
articles. This is a purged delete and CANNOT be undone. articles. This is a purged delete and CANNOT be undone.
""" """
for descendant in self.get_descendants(include_self=True).order_by("-level"): try:
descendant.article.delete() for descendant in self.get_descendants(include_self=True).order_by("-level"):
print("deleting " , descendant) #space in string -> " "?
descendant.article.delete()
transaction.commit()
except:
transaction.rollback()
log.exception("Exception deleting article subtree.")
@classmethod @classmethod
def root(cls): def root(cls):
site = Site.objects.get_current() site = Site.objects.get_current()
......
from django.contrib import admin from django.contrib import admin
import models from . import models
class AttachmentRevisionAdmin(admin.TabularInline): class AttachmentRevisionAdmin(admin.TabularInline):
model = models.AttachmentRevision model = models.AttachmentRevision
......
...@@ -29,7 +29,7 @@ class AttachmentForm(forms.ModelForm): ...@@ -29,7 +29,7 @@ class AttachmentForm(forms.ModelForm):
if uploaded_file: if uploaded_file:
try: try:
models.extension_allowed(uploaded_file.name) models.extension_allowed(uploaded_file.name)
except IllegalFileExtension, e: except IllegalFileExtension as e:
raise forms.ValidationError(e) raise forms.ValidationError(e)
return uploaded_file return uploaded_file
...@@ -96,7 +96,7 @@ class AttachmentArchiveForm(AttachmentForm): ...@@ -96,7 +96,7 @@ class AttachmentArchiveForm(AttachmentForm):
for zipinfo in self.zipfile.filelist: for zipinfo in self.zipfile.filelist:
try: try:
models.extension_allowed(zipinfo.filename) models.extension_allowed(zipinfo.filename)
except IllegalFileExtension, e: except IllegalFileExtension as e:
raise forms.ValidationError(e) raise forms.ValidationError(e)
except zipfile.BadZipfile: except zipfile.BadZipfile:
raise forms.ValidationError(_(u"Not a zip file")) raise forms.ValidationError(_(u"Not a zip file"))
......
...@@ -10,6 +10,8 @@ from wiki import managers ...@@ -10,6 +10,8 @@ from wiki import managers
from wiki.models.pluginbase import ReusablePlugin from wiki.models.pluginbase import ReusablePlugin
from wiki.models.article import BaseRevisionMixin from wiki.models.article import BaseRevisionMixin
from django.db.models import signals from django.db.models import signals
from six.moves import map
from six.moves import zip
class IllegalFileExtension(Exception): class IllegalFileExtension(Exception):
"""File extension on upload is not allowed""" """File extension on upload is not allowed"""
...@@ -133,7 +135,8 @@ class AttachmentRevision(BaseRevisionMixin, models.Model): ...@@ -133,7 +135,8 @@ class AttachmentRevision(BaseRevisionMixin, models.Model):
previous_revision = self.attachment.attachmentrevision_set.latest() previous_revision = self.attachment.attachmentrevision_set.latest()
self.revision_number = previous_revision.revision_number + 1 self.revision_number = previous_revision.revision_number + 1
# NB! The above should not raise the below exception, but somehow it does. # NB! The above should not raise the below exception, but somehow it does.
except AttachmentRevision.DoesNotExist, Attachment.DoesNotExist: except AttachmentRevision.DoesNotExist as noattach
Attachment.DoesNotExist = noattach
self.revision_number = 1 self.revision_number = 1
super(AttachmentRevision, self).save(*args, **kwargs) super(AttachmentRevision, self).save(*args, **kwargs)
......
...@@ -120,7 +120,7 @@ class AttachmentReplaceView(ArticleMixin, FormView): ...@@ -120,7 +120,7 @@ class AttachmentReplaceView(ArticleMixin, FormView):
self.attachment.current_revision = attachment_revision self.attachment.current_revision = attachment_revision
self.attachment.save() self.attachment.save()
messages.success(self.request, _(u'%s uploaded and replaces old attachment.') % attachment_revision.get_filename()) messages.success(self.request, _(u'%s uploaded and replaces old attachment.') % attachment_revision.get_filename())
except models.IllegalFileExtension, e: except models.IllegalFileExtension as e:
messages.error(self.request, _(u'Your file could not be saved: %s') % e) messages.error(self.request, _(u'Your file could not be saved: %s') % e)
return redirect("wiki:attachments_replace", attachment_id=self.attachment.id, return redirect("wiki:attachments_replace", attachment_id=self.attachment.id,
path=self.urlpath.path, article_id=self.article.id) path=self.urlpath.path, article_id=self.article.id)
......
from django.contrib import admin from django.contrib import admin
from django import forms from django import forms
import models from . import models
class ImageForm(forms.ModelForm): class ImageForm(forms.ModelForm):
...@@ -26,4 +26,4 @@ class ImageAdmin(admin.ModelAdmin): ...@@ -26,4 +26,4 @@ class ImageAdmin(admin.ModelAdmin):
form = ImageForm form = ImageForm
inlines = (ImageRevisionInline,) inlines = (ImageRevisionInline,)
admin.site.register(models.Image, ImageAdmin) admin.site.register(models.Image, ImageAdmin)
\ No newline at end of file
...@@ -5,7 +5,7 @@ from django.core.exceptions import ImproperlyConfigured ...@@ -5,7 +5,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.db import models from django.db import models
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
import settings from . import settings
from wiki.models.pluginbase import RevisionPlugin, RevisionPluginRevision from wiki.models.pluginbase import RevisionPlugin, RevisionPluginRevision
from django.db.models import signals from django.db.models import signals
......
...@@ -123,9 +123,9 @@ class WikiPath(markdown.inlinepatterns.Pattern): ...@@ -123,9 +123,9 @@ class WikiPath(markdown.inlinepatterns.Pattern):
base_url = self.config['base_url'][0] base_url = self.config['base_url'][0]
html_class = self.config['html_class'][0] html_class = self.config['html_class'][0]
if hasattr(self.md, 'Meta'): if hasattr(self.md, 'Meta'):
if self.md.Meta.has_key('wiki_base_url'): if 'wiki_base_url' in self.md.Meta:
base_url = self.md.Meta['wiki_base_url'][0] base_url = self.md.Meta['wiki_base_url'][0]
if self.md.Meta.has_key('wiki_html_class'): if 'wiki_html_class' in self.md.Meta:
html_class = self.md.Meta['wiki_html_class'][0] html_class = self.md.Meta['wiki_html_class'][0]
return base_url, html_class return base_url, html_class
......
...@@ -65,7 +65,7 @@ for plugin in registry.get_plugins(): ...@@ -65,7 +65,7 @@ for plugin in registry.get_plugins():
return return
if kwargs.get('created', False) == notification_dict.get('created', True): if kwargs.get('created', False) == notification_dict.get('created', True):
url = None url = None
if notification_dict.has_key('get_url'): if 'get_url' in notification_dict:
url = notification_dict['get_url'](instance) url = notification_dict['get_url'](instance)
else: else:
url = default_url(notification_dict['get_article'](instance)) url = default_url(notification_dict['get_article'](instance))
......
...@@ -6,7 +6,7 @@ from django.utils.decorators import method_decorator ...@@ -6,7 +6,7 @@ from django.utils.decorators import method_decorator
from django.utils.translation import ugettext as _ from django.utils.translation import ugettext as _
from django.views.generic.edit import FormView from django.views.generic.edit import FormView
import forms from . import forms
class NotificationSettings(FormView): class NotificationSettings(FormView):
...@@ -20,7 +20,7 @@ class NotificationSettings(FormView): ...@@ -20,7 +20,7 @@ class NotificationSettings(FormView):
def form_valid(self, formset): def form_valid(self, formset):
for form in formset: for form in formset:
settings = form.save() settings = form.save()
import models from . import models
article_subscriptions = models.ArticleSubscription.objects.filter( article_subscriptions = models.ArticleSubscription.objects.filter(
settings = form.instance, settings = form.instance,
article__current_revision__deleted=False, article__current_revision__deleted=False,
...@@ -44,7 +44,7 @@ class NotificationSettings(FormView): ...@@ -44,7 +44,7 @@ class NotificationSettings(FormView):
def get_context_data(self, **kwargs): def get_context_data(self, **kwargs):
context = FormView.get_context_data(self, **kwargs) context = FormView.get_context_data(self, **kwargs)
context['formset'] = kwargs['form'] context['formset'] = kwargs['form']
import models from . import models
for form in context['formset']: for form in context['formset']:
if form.instance: if form.instance:
setattr(form.instance, 'articlesubscriptions', setattr(form.instance, 'articlesubscriptions',
......
...@@ -3,7 +3,7 @@ from wiki.core.plugins.base import BasePlugin ...@@ -3,7 +3,7 @@ from wiki.core.plugins.base import BasePlugin
from django.conf.urls import patterns, url from django.conf.urls import patterns, url
import settings, views from . import settings, views
class NotifyPlugin(BasePlugin): class NotifyPlugin(BasePlugin):
......
...@@ -9,6 +9,7 @@ from django.forms import BaseForm ...@@ -9,6 +9,7 @@ from django.forms import BaseForm
from django.utils.safestring import mark_safe from django.utils.safestring import mark_safe
from django.template.defaultfilters import striptags from django.template.defaultfilters import striptags
from django.utils.http import urlquote from django.utils.http import urlquote
from six.moves import filter
register = template.Library() register = template.Library()
......
from __future__ import print_function
from django.core.urlresolvers import reverse from django.core.urlresolvers import reverse
from django.test import TestCase from django.test import TestCase
from django.test.client import Client from django.test.client import Client
......
...@@ -90,8 +90,11 @@ class Create(FormView, ArticleMixin): ...@@ -90,8 +90,11 @@ class Create(FormView, ArticleMixin):
'other_write': self.article.other_write, 'other_write': self.article.other_write,
}) })
messages.success(self.request, _(u"New article '%s' created.") % self.newpath.article.current_revision.title) messages.success(self.request, _(u"New article '%s' created.") % self.newpath.article.current_revision.title)
transaction.commit()
# TODO: Handle individual exceptions better and give good feedback.
except Exception, e: except Exception, e:
log.exception("Exception creating article.") log.exception("Exception creating article.")
transaction.rollback()
if self.request.user.is_superuser: if self.request.user.is_superuser:
messages.error(self.request, _(u"There was an error creating this article: %s") % str(e)) messages.error(self.request, _(u"There was an error creating this article: %s") % str(e))
else: else:
......
...@@ -18,7 +18,7 @@ class ArticleMixin(TemplateResponseMixin): ...@@ -18,7 +18,7 @@ class ArticleMixin(TemplateResponseMixin):
articles__article__current_revision__deleted=False, articles__article__current_revision__deleted=False,
user_can_read=request.user): user_can_read=request.user):
self.children_slice.append(child) self.children_slice.append(child)
except AttributeError, e: except AttributeError as e:
raise Exception("Attribute error most likely caused by wrong MPTT version. Use 0.5.3+.\n\n" + str(e)) raise Exception("Attribute error most likely caused by wrong MPTT version. Use 0.5.3+.\n\n" + str(e))
return super(ArticleMixin, self).dispatch(request, *args, **kwargs) return super(ArticleMixin, self).dispatch(request, *args, **kwargs)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment