Commit 47a7944c authored by fred's avatar fred

trivial: apply black

parent 72e06b73
from django.conf import settings
def panikweb(request):
return {
'site_url': request.build_absolute_uri('/').strip('/'),
......
import re
class StripPiwikCookieMiddleware(object):
# idea from http://djangosnippets.org/snippets/1772/
strip_re = re.compile(r'(_pk_[a-z0-9\.]+=.+?(?:; |$))')
def process_request(self, request):
try:
cookie = self.strip_re.sub('', request.META['HTTP_COOKIE'])
......
......@@ -23,10 +23,12 @@ from panikweb import search
register = template.Library()
@register.filter(name='zip')
def zip_lists(a, b):
return zip(a, b)
@register.inclusion_tag('includes/audio.html', takes_context=True)
def audio(context, sound=None, embed=False, display_fragment_name=False):
return {
......@@ -36,6 +38,7 @@ def audio(context, sound=None, embed=False, display_fragment_name=False):
'embed': embed,
}
@register.inclusion_tag('listen/nav.html', takes_context=True)
def listen_nav(context, date=None, klass=None):
return {
......@@ -43,6 +46,7 @@ def listen_nav(context, date=None, klass=None):
'categories': context.get('categories'),
}
@register.inclusion_tag('news/nav.html', takes_context=True)
def news_nav(context, date=None, klass=None):
return {
......@@ -53,6 +57,7 @@ def news_nav(context, date=None, klass=None):
'search_query': context.get('search_query'),
}
@register.inclusion_tag('emissions/nav.html', takes_context=True)
def emission_nav(context, date=None, klass=None):
return {
......@@ -64,6 +69,7 @@ def emission_nav(context, date=None, klass=None):
'search_query': context.get('search_query'),
}
@register.inclusion_tag('episodes/inline.html', takes_context=True)
def episode_inline(context, date=None, model=None, klass=None):
return {
......@@ -71,6 +77,8 @@ def episode_inline(context, date=None, model=None, klass=None):
'episode': context.get('episode'),
'date': date,
}
@register.inclusion_tag('episodes/resume.html', takes_context=True)
def episode_resume(context, date=None, model=None, klass=None):
return {
......@@ -80,10 +88,12 @@ def episode_resume(context, date=None, model=None, klass=None):
'date': date,
}
@register.inclusion_tag('episodes/detail.html', takes_context=True)
def episode_detail(context, date=None):
soundfiles = SoundFile.objects.select_related().filter(
fragment=True, podcastable=True, episode=context.get('episode'))
fragment=True, podcastable=True, episode=context.get('episode')
)
return {
'episode': context.get('episode'),
'emission': context.get('emission'),
......@@ -93,6 +103,7 @@ def episode_detail(context, date=None):
'topik_pages': context.get('topik_pages'),
}
@register.inclusion_tag('emissions/detail.html', takes_context=True)
def emission_detail(context, date=None):
return {
......@@ -100,6 +111,7 @@ def emission_detail(context, date=None):
'schedules': context.get('schedules'),
}
@register.inclusion_tag('emissions/resume.html', takes_context=True)
def emission_resume(context, date=None):
return {
......@@ -107,6 +119,7 @@ def emission_resume(context, date=None):
'schedules': context.get('schedules'),
}
@register.inclusion_tag('emissions/inline.html', takes_context=True)
def emission_inline(context, date=None):
return {
......@@ -114,10 +127,11 @@ def emission_inline(context, date=None):
'schedules': context.get('schedules'),
}
@register.inclusion_tag('soundfiles/resume.html')
def soundfile_resume(soundfile, date=None):
return {'soundfile': soundfile,
'date': date}
return {'soundfile': soundfile, 'date': date}
@register.inclusion_tag('includes/player.html', takes_context=True)
def player(context):
......@@ -127,6 +141,7 @@ def player(context):
'soundfiles': context.get('soundfiles'),
}
@register.inclusion_tag('includes/metaNav.html', takes_context=True)
def metanav(context):
try:
......@@ -167,11 +182,15 @@ def weekview(year=None, week=None):
date = utils.tofirstdayinisoweek(year, week)
date = datetime(*date.timetuple()[:3])
program = period_program(date, date+timedelta(days=7))
program = period_program(date, date + timedelta(days=7))
days = []
for day in range(7):
days.append({'cells': [x for x in program if x.is_on_weekday(day+1)],
'datetime': date+timedelta(days=day)})
days.append(
{
'cells': [x for x in program if x.is_on_weekday(day + 1)],
'datetime': date + timedelta(days=day),
}
)
return {
'days': days,
......@@ -179,6 +198,7 @@ def weekview(year=None, week=None):
'year': year,
}
@register.inclusion_tag('includes/week-nav.html')
def weeknav(year=None, week=None, weekday=None):
year = year if year else datetime.today().isocalendar()[0]
......@@ -190,7 +210,7 @@ def weeknav(year=None, week=None, weekday=None):
days = []
for day in range(7):
days.append({'datetime': date+timedelta(days=day)})
days.append({'datetime': date + timedelta(days=day)})
previous_week = date - timedelta(days=7)
previous_week_year, previous_week_no = previous_week.isocalendar()[:2]
......@@ -212,17 +232,15 @@ def weeknav(year=None, week=None, weekday=None):
@register.inclusion_tag('news/inline.html', takes_context=True)
def news_inline(context, klass=None, logo=None):
return {
'content': context.get('content'),
'class': klass,
'logo': logo
}
return {'content': context.get('content'), 'class': klass, 'logo': logo}
@register.inclusion_tag('news/roll.html')
def newsroll():
return {
'news': Focus.objects.filter(current=True).select_related('emission', 'newsitem',
'soundfile', 'episode', 'newsitem__category').order_by('?')[:3]
'news': Focus.objects.filter(current=True)
.select_related('emission', 'newsitem', 'soundfile', 'episode', 'newsitem__category')
.order_by('?')[:3]
}
......@@ -232,34 +250,37 @@ def jsonify(object):
return serialize('json', object)
return json.dumps(object)
@register.filter
def strreplace ( string, args ):
find = args.split(',')[0]
def strreplace(string, args):
find = args.split(',')[0]
replace = args.split(',')[1]
return string.replace(find,replace)
return string.replace(find, replace)
@register.filter
def replace ( string, args ):
search = args.split(args[0])[1]
def replace(string, args):
search = args.split(args[0])[1]
replace = args.split(args[0])[2]
return re.sub( search, replace, string )
return re.sub(search, replace, string)
def remove_facet(facet_id, url, facet):
scheme, netloc, path, query, fragment = list(urlparse.urlsplit(str(url)))
facet = '%s_exact:%s' % (facet_id, facet)
query_string = urlparse.parse_qsl(query)
query_string = [x for x in query_string if not (
x[0] == 'selected_facets' and x[1] == facet)]
query_string = [x for x in query_string if not (x[0] == 'selected_facets' and x[1] == facet)]
query = '&'.join(['%s=%s' % x for x in query_string])
url = urlparse.urlunsplit([scheme, netloc, path, query, None])
return re.sub(r'&page=\d+', '', url)
@register.filter
def remove_tag_facet(url, facet):
return remove_facet('tags', url, facet)
@register.filter
def remove_category_facet(url, facet):
return remove_facet('categories', url, facet)
......@@ -269,6 +290,7 @@ def remove_category_facet(url, facet):
def remove_news_category_facet(url, facet):
return remove_facet('news_categories', url, facet)
@register.filter
def remove_format_facet(url, facet):
return remove_facet('format', url, facet)
......@@ -280,18 +302,22 @@ def append_facet(facet_id, url, facet):
url = url + '?'
return re.sub(r'&page=\d+', '', url + '&selected_facets=%s_exact:%s' % (facet_id, facet))
@register.filter
def append_tag_facet(url, facet):
return append_facet('tags', url, facet)
@register.filter
def append_category_facet(url, facet):
return append_facet('categories', url, facet)
@register.filter
def append_news_category_facet(url, facet):
return append_facet('news_categories', url, facet)
@register.filter
def append_format_facet(url, facet):
return append_facet('format', url, facet)
......@@ -312,11 +338,7 @@ class FormatSearchResultNode(template.Node):
def render(self, context):
result = self.result_var.resolve(context)
dir_mapping = {
'newsitem': 'news',
'emission': 'emissions',
'episode': 'episodes'
}
dir_mapping = {'newsitem': 'news', 'emission': 'emissions', 'episode': 'episodes'}
t = template.loader.get_template('%s/search_result.html' % dir_mapping.get(result.model_name))
return t.render({'result': result})
......@@ -332,11 +354,13 @@ def rfc822(datetime):
return ''
return email.utils.formatdate(time.mktime(datetime.timetuple()))
@register.inclusion_tag('includes/related.html', takes_context=False)
def related_objects(object):
sqs = search.MoreLikeThisSearchQuerySet().models(Emission, Episode, NewsItem)
return {'more_like_this': sqs.more_like_this(object)[:12]}
@register.inclusion_tag('includes/topik.html', takes_context=True)
def topik(context, topik):
return {'page': topik}
......@@ -349,16 +373,23 @@ def get_focus_url(object):
if object.emission:
return reverse('emission-view', kwargs={'slug': object.emission.slug})
if object.episode:
return reverse('episode-view', kwargs={
'slug': object.episode.slug, 'emission_slug': object.episode.emission.slug})
return reverse(
'episode-view',
kwargs={'slug': object.episode.slug, 'emission_slug': object.episode.emission.slug},
)
if object.soundfile:
return reverse('episode-view', kwargs={
'slug': object.soundfile.episode.slug,
'emission_slug': object.soundfile.episode.emission.slug})
return reverse(
'episode-view',
kwargs={
'slug': object.soundfile.episode.slug,
'emission_slug': object.soundfile.episode.emission.slug,
},
)
if object.page:
return object.page.get_online_url()
return ''
@register.filter
def facet_tag(tag):
return tag.name.lower()
......@@ -370,6 +401,7 @@ def set_absolute_urls(text):
text = text.replace('href="/', 'href="%s' % settings.WEBSITE_BASE_URL)
return text
@register.filter
def as_absolute_url(url):
if url.startswith('/'):
......
......@@ -47,9 +47,17 @@ class CustomSolrSearchQuery(haystack.backends.solr_backend.SolrSearchQuery):
class CustomSolrSearchBackend(haystack.backends.solr_backend.SolrSearchBackend):
def more_like_this(self, model_instance, additional_query_string=None,
start_offset=0, end_offset=None, models=None,
limit_to_registered_models=None, result_class=None, **kwargs):
def more_like_this(
self,
model_instance,
additional_query_string=None,
start_offset=0,
end_offset=None,
models=None,
limit_to_registered_models=None,
result_class=None,
**kwargs,
):
from haystack import connections
# Deferred models will have a different class ("RealClass_Deferred_fieldname")
......@@ -76,7 +84,9 @@ class CustomSolrSearchBackend(haystack.backends.solr_backend.SolrSearchBackend):
limit_to_registered_models = getattr(settings, 'HAYSTACK_LIMIT_TO_REGISTERED_MODELS', True)
if models and len(models):
model_choices = sorted(['%s.%s' % (model._meta.app_label, model._meta.model_name) for model in models])
model_choices = sorted(
['%s.%s' % (model._meta.app_label, model._meta.model_name) for model in models]
)
elif limit_to_registered_models:
# Using narrow queries, limit the results to only models handled
# with the current routers.
......@@ -138,26 +148,28 @@ class SearchView(FacetedSearchView):
if self.request.GET.getlist('selected_facets'):
context['facets_qs'] = '&selected_facets=' + '&'.join(self.request.GET.getlist('selected_facets'))
context['selected_categories'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('categories_exact') and ':' in x]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('categories_exact') and ':' in x
]
context['selected_tags'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact') and ':' in x]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact') and ':' in x
]
if 'categories' in context['facets'].get('fields', []):
context['facets']['fields']['categories'] = [x for x in
context['facets']['fields']['categories'] if x[1] > 0]
context['facets']['fields']['categories'] = [
x for x in context['facets']['fields']['categories'] if x[1] > 0
]
context['facets']['fields']['categories'].sort()
if 'tags' in context['facets'].get('fields', []):
context['facets']['fields']['tags'] = [x for x in
context['facets']['fields']['tags'] if x[1] > 0]
context['facets']['fields']['tags'] = [x for x in context['facets']['fields']['tags'] if x[1] > 0]
return context
sqs = SearchQuerySet().models(Emission, Episode, NewsItem).facet('categories').facet('tags')
view = search_view_factory(SearchView,
form_class=GlobalSearchForm,
searchqueryset=sqs)
sqs = SearchQuerySet().models(Emission, Episode, NewsItem).facet('categories').facet('tags')
view = search_view_factory(SearchView, form_class=GlobalSearchForm, searchqueryset=sqs)
class ListenArchivesForm(FacetedSearchForm):
......@@ -176,28 +188,34 @@ class ListenArchivesView(FacetedSearchView):
def __init__(self):
sqs = RelatedSearchQuerySet().models(SoundFile).facet('format').facet('tags').order_by('-date')
super(ListenArchivesView, self).__init__(searchqueryset=sqs,
form_class=ListenArchivesForm, results_per_page=20)
super(ListenArchivesView, self).__init__(
searchqueryset=sqs, form_class=ListenArchivesForm, results_per_page=20
)
def extra_context(self):
context = super(ListenArchivesView, self).extra_context()
if self.request.GET.getlist('selected_facets'):
context['facets_qs'] = '&selected_facets=' + '&'.join(self.request.GET.getlist('selected_facets'))
context['selected_format'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('format_exact')]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('format_exact')
]
context['selected_tags'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact')]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact')
]
if 'format' in context['facets'].get('fields', []):
context['facets']['fields']['format'] = [x for x in
context['facets']['fields']['format'] if x[1] > 0]
context['facets']['fields']['format'] = [
x for x in context['facets']['fields']['format'] if x[1] > 0
]
context['facets']['fields']['format'].sort()
if 'tags' in context['facets'].get('fields', []):
context['facets']['fields']['tags'] = [x for x in
context['facets']['fields']['tags'] if x[1] > 0]
context['facets']['fields']['tags'] = [x for x in context['facets']['fields']['tags'] if x[1] > 0]
return context
listenArchives = search_view_factory(ListenArchivesView)
......@@ -216,27 +234,35 @@ class NewsArchivesView(FacetedSearchView):
template = 'news/archives.html'
def __init__(self):
sqs = RelatedSearchQuerySet().models(NewsItem).facet('news_categories').facet('tags').order_by('-date')
super(NewsArchivesView, self).__init__(searchqueryset=sqs,
form_class=NewsArchivesForm, results_per_page=20)
sqs = (
RelatedSearchQuerySet().models(NewsItem).facet('news_categories').facet('tags').order_by('-date')
)
super(NewsArchivesView, self).__init__(
searchqueryset=sqs, form_class=NewsArchivesForm, results_per_page=20
)
def extra_context(self):
context = super(NewsArchivesView, self).extra_context()
if self.request.GET.getlist('selected_facets'):
context['facets_qs'] = '&selected_facets=' + '&'.join(self.request.GET.getlist('selected_facets'))
context['selected_news_categories'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('news_categories_exact')]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('news_categories_exact')
]
context['selected_tags'] = [
x.split(':', 1)[1] for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact')]
x.split(':', 1)[1]
for x in self.request.GET.getlist('selected_facets')
if x.startswith('tags_exact')
]
if 'news_categories' in context['facets'].get('fields', []):
context['facets']['fields']['news_categories'] = [x for x in
context['facets']['fields']['news_categories'] if x[1] > 0]
context['facets']['fields']['news_categories'] = [
x for x in context['facets']['fields']['news_categories'] if x[1] > 0
]
context['facets']['fields']['news_categories'].sort()
if 'tags' in context['facets'].get('fields', []):
context['facets']['fields']['tags'] = [x for x in
context['facets']['fields']['tags'] if x[1] > 0]
context['facets']['fields']['tags'] = [x for x in context['facets']['fields']['tags'] if x[1] > 0]
return context
newsArchives = search_view_factory(NewsArchivesView)
......@@ -32,7 +32,7 @@ DATABASES = {
ACCOUNT_ACTIVATION_DAYS = 7 # Activation window
#if django.VERSION[:2] < (1, 6):
# if django.VERSION[:2] < (1, 6):
TEST_RUNNER = 'discover_runner.DiscoverRunner'
# Local time zone for this installation. Choices can be found here:
......@@ -47,8 +47,8 @@ TIME_ZONE = 'Europe/Brussels'
LANGUAGE_CODE = 'fr-be'
LANGUAGES = (
('fr', u'Français'),
('en', u'English'),
('fr', u'Français'),
('en', u'English'),
)
SITE_ID = 1
......@@ -92,7 +92,7 @@ STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
'gadjo.finders.XStaticFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
......@@ -182,13 +182,11 @@ CKEDITOR_UPLOAD_PREFIX = '/media/uploads/'
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.solr_backend.SolrEngine',
'URL': 'http://127.0.0.1:8985/solr/panik'
'URL': 'http://127.0.0.1:8985/solr/panik',
},
}
FIBER_TEMPLATE_CHOICES = (
('tpl-default.html', 'Default template'),
)
FIBER_TEMPLATE_CHOICES = (('tpl-default.html', 'Default template'),)
ENABLE_PIWIK = False
......@@ -201,16 +199,12 @@ CACHES = {
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'filters': {'require_debug_false': {'()': 'django.utils.log.RequireDebugFalse'}},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
'class': 'django.utils.log.AdminEmailHandler',
}
},
'loggers': {
......@@ -219,7 +213,7 @@ LOGGING = {
'level': 'ERROR',
'propagate': True,
},
}
},
}
STATSD_CLIENT = 'django_statsd.clients.null'
......@@ -266,30 +260,23 @@ if os.path.exists(local_settings_file):
exec(open(local_settings_file).read())
if DEBUG and DEBUG_TOOLBAR:
MIDDLEWARE_CLASSES += (
'debug_toolbar.middleware.DebugToolbarMiddleware',
)
INSTALLED_APPS += (
'debug_toolbar',
)
MIDDLEWARE_CLASSES += ('debug_toolbar.middleware.DebugToolbarMiddleware',)
INSTALLED_APPS += ('debug_toolbar',)
if 'template_timings_panel.panels.TemplateTimings.TemplateTimings' in DEBUG_TOOLBAR_PANELS:
INSTALLED_APPS += ('template_timings_panel',)
if ENABLE_PIWIK is False:
MIDDLEWARE_CLASSES = tuple([x for x in MIDDLEWARE_CLASSES \
if x != 'panikweb.middleware.StripPiwikCookieMiddleware'])
MIDDLEWARE_CLASSES = tuple(
[x for x in MIDDLEWARE_CLASSES if x != 'panikweb.middleware.StripPiwikCookieMiddleware']
)
if STATSD_CLIENT != 'django_statsd.clients.null':
MIDDLEWARE_CLASSES = (
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
'django_statsd.middleware.GraphiteRequestTimingMiddleware',
'django_statsd.middleware.GraphiteMiddleware',
) + MIDDLEWARE_CLASSES
INSTALLED_APPS += (
'django_statsd',
)
INSTALLED_APPS += ('django_statsd',)
if RAVEN_CONFIG:
INSTALLED_APPS += (
'raven.contrib.django.raven_compat',
)
INSTALLED_APPS += ('raven.contrib.django.raven_compat',)
......@@ -20,12 +20,21 @@ urlpatterns = [
url(r'^emissions/(?P<slug>[\w,-]+)/podcasts.rss', views.emission_podcasts_feed, name='emission-podcasts'),
url(r'^emissions/(?P<slug>[\w,-]+)/chat/$', views.chat, name='emission-chat'),
url(r'^emissions/(?P<emission_slug>[\w,-]+)/(?P<slug>[\w,-]+)/$', views.episode, name='episode-view'),
url(r'^emissions/(?P<emission_slug>[\w,-]+)/(?P<episode_slug>[\w,-]+)/embed/(?P<pk>\d+)/$',
views.soundfile_embed, name='soundfile-embed-view'),
url(r'^emissions/(?P<emission_slug>[\w,-]+)/(?P<episode_slug>[\w,-]+)/dlg-embed/(?P<pk>\d+)/$',
views.soundfile_dlg_embed, name='soundfile-dialog-embed-view'),
url(r'^emissions/(?P<slug>[\w,-]+)/playlist/(?P<year>[0-9]{4})-(?P<month>[-\w]+)-(?P<day>[0-9]+)/$',