Skip to content

Commit

Permalink
Bring codebase up to modern Python using pyupgrade (#213)
Browse files Browse the repository at this point in the history
* Drop empty test_settings.py file

Was emptied out back in e5dc7f6

* Remove redundant imports - via pyupgrade

* Update dictionary-comprehension syntax - via pyupgrade

* Update set() syntax - via pyupgrade

* Update string formatting to f-strings - via pyupgrade

* Update string formatting (but not to f-strings) - via pyupgrade

* Drop redundant encoding comment - via pyupgrade

* Update class def/inheritance - via pyupgrade

* Update changelog
  • Loading branch information
stevejalim authored Jan 29, 2024
1 parent 9698258 commit 371da46
Show file tree
Hide file tree
Showing 11 changed files with 16 additions and 24 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ Next
Unreleased
==========

- Update Python syntax for modern versions with pyupgrade
- Drop support for EOL Python <3.8 and Django <2.2 versions
- Switch to ruff instead of pep8 and flake8
- Move from CircleCI to Github Actions for CI
Expand Down
6 changes: 3 additions & 3 deletions csp/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def _wrapped(*a, **kw):


def csp_update(**kwargs):
update = dict((k.lower().replace("_", "-"), v) for k, v in kwargs.items())
update = {k.lower().replace("_", "-"): v for k, v in kwargs.items()}

def decorator(f):
@wraps(f)
Expand All @@ -27,7 +27,7 @@ def _wrapped(*a, **kw):


def csp_replace(**kwargs):
replace = dict((k.lower().replace("_", "-"), v) for k, v in kwargs.items())
replace = {k.lower().replace("_", "-"): v for k, v in kwargs.items()}

def decorator(f):
@wraps(f)
Expand All @@ -42,7 +42,7 @@ def _wrapped(*a, **kw):


def csp(**kwargs):
config = dict((k.lower().replace("_", "-"), [v] if isinstance(v, str) else v) for k, v in kwargs.items())
config = {k.lower().replace("_", "-"): [v] if isinstance(v, str) else v for k, v in kwargs.items()}

def decorator(f):
@wraps(f)
Expand Down
4 changes: 1 addition & 3 deletions csp/extensions/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

from jinja2 import nodes
from jinja2.ext import Extension

Expand All @@ -8,7 +6,7 @@

class NoncedScript(Extension):
# a set of names that trigger the extension.
tags = set(["script"])
tags = {"script"}

def parse(self, parser):
# the first token is the token that started the tag. In our case
Expand Down
2 changes: 0 additions & 2 deletions csp/middleware.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

import base64
import http.client as http_client
import os
Expand Down
2 changes: 0 additions & 2 deletions csp/templatetags/csp.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

from django import template
from django.template.base import token_kwargs

Expand Down
2 changes: 0 additions & 2 deletions csp/tests/test_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import absolute_import

from django.conf import settings
from django.test.utils import override_settings
from django.utils.functional import lazy
Expand Down
4 changes: 2 additions & 2 deletions csp/tests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@ def get_response(req):
rf = RequestFactory()


class ScriptTestBase(object):
class ScriptTestBase:
def assert_template_eq(self, tpl1, tpl2):
aaa = tpl1.replace("\n", "").replace(" ", "")
bbb = tpl2.replace("\n", "").replace(" ", "")
assert aaa == bbb, "{} != {}".format(aaa, bbb)
assert aaa == bbb, f"{aaa} != {bbb}"

def process_templates(self, tpl, expected):
request = rf.get("/")
Expand Down
16 changes: 8 additions & 8 deletions csp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,14 +99,14 @@ def build_policy(config=None, update=None, replace=None, nonce=None):
include_nonce_in = getattr(settings, "CSP_INCLUDE_NONCE_IN", ["default-src"])
for section in include_nonce_in:
policy = policy_parts.get(section, "")
policy_parts[section] = ("%s %s" % (policy, "'nonce-%s'" % nonce)).strip()
policy_parts[section] = ("{} {}".format(policy, "'nonce-%s'" % nonce)).strip()

return "; ".join(["{} {}".format(k, val).strip() for k, val in policy_parts.items()])
return "; ".join([f"{k} {val}".strip() for k, val in policy_parts.items()])


def _default_attr_mapper(attr_name, val):
if val:
return ' {}="{}"'.format(attr_name, val)
return f' {attr_name}="{val}"'
else:
return ""

Expand All @@ -115,7 +115,7 @@ def _bool_attr_mapper(attr_name, val):
# Only return the bare word if the value is truthy
# ie - defer=False should actually return an empty string
if val:
return " {}".format(attr_name)
return f" {attr_name}"
else:
return ""

Expand All @@ -125,9 +125,9 @@ def _async_attr_mapper(attr_name, val):
attributes. It can be set explicitly to `false` with no surrounding quotes
according to the spec."""
if val in [False, "False"]:
return " {}=false".format(attr_name)
return f" {attr_name}=false"
elif val:
return " {}".format(attr_name)
return f" {attr_name}"
else:
return ""

Expand All @@ -144,7 +144,7 @@ def _async_attr_mapper(attr_name, val):
SCRIPT_ATTRS["nomodule"] = _bool_attr_mapper

# Generates an interpolatable string of valid attrs eg - '{nonce}{id}...'
ATTR_FORMAT_STR = "".join(["{{{}}}".format(a) for a in SCRIPT_ATTRS])
ATTR_FORMAT_STR = "".join([f"{{{a}}}" for a in SCRIPT_ATTRS])


_script_tag_contents_re = re.compile(
Expand Down Expand Up @@ -176,4 +176,4 @@ def build_script_tag(content=None, **kwargs):
# Don't render block contents if the script has a 'src' attribute
c = _unwrap_script(content) if content and not kwargs.get("src") else ""
attrs = ATTR_FORMAT_STR.format(**data).rstrip()
return "<script{}>{}</script>".format(attrs, c).strip()
return f"<script{attrs}>{c}</script>".strip()
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# Django-CSP documentation build configuration file, created by
# sphinx-quickstart on Wed Oct 31 13:02:27 2012.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
os.system("python setup.py sdist upload")
os.system("python setup.py bdist_wheel upload")
print("You probably want to also tag the version now:")
print(' git tag -a %s -m "version %s"' % (version, version))
print(f' git tag -a {version} -m "version {version}"')
print(" git push --tags")
sys.exit()

Expand Down
Empty file removed test_settings.py
Empty file.

0 comments on commit 371da46

Please sign in to comment.