Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Applied isort and black to project #180

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 36 additions & 36 deletions analytical/templatetags/analytical.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,45 +3,44 @@
"""

import logging
from importlib import import_module

from django import template
from django.template import Node, TemplateSyntaxError
from importlib import import_module

from analytical.utils import AnalyticalException


TAG_LOCATIONS = ['head_top', 'head_bottom', 'body_top', 'body_bottom']
TAG_POSITIONS = ['first', None, 'last']
TAG_LOCATIONS = ["head_top", "head_bottom", "body_top", "body_bottom"]
TAG_POSITIONS = ["first", None, "last"]
TAG_MODULES = [
'analytical.chartbeat',
'analytical.clickmap',
'analytical.clicky',
'analytical.crazy_egg',
'analytical.facebook_pixel',
'analytical.gauges',
'analytical.google_analytics',
'analytical.google_analytics_js',
'analytical.google_analytics_gtag',
'analytical.gosquared',
'analytical.hotjar',
'analytical.hubspot',
'analytical.intercom',
'analytical.kiss_insights',
'analytical.kiss_metrics',
'analytical.luckyorange',
'analytical.matomo',
'analytical.mixpanel',
'analytical.olark',
'analytical.optimizely',
'analytical.performable',
'analytical.piwik',
'analytical.rating_mailru',
'analytical.snapengage',
'analytical.spring_metrics',
'analytical.uservoice',
'analytical.woopra',
'analytical.yandex_metrica',
"analytical.chartbeat",
"analytical.clickmap",
"analytical.clicky",
"analytical.crazy_egg",
"analytical.facebook_pixel",
"analytical.gauges",
"analytical.google_analytics",
"analytical.google_analytics_js",
"analytical.google_analytics_gtag",
"analytical.gosquared",
"analytical.hotjar",
"analytical.hubspot",
"analytical.intercom",
"analytical.kiss_insights",
"analytical.kiss_metrics",
"analytical.luckyorange",
"analytical.matomo",
"analytical.mixpanel",
"analytical.olark",
"analytical.optimizely",
"analytical.performable",
"analytical.piwik",
"analytical.rating_mailru",
"analytical.snapengage",
"analytical.spring_metrics",
"analytical.uservoice",
"analytical.woopra",
"analytical.yandex_metrica",
]

logger = logging.getLogger(__name__)
Expand All @@ -59,7 +58,7 @@ def analytical_tag(parser, token):


for loc in TAG_LOCATIONS:
register.tag('analytical_%s' % loc, _location_tag(loc))
register.tag("analytical_%s" % loc, _location_tag(loc))


class AnalyticalNode(Node):
Expand All @@ -83,13 +82,14 @@ def add_node_cls(location, node, position=None):
except AnalyticalException as e:
logger.debug("not loading tags from '%s': %s", path, e)
for location in TAG_LOCATIONS:
template_nodes[location] = sum((template_nodes[location][p]
for p in TAG_POSITIONS), [])
template_nodes[location] = sum(
(template_nodes[location][p] for p in TAG_POSITIONS), []
)
return template_nodes


def _import_tag_module(path):
app_name, lib_name = path.rsplit('.', 1)
app_name, lib_name = path.rsplit(".", 1)
return import_module("%s.templatetags.%s" % (app_name, lib_name))


Expand Down
35 changes: 19 additions & 16 deletions analytical/templatetags/chartbeat.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
from django.core.exceptions import ImproperlyConfigured
from django.template import Library, Node, TemplateSyntaxError

from analytical.utils import is_internal_ip, disable_html, get_required_setting
from analytical.utils import disable_html, get_required_setting, is_internal_ip


USER_ID_RE = re.compile(r'^\d+$')
INIT_CODE = """<script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script>"""
USER_ID_RE = re.compile(r"^\d+$")
INIT_CODE = (
'<script type="text/javascript">var _sf_startpt=(new Date()).getTime()</script>'
)
SETUP_CODE = """
<script type="text/javascript">
var _sf_async_config=%(config)s;
Expand All @@ -34,7 +35,7 @@
})();
</script>
""" # noqa
DOMAIN_CONTEXT_KEY = 'chartbeat_domain'
DOMAIN_CONTEXT_KEY = "chartbeat_domain"


register = Library()
Expand Down Expand Up @@ -77,24 +78,25 @@ def chartbeat_bottom(parser, token):

class ChartbeatBottomNode(Node):
def __init__(self):
self.user_id = get_required_setting('CHARTBEAT_USER_ID', USER_ID_RE,
"must be (a string containing) a number")
self.user_id = get_required_setting(
"CHARTBEAT_USER_ID", USER_ID_RE, "must be (a string containing) a number"
)

def render(self, context):
config = {'uid': self.user_id}
config = {"uid": self.user_id}
domain = _get_domain(context)
if domain is not None:
config['domain'] = domain
html = SETUP_CODE % {'config': json.dumps(config, sort_keys=True)}
if is_internal_ip(context, 'CHARTBEAT'):
html = disable_html(html, 'Chartbeat')
config["domain"] = domain
html = SETUP_CODE % {"config": json.dumps(config, sort_keys=True)}
if is_internal_ip(context, "CHARTBEAT"):
html = disable_html(html, "Chartbeat")
return html


def contribute_to_analytical(add_node):
ChartbeatBottomNode() # ensure properly configured
add_node('head_top', ChartbeatTopNode, 'first')
add_node('body_bottom', ChartbeatBottomNode, 'last')
add_node("head_top", ChartbeatTopNode, "first")
add_node("body_bottom", ChartbeatBottomNode, "last")


def _get_domain(context):
Expand All @@ -103,10 +105,11 @@ def _get_domain(context):
if domain is not None:
return domain
else:
if 'django.contrib.sites' not in settings.INSTALLED_APPS:
if "django.contrib.sites" not in settings.INSTALLED_APPS:
return
elif getattr(settings, 'CHARTBEAT_AUTO_DOMAIN', True):
elif getattr(settings, "CHARTBEAT_AUTO_DOMAIN", True):
from django.contrib.sites.models import Site

try:
return Site.objects.get_current().domain
except (ImproperlyConfigured, Site.DoesNotExist): # pylint: disable=E1101
Expand Down
21 changes: 11 additions & 10 deletions analytical/templatetags/clickmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@

from django.template import Library, Node, TemplateSyntaxError

from analytical.utils import is_internal_ip, disable_html, get_required_setting
from analytical.utils import disable_html, get_required_setting, is_internal_ip


CLICKMAP_TRACKER_ID_RE = re.compile(r'^\w+$')
CLICKMAP_TRACKER_ID_RE = re.compile(r"^\w+$")
TRACKING_CODE = """
<script type="text/javascript">
var clickmapConfig = {tracker: '%(tracker_id)s', version:'2'};
Expand Down Expand Up @@ -43,17 +42,19 @@ def clickmap(parser, token):

class ClickmapNode(Node):
def __init__(self):
self.tracker_id = get_required_setting('CLICKMAP_TRACKER_ID',
CLICKMAP_TRACKER_ID_RE,
"must be an alphanumeric string")
self.tracker_id = get_required_setting(
"CLICKMAP_TRACKER_ID",
CLICKMAP_TRACKER_ID_RE,
"must be an alphanumeric string",
)

def render(self, context):
html = TRACKING_CODE % {'tracker_id': self.tracker_id}
if is_internal_ip(context, 'CLICKMAP'):
html = disable_html(html, 'Clickmap')
html = TRACKING_CODE % {"tracker_id": self.tracker_id}
if is_internal_ip(context, "CLICKMAP"):
html = disable_html(html, "Clickmap")
return html


def contribute_to_analytical(add_node):
ClickmapNode() # ensure properly configured
add_node('body_bottom', ClickmapNode)
add_node("body_bottom", ClickmapNode)
33 changes: 18 additions & 15 deletions analytical/templatetags/clicky.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,14 @@

from django.template import Library, Node, TemplateSyntaxError

from analytical.utils import get_identity, is_internal_ip, disable_html, \
get_required_setting
from analytical.utils import (
disable_html,
get_identity,
get_required_setting,
is_internal_ip,
)


SITE_ID_RE = re.compile(r'^\d+$')
SITE_ID_RE = re.compile(r"^\d+$")
TRACKING_CODE = """
<script type="text/javascript">
var clicky = { log: function(){ return; }, goal: function(){ return; }};
Expand Down Expand Up @@ -50,29 +53,29 @@ def clicky(parser, token):
class ClickyNode(Node):
def __init__(self):
self.site_id = get_required_setting(
'CLICKY_SITE_ID', SITE_ID_RE,
"must be a (string containing) a number")
"CLICKY_SITE_ID", SITE_ID_RE, "must be a (string containing) a number"
)

def render(self, context):
custom = {}
for dict_ in context:
for var, val in dict_.items():
if var.startswith('clicky_'):
if var.startswith("clicky_"):
custom[var[7:]] = val
if 'username' not in custom.get('session', {}):
identity = get_identity(context, 'clicky')
if "username" not in custom.get("session", {}):
identity = get_identity(context, "clicky")
if identity is not None:
custom.setdefault('session', {})['username'] = identity
custom.setdefault("session", {})["username"] = identity

html = TRACKING_CODE % {
'site_id': self.site_id,
'custom': json.dumps(custom, sort_keys=True),
"site_id": self.site_id,
"custom": json.dumps(custom, sort_keys=True),
}
if is_internal_ip(context, 'CLICKY'):
html = disable_html(html, 'Clicky')
if is_internal_ip(context, "CLICKY"):
html = disable_html(html, "Clicky")
return html


def contribute_to_analytical(add_node):
ClickyNode() # ensure properly configured
add_node('body_bottom', ClickyNode)
add_node("body_bottom", ClickyNode)
46 changes: 25 additions & 21 deletions analytical/templatetags/crazy_egg.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@

from django.template import Library, Node, TemplateSyntaxError

from analytical.utils import is_internal_ip, disable_html, get_required_setting
from analytical.utils import disable_html, get_required_setting, is_internal_ip


ACCOUNT_NUMBER_RE = re.compile(r'^\d+$')
SETUP_CODE = '<script type="text/javascript" src="{placeholder_url}">' \
'</script>'.\
format(placeholder_url='//dnn506yrbagrg.cloudfront.net/pages/scripts/'
'%(account_nr_1)s/%(account_nr_2)s.js')
ACCOUNT_NUMBER_RE = re.compile(r"^\d+$")
SETUP_CODE = (
'<script type="text/javascript" '
'src="//dnn506yrbagrg.cloudfront.net/pages/scripts/%(account_nr_1)s/%(account_nr_2)s.js">'
"</script>"
)
USERVAR_CODE = "CE2.set(%(varnr)d, '%(value)s');"


Expand All @@ -38,29 +38,33 @@ def crazy_egg(parser, token):
class CrazyEggNode(Node):
def __init__(self):
self.account_nr = get_required_setting(
'CRAZY_EGG_ACCOUNT_NUMBER',
ACCOUNT_NUMBER_RE, "must be (a string containing) a number"
"CRAZY_EGG_ACCOUNT_NUMBER",
ACCOUNT_NUMBER_RE,
"must be (a string containing) a number",
)

def render(self, context):
html = SETUP_CODE % {
'account_nr_1': self.account_nr[:4],
'account_nr_2': self.account_nr[4:],
"account_nr_1": self.account_nr[:4],
"account_nr_2": self.account_nr[4:],
}
values = (context.get('crazy_egg_var%d' % i) for i in range(1, 6))
values = (context.get("crazy_egg_var%d" % i) for i in range(1, 6))
params = [(i, v) for i, v in enumerate(values, 1) if v is not None]
if params:
js = " ".join(USERVAR_CODE % {
'varnr': varnr,
'value': value,
} for (varnr, value) in params)
html = '%s\n' \
'<script type="text/javascript">%s</script>' % (html, js)
if is_internal_ip(context, 'CRAZY_EGG'):
html = disable_html(html, 'Crazy Egg')
js = " ".join(
USERVAR_CODE
% {
"varnr": varnr,
"value": value,
}
for (varnr, value) in params
)
html = "%s\n" '<script type="text/javascript">%s</script>' % (html, js)
if is_internal_ip(context, "CRAZY_EGG"):
html = disable_html(html, "Crazy Egg")
return html


def contribute_to_analytical(add_node):
CrazyEggNode() # ensure properly configured
add_node('body_bottom', CrazyEggNode)
add_node("body_bottom", CrazyEggNode)
18 changes: 9 additions & 9 deletions analytical/templatetags/facebook_pixel.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@

from django.template import Library, Node, TemplateSyntaxError

from analytical.utils import get_required_setting, is_internal_ip, disable_html

from analytical.utils import disable_html, get_required_setting, is_internal_ip

FACEBOOK_PIXEL_HEAD_CODE = """\
<script>
Expand Down Expand Up @@ -61,17 +60,18 @@ class _FacebookPixelNode(Node):
"""
Base class: override and provide code_template.
"""

def __init__(self):
self.pixel_id = get_required_setting(
'FACEBOOK_PIXEL_ID',
re.compile(r'^\d+$'),
"FACEBOOK_PIXEL_ID",
re.compile(r"^\d+$"),
"must be (a string containing) a number",
)

def render(self, context):
html = self.code_template % {'FACEBOOK_PIXEL_ID': self.pixel_id}
if is_internal_ip(context, 'FACEBOOK_PIXEL'):
return disable_html(html, 'Facebook Pixel')
html = self.code_template % {"FACEBOOK_PIXEL_ID": self.pixel_id}
if is_internal_ip(context, "FACEBOOK_PIXEL"):
return disable_html(html, "Facebook Pixel")
else:
return html

Expand All @@ -92,5 +92,5 @@ def contribute_to_analytical(add_node):
# ensure properly configured
FacebookPixelHeadNode()
FacebookPixelBodyNode()
add_node('head_bottom', FacebookPixelHeadNode)
add_node('body_bottom', FacebookPixelBodyNode)
add_node("head_bottom", FacebookPixelHeadNode)
add_node("body_bottom", FacebookPixelBodyNode)
Loading