Permalink
Browse files

Merge pull request #12 from sergiocharpineljr/cleanup

Cleanup
  • Loading branch information...
2 parents 8a703b9 + edf5563 commit ae6d56a1150ba5f9fa0cb5a89fb97ce7736fd657 @bwinton bwinton committed Aug 20, 2012
View
@@ -1,21 +1,22 @@
# from http://code.djangoproject.com/wiki/AuditTrail
-from django.dispatch import dispatcher
-from django.db import models
-from django.core.exceptions import ImproperlyConfigured
-from django.contrib import admin
import copy
import re
-import types
+
+from django.contrib import admin
+from django.core.exceptions import ImproperlyConfigured
+from django.db import models
try:
import settings_audit
except ImportError:
settings_audit = None
+
value_error_re = re.compile("^.+'(.+)'$")
+
class AuditTrail(object):
- def __init__(self, show_in_admin=False, save_change_type=True, audit_deletes=True,
- track_fields=None):
+ def __init__(self, show_in_admin=False, save_change_type=True,
+ audit_deletes=True, track_fields=None):
self.opts = {}
self.opts['show_in_admin'] = show_in_admin
self.opts['save_change_type'] = save_change_type
@@ -38,7 +39,8 @@ def _contribute(sender, **kwargs):
# admin.site.register(cls, clsAdmin)
# Otherwise, register class with default ModelAdmin
admin.site.register(model)
- descriptor = AuditTrailDescriptor(model._default_manager, sender._meta.pk.attname)
+ descriptor = AuditTrailDescriptor(model._default_manager,
+ sender._meta.pk.attname)
setattr(sender, name, descriptor)
def _audit_track(instance, field_arr, **kwargs):
@@ -68,9 +70,6 @@ def _audit(sender, instance, created, **kwargs):
for field_arr in model._audit_track:
kwargs[field_arr[0]] = _audit_track(instance, field_arr)
model._default_manager.create(**kwargs)
- ## Uncomment this line for pre r8223 Django builds
- #dispatcher.connect(_audit, signal=models.signals.post_save, sender=cls, weak=False)
- ## Comment this line for pre r8223 Django builds
models.signals.post_save.connect(_audit, sender=cls, weak=False)
if self.opts['audit_deletes']:
@@ -82,32 +81,30 @@ def _audit_delete(sender, instance, **kwargs):
if self.opts['save_change_type']:
kwargs['_audit_change_type'] = 'D'
for field_arr in model._audit_track:
- kwargs[field_arr[0]] = _audit_track(instance, field_arr)
+ kwargs[field_arr[0]] = _audit_track(instance,
+ field_arr)
model._default_manager.create(**kwargs)
- ## Uncomment this line for pre r8223 Django builds
- #dispatcher.connect(_audit_delete, signal=models.signals.pre_delete, sender=cls, weak=False)
- ## Comment this line for pre r8223 Django builds
- models.signals.pre_delete.connect(_audit_delete, sender=cls, weak=False)
-
- ## Uncomment this line for pre r8223 Django builds
- #dispatcher.connect(_contribute, signal=models.signals.class_prepared, sender=cls, weak=False)
- ## Comment this line for pre r8223 Django builds
- models.signals.class_prepared.connect(_contribute, sender=cls, weak=False)
+ models.signals.pre_delete.connect(_audit_delete, sender=cls,
+ weak=False)
+ models.signals.class_prepared.connect(_contribute, sender=cls,
+ weak=False)
+
class AuditTrailDescriptor(object):
def __init__(self, manager, pk_attribute):
self.manager = manager
self.pk_attribute = pk_attribute
def __get__(self, instance=None, owner=None):
- if instance == None:
- #raise AttributeError, "Audit trail is only accessible via %s instances." % type.__name__
+ if instance is None:
return create_audit_manager_class(self.manager)
else:
- return create_audit_manager_with_pk(self.manager, self.pk_attribute, instance._get_pk_val())
+ return create_audit_manager_with_pk(self.manager,
+ self.pk_attribute, instance._get_pk_val())
def __set__(self, instance, value):
- raise AttributeError, "Audit trail may not be edited in this manner."
+ raise AttributeError("Audit trail may not be edited in this manner.")
+
def create_audit_manager_with_pk(manager, pk_attribute, pk):
"""Create an audit trail manager based on the current object"""
@@ -116,16 +113,19 @@ def __init__(self):
self.model = manager.model
def get_query_set(self):
- return super(AuditTrailWithPkManager, self).get_query_set().filter(**{pk_attribute: pk})
+ return super(AuditTrailWithPkManager, self).get_query_set().filter(
+ **{pk_attribute: pk})
return AuditTrailWithPkManager()
+
def create_audit_manager_class(manager):
"""Create an audit trail manager based on the current object"""
class AuditTrailManager(manager.__class__):
def __init__(self):
self.model = manager.model
return AuditTrailManager()
+
def create_audit_model(cls, **kwargs):
"""Create an audit model for the specific class"""
name = cls.__name__ + 'Audit'
@@ -140,10 +140,13 @@ class Meta:
'__module__': cls.__module__,
'Meta': Meta,
'_audit_id': models.AutoField(primary_key=True),
- '_audit_timestamp': models.DateTimeField(auto_now_add=True, db_index=True),
+ '_audit_timestamp': models.DateTimeField(auto_now_add=True,
+ db_index=True),
'_audit__str__': cls.__str__.im_func,
- '__str__': lambda self: '%s as of %s' % (self._audit__str__(), self._audit_timestamp),
- '_audit_track': _track_fields(track_fields=kwargs['track_fields'], unprocessed=True)
+ '__str__': lambda self: '%s as of %s' % (self._audit__str__(),
+ self._audit_timestamp),
+ '_audit_track': _track_fields(track_fields=kwargs['track_fields'],
+ unprocessed=True)
}
if 'save_change_type' in kwargs and kwargs['save_change_type']:
@@ -153,26 +156,31 @@ class Meta:
for field in cls._meta.fields:
#if field.attname in attrs:
if field.name in attrs:
- raise ImproperlyConfigured, "%s cannot use %s as it is needed by AuditTrail." % (cls.__name__, field.attname)
+ raise ImproperlyConfigured("%s cannot use %s as it is needed by "
+ "AuditTrail." % (cls.__name__,
+ field.attname))
if isinstance(field, models.AutoField):
# Audit models have a separate AutoField
- attrs[field.name] = models.IntegerField(db_index=True, editable=False)
+ attrs[field.name] = models.IntegerField(db_index=True,
+ editable=False)
else:
attrs[field.name] = copy.copy(field)
- # If 'unique' is in there, we need to remove it, otherwise the index
- # is created and multiple audit entries for one item fail.
+ # If 'unique' is in there, we need to remove it, otherwise the
+ # index is created and multiple audit entries for one item fail.
attrs[field.name]._unique = False
# If a model has primary_key = True, a second primary key would be
# created in the audit model. Set primary_key to false.
attrs[field.name].primary_key = False
for track_field in _track_fields(kwargs['track_fields']):
if track_field['name'] in attrs:
- raise NameError('Field named "%s" already exists in audit version of %s' % (track_field['name'], cls.__name__))
+ raise NameError('Field named "%s" already exists in audit version '
+ 'of %s' % (track_field['name'], cls.__name__))
attrs[track_field['name']] = copy.copy(track_field['field'])
-
+
return type(name, (models.Model,), attrs)
+
def _build_track_field(track_item):
track = {}
track['name'] = track_item[0]
@@ -181,26 +189,28 @@ def _build_track_field(track_item):
elif issubclass(track_item[1], models.Model):
track['field'] = models.ForeignKey(track_item[1])
else:
- raise TypeError('Track fields only support items that are Fields or Models.')
+ raise TypeError('Track fields only support items that are Fields or '
+ 'Models.')
return track
+
def _track_fields(track_fields=None, unprocessed=False):
# Add in the fields from the Audit class "track" attribute.
tracks_found = []
-
+
if settings_audit:
- global_track_fields = getattr(settings_audit, 'GLOBAL_TRACK_FIELDS', [])
+ global_track_fields = getattr(settings_audit, 'GLOBAL_TRACK_FIELDS',
+ [])
for track_item in global_track_fields:
if unprocessed:
tracks_found.append(track_item)
else:
tracks_found.append(_build_track_field(track_item))
-
+
if track_fields:
for track_item in track_fields:
if unprocessed:
tracks_found.append(track_item)
else:
tracks_found.append(_build_track_field(track_item))
return tracks_found
-
View
@@ -1,14 +1,17 @@
-from ispdb.config.models import Config, Domain, DomainRequest
from django.contrib import admin
+from ispdb.config.models import Config, Domain, DomainRequest
+
class DomainInline(admin.TabularInline):
model = Domain
extra = 0
+
class DomainRequestInline(admin.TabularInline):
model = DomainRequest
extra = 0
+
class ConfigAdmin(admin.ModelAdmin):
inlines = [
DomainRequestInline,
@@ -21,7 +24,7 @@ class ConfigAdmin(admin.ModelAdmin):
def change_view(self, request, obj_id):
c = self.model.objects.get(pk=obj_id)
if not c.domainrequests.all():
- self.inlines=[DomainInline,]
+ self.inlines = [DomainInline, ]
return super(ConfigAdmin, self).change_view(request, obj_id)
def list_domains(self, obj):
@@ -2,14 +2,12 @@
This file contains methods to do sanity checks on domains and configs
"""
-import re
-import os
-import socket
-import smtplib
+import dns.resolver
import imaplib
import poplib
+import re
+import smtplib
import ssl
-import dns.resolver
import tldextract
TIMEOUT = 10
@@ -104,7 +102,7 @@ def IMAP_starttls(self, keyfile=None, certfile=None, cert_reqs=ssl.CERT_NONE,
if name not in self.capabilities:
raise self.error("STARTTLS extension not supported by server.")
if hasattr(self, '_tls_established') and self._tls_established:
- raise error_proto('TLS session already established')
+ raise self.error('TLS session already established')
typ, dat = self._simple_command(name)
if typ == 'OK':
self.sock = ssl.wrap_socket(self.sock, keyfile, certfile,
@@ -361,14 +359,14 @@ def do_config_checks(config):
config.incoming_socket_type == 'STARTTLS'):
if check_socket_type(config.incoming_hostname,
config.incoming_type,
- 'SSL') != None:
+ 'SSL') is not None:
config_warnings.append("Incoming server '%s' supports SSL "
"using default port." %
(config.incoming_hostname))
elif config.incoming_socket_type == 'plain':
if check_socket_type(config.incoming_hostname,
config.incoming_type,
- 'STARTTLS') != None:
+ 'STARTTLS') is not None:
config_warnings.append("Incoming server '%s' supports "
"STARTTLS using default port." %
(config.incoming_hostname,))
@@ -377,7 +375,7 @@ def do_config_checks(config):
config.incoming_type,
config.incoming_socket_type,
port=config.incoming_port)
- if capa == None:
+ if capa is None:
config_errors.append("Incoming server '%s' does not support "
"socket type %s on port %s." %
(config.incoming_hostname,
@@ -407,14 +405,14 @@ def do_config_checks(config):
config.outgoing_socket_type == 'STARTTLS'):
if check_socket_type(config.outgoing_hostname,
'smtp',
- 'SSL') != None:
+ 'SSL') is not None:
config_warnings.append("Outgoing server '%s' supports SSL "
"using default port." %
(config.outgoing_hostname))
elif config.outgoing_socket_type == 'plain':
if check_socket_type(config.outgoing_hostname,
'smtp',
- 'STARTTLS') != None:
+ 'STARTTLS') is not None:
config_warnings.append("Outgoing server supports '%s' "
"STARTTLS using default port." %
(config.outgoing_hostname,))
@@ -423,7 +421,7 @@ def do_config_checks(config):
'smtp',
config.outgoing_socket_type,
port=config.outgoing_port)
- if capa == None:
+ if capa is None:
config_errors.append("Outgoing server '%s' does not support "
"socket type %s on port %s." %
(config.outgoing_hostname,
Oops, something went wrong.

0 comments on commit ae6d56a

Please sign in to comment.