Skip to content

Commit 318e48d

Browse files
committed
Appease the isort gods
1 parent f2087ff commit 318e48d

File tree

4 files changed

+44
-48
lines changed

4 files changed

+44
-48
lines changed

cspreports/models.py

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,37 @@
11
# STANDARD LIB
22
import json
33

4+
# Third party
5+
from django.apps import apps
46
from django.core.exceptions import ValidationError, ImproperlyConfigured
57
from django.db import models
68
from django.utils.html import escape
79
from django.utils.safestring import mark_safe
8-
from django.apps import apps
910

11+
# CSP Reports
1012
from cspreports.conf import app_settings
1113

1214
DISPOSITIONS = (
13-
('enforce', 'enforce'),
14-
('report', 'report'),
15+
("enforce", "enforce"),
16+
("report", "report"),
1517
)
1618

1719
# Map of required CSP report fields to model fields
1820
REQUIRED_FIELDS = (
19-
('document-uri', 'document_uri'),
20-
('referrer', 'referrer'),
21-
('blocked-uri', 'blocked_uri'),
22-
('violated-directive', 'violated_directive'),
23-
('original-policy', 'original_policy'),
21+
("document-uri", "document_uri"),
22+
("referrer", "referrer"),
23+
("blocked-uri", "blocked_uri"),
24+
("violated-directive", "violated_directive"),
25+
("original-policy", "original_policy"),
2426
)
2527
# Map of optional (CSP >= 2.0) CSP report fields to model fields
2628
OPTIONAL_FIELDS = (
27-
('disposition', 'disposition'),
28-
('effective-directive', 'effective_directive'),
29-
('source-file', 'source_file'),
30-
('status-code', 'status_code'),
31-
('line-number', 'line_number'),
32-
('column-number', 'column_number'),
29+
("disposition", "disposition"),
30+
("effective-directive", "effective_directive"),
31+
("source-file", "source_file"),
32+
("status-code", "status_code"),
33+
("line-number", "line_number"),
34+
("column-number", "column_number"),
3335
)
3436

3537

@@ -63,7 +65,7 @@ class CSPReportBase(models.Model):
6365
"""
6466

6567
class Meta:
66-
ordering = ('-created',)
68+
ordering = ("-created",)
6769
abstract = True
6870

6971
created = models.DateTimeField(auto_now_add=True)
@@ -88,14 +90,14 @@ class Meta:
8890
def nice_report(self):
8991
"""Return a nicely formatted original report."""
9092
if not self.json:
91-
return '[no CSP report data]'
93+
return "[no CSP report data]"
9294
try:
9395
data = json.loads(self.json)
9496
except ValueError:
9597
return "Invalid CSP report: '{}'".format(self.json)
96-
if 'csp-report' not in data:
97-
return 'Invalid CSP report: ' + json.dumps(data, indent=4, sort_keys=True, separators=(',', ': '))
98-
return json.dumps(data['csp-report'], indent=4, sort_keys=True, separators=(',', ': '))
98+
if "csp-report" not in data:
99+
return "Invalid CSP report: " + json.dumps(data, indent=4, sort_keys=True, separators=(",", ": "))
100+
return json.dumps(data["csp-report"], indent=4, sort_keys=True, separators=(",", ": "))
99101

100102
def __str__(self):
101103
return self.nice_report
@@ -116,7 +118,7 @@ def from_message(cls, message):
116118
# Message is not a valid JSON. Return as invalid.
117119
return self
118120
try:
119-
report_data = decoded_data['csp-report']
121+
report_data = decoded_data["csp-report"]
120122
except KeyError:
121123
# Message is not a valid CSP report. Return as invalid.
122124
return self
@@ -159,15 +161,15 @@ def from_message(cls, message):
159161

160162
@property
161163
def data(self):
162-
""" Returns self.json loaded as a python object. """
164+
"""Returns self.json loaded as a python object."""
163165
try:
164166
data = self._data
165167
except AttributeError:
166168
data = self._data = json.loads(self.json)
167169
return data
168170

169171
def json_as_html(self):
170-
""" Print out self.json in a nice way. """
172+
"""Print out self.json in a nice way."""
171173

172174
# To avoid circular import
173175
from cspreports import utils
@@ -185,11 +187,6 @@ def get_report_model():
185187
try:
186188
return apps.get_model(model_string, require_ready=False)
187189
except ValueError:
188-
raise ImproperlyConfigured(
189-
"CSP_REPORTS_MODEL must be of the form 'app_label.model_name'"
190-
)
190+
raise ImproperlyConfigured("CSP_REPORTS_MODEL must be of the form 'app_label.model_name'")
191191
except LookupError:
192-
raise ImproperlyConfigured(
193-
"CSP_REPORTS_MODEL refers to model '%s' that has not been installed"
194-
% model_string
195-
)
192+
raise ImproperlyConfigured("CSP_REPORTS_MODEL refers to model '%s' that has not been installed" % model_string)

cspreports/summary.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,20 @@
11
"""Collect summary of CSP reports."""
2+
23
from operator import attrgetter
34
from urllib.parse import urlsplit, urlunsplit
45

56
from django.template.loader import get_template
67

78
from cspreports.models import get_report_model
89

9-
1010
CSPReport = get_report_model()
1111
DEFAULT_TOP = 10
1212

1313

1414
def get_root_uri(uri):
1515
"""Return root URI - strip query and fragment."""
1616
chunks = urlsplit(uri)
17-
return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, '', ''))
17+
return urlunsplit((chunks.scheme, chunks.netloc, chunks.path, "", ""))
1818

1919

2020
class ViolationInfo:
@@ -72,7 +72,7 @@ def __init__(self, since, to, top=DEFAULT_TOP):
7272

7373
def render(self):
7474
"""Render the summary."""
75-
template = get_template('cspreports/summary.txt')
75+
template = get_template("cspreports/summary.txt")
7676
return template.render(self.__dict__)
7777

7878

@@ -95,15 +95,15 @@ def collect(since, to, top=DEFAULT_TOP):
9595
root_uri = get_root_uri(report.document_uri)
9696
info = sources.setdefault(root_uri, ViolationInfo(root_uri))
9797
info.append(report)
98-
summary.sources = sorted(sources.values(), key=attrgetter('count'), reverse=True)[:top]
98+
summary.sources = sorted(sources.values(), key=attrgetter("count"), reverse=True)[:top]
9999

100100
# Collect blocks
101101
blocks = {}
102102
for report in valid_queryset:
103103
root_uri = get_root_uri(report.blocked_uri)
104104
info = blocks.setdefault(root_uri, ViolationInfo(root_uri))
105105
info.append(report)
106-
summary.blocks = sorted(blocks.values(), key=attrgetter('count'), reverse=True)[:top]
106+
summary.blocks = sorted(blocks.values(), key=attrgetter("count"), reverse=True)[:top]
107107

108108
# Collect invalid reports
109109
summary.invalid_count = invalid_queryset.count()

cspreports/tests/test_custom_model.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,9 @@
11
from django.conf import settings
22
from django.core.exceptions import ImproperlyConfigured
33
from django.test import TestCase, override_settings
4-
from django.test.signals import setting_changed
54

6-
from cspreports.models import get_report_model
75
from cspreports.conf import app_settings
6+
from cspreports.models import get_report_model
87
from cspreports.tests.models import CustomCSPReport
98

109

cspreports/utils.py

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,16 @@
88
from django.utils.dateparse import parse_date
99
from django.utils.timezone import localtime, make_aware, now
1010

11-
from cspreports.models import get_report_model
1211
from cspreports.conf import app_settings
12+
from cspreports.models import get_report_model
1313

1414
CSPReport = get_report_model()
1515

1616
logger = logging.getLogger(app_settings.LOGGER_NAME)
1717

1818

1919
def process_report(request):
20-
""" Given the HTTP request of a CSP violation report, log it in the required ways. """
20+
"""Given the HTTP request of a CSP violation report, log it in the required ways."""
2121
if not should_process_report(request):
2222
return
2323
if app_settings.EMAIL_ADMINS:
@@ -31,21 +31,21 @@ def process_report(request):
3131

3232

3333
def format_report(jsn):
34-
""" Given a JSON report, return a nicely formatted (i.e. with indentation) string.
35-
This should handle invalid JSON (as the JSON comes from the browser/user).
36-
We trust that Python's json library is secure, but if the JSON is invalid then we still
37-
want to be able to display it, rather than tripping up on a ValueError.
34+
"""Given a JSON report, return a nicely formatted (i.e. with indentation) string.
35+
This should handle invalid JSON (as the JSON comes from the browser/user).
36+
We trust that Python's json library is secure, but if the JSON is invalid then we still
37+
want to be able to display it, rather than tripping up on a ValueError.
3838
"""
3939
if isinstance(jsn, bytes):
40-
jsn = jsn.decode('utf-8')
40+
jsn = jsn.decode("utf-8")
4141
try:
42-
return json.dumps(json.loads(jsn), indent=4, sort_keys=True, separators=(',', ': '))
42+
return json.dumps(json.loads(jsn), indent=4, sort_keys=True, separators=(",", ": "))
4343
except ValueError:
4444
return "Invalid JSON. Raw dump is below.\n\n" + jsn
4545

4646

4747
def email_admins(request):
48-
user_agent = request.META.get('HTTP_USER_AGENT', '')
48+
user_agent = request.META.get("HTTP_USER_AGENT", "")
4949
report = format_report(request.body)
5050
message = "User agent:\n%s\n\nReport:\n%s" % (user_agent, report)
5151
mail_admins("CSP Violation Report", message)
@@ -62,7 +62,7 @@ def save_report(request):
6262
message = message.decode(request.encoding or settings.DEFAULT_CHARSET)
6363

6464
report = CSPReport.from_message(message)
65-
report.user_agent = request.META.get('HTTP_USER_AGENT', '')
65+
report.user_agent = request.META.get("HTTP_USER_AGENT", "")
6666
report.save()
6767

6868

@@ -76,7 +76,7 @@ def run_additional_handlers(request):
7676

7777

7878
def get_additional_handlers():
79-
""" Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS. """
79+
"""Returns the actual functions from the dotted paths specified in ADDITIONAL_HANDLERS."""
8080
global _additional_handlers
8181
if not isinstance(_additional_handlers, list):
8282
handlers = []
@@ -119,7 +119,7 @@ def get_midnight():
119119

120120

121121
def import_from_dotted_path(name):
122-
module_name, function_name = name.rsplit('.', 1)
122+
module_name, function_name = name.rsplit(".", 1)
123123
return getattr(import_module(module_name), function_name)
124124

125125

0 commit comments

Comments
 (0)