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

[WIP] Aesthetic overhaul #272

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
57 changes: 19 additions & 38 deletions aligulac/aligulac/tools.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# {{{ Imports
# Imports
from itertools import chain
import json
import random
Expand Down Expand Up @@ -37,9 +37,8 @@
from ratings.tools import get_latest_period, find_player
from ratings.templatetags.ratings_extras import urlfilter
from django.utils.translation import ugettext as _
# }}}

# {{{ JsonResponse
# JsonResponse
# Works similarily to HttpResponse but returns JSON instead.
class JsonResponse(HttpResponse):

Expand All @@ -50,10 +49,9 @@ def __init__(self, content, *args, **kwargs):
kwargs["content_type"] = "application/json"

super().__init__(scontent, *args, **kwargs)
# }}}


# {{{ Message
# Message
# This class encodes error/success/warning messages sent to the templates.
# context['messages'] should point to a list of Message objects.
class Message:
Expand All @@ -76,9 +74,8 @@ def __init__(self, text=None, title='', type='info', error=None, field=None, msg
self.text = field + ': ' + error
self.type = self.ERROR
self.id = ''.join([random.choice(string.ascii_letters+string.digits) for _ in range(10)])
# }}}

# {{{ NotUniquePlayerMessage
# NotUniquePlayerMessage
class NotUniquePlayerMessage(Message):

def __init__(self, search, players, update=None, updateline=None, type='error'):
Expand All @@ -104,14 +101,12 @@ def __init__(self, search, players, update=None, updateline=None, type='error'):

Message.__init__(self, s, _('\'%s\' not unique') % search, type)
self.id = id
# }}}

# {{{ generate_messages: Generates a list of message objects for an object that supports them.
# generate_messages: Generates a list of message objects for an object that supports them.
def generate_messages(obj):
return [Message(m.get_message(), m.get_title(), m.type) for m in obj.message_set.all()]
# }}}

# {{{ login_message: Generates a message notifying about login status.
# login_message: Generates a message notifying about login status.
def login_message(base, extra=''):
if not base['adm']:
text = ' '.join([_('You are not logged in.'), extra, '(<a href="/login/">%s</a>)' % _('login')])
Expand All @@ -124,9 +119,8 @@ def login_message(base, extra=''):
)
])
base['messages'].append(Message(text, type=Message.INFO))
# }}}

# {{{ StrippedCharField: Subclass of CharField that performs stripping.
# StrippedCharField: Subclass of CharField that performs stripping.
class StrippedCharField(forms.CharField):
def clean(self, value):
value = super(StrippedCharField, self).clean(value)
Expand All @@ -138,17 +132,15 @@ def clean(self, value):
return None
return value
return None
# }}}

# {{{ get_param(request, param, default): Returns request.GET[param] if available, default if not.
# get_param(request, param, default): Returns request.GET[param] if available, default if not.
def get_param(request, param, default):
try:
return request.GET[param]
except:
return default
# }}}

# {{{ get_param_choice(request, param, choices, default): Returns request.GET[param] if available and in
# get_param_choice(request, param, choices, default): Returns request.GET[param] if available and in
# the list choices, default if not.
def get_param_choice(request, param, choices, default):
try:
Expand All @@ -157,37 +149,33 @@ def get_param_choice(request, param, choices, default):
return val
except:
return default
# }}}

# {{{ get_param_range(request, param, range, default): Returns request.GET[param] as an int, restricted to the
# get_param_range(request, param, range, default): Returns request.GET[param] as an int, restricted to the
# range given (a tuple (min,max)), or default if not.
def get_param_range(request, param, rng, default):
try:
val = int(request.GET[param])
return min(max(val, rng[0]), rng[1])
except:
return default
# }}}

# {{{ get_param_date(request, param, default): Converts a GET param to a date.
# get_param_date(request, param, default): Converts a GET param to a date.
def get_param_date(request, param, default):
param = get_param(request, param, None)
try:
return datetime.strptime(param, '%Y-%m-%d').date()
except:
return default
# }}}

# {{{ post_param(request, param, default): Returns request.POST[param] if available, default if not.
# post_param(request, param, default): Returns request.POST[param] if available, default if not.
# If you're using this method, consider deploying a form instead.
def post_param(request, param, default):
try:
return request.POST[param]
except:
return default
# }}}

# {{{ base_ctx: Generates a minimal context, required to render the site layout and menus
# base_ctx: Generates a minimal context, required to render the site layout and menus
# Parameters:
# - section: A string, name of the current major section (or None)
# - subpage: A string, name of the current subsection (or None)
Expand Down Expand Up @@ -333,9 +321,8 @@ def add_subnav(title, url):
base['commitbranch'] = p.communicate()[0].decode().strip()

return base
# }}}

# {{{ cache_login_protect: Decorator for caching only if user is not logged in.
# cache_login_protect: Decorator for caching only if user is not logged in.
# Use this in place of BOTH cache_page and csrf_protect, and only on pages that require a CSRF token IF AND
# ONLY IF the user is logged in. If the view ALWAYS issues a CSRF token (or SOMETIMES does, but you can't tell
# when easily), use neither cache_page nor csrf_protect. If the view NEVER issues a CSRF token, use cache_page
Expand All @@ -348,25 +335,22 @@ def handler(request, *args, **kwargs):
final_view = cache_page(view)
return final_view(request, *args, **kwargs)
return handler
# }}}

# {{{ etn: Executes a function and returns its result if it doesn't throw an exception, or None if it does.
# etn: Executes a function and returns its result if it doesn't throw an exception, or None if it does.
def etn(f):
try:
return f()
except:
return None
# }}}

# {{{ ntz: Helper function with aggregation, sending None to 0, so that the sum of an empty list is 0.
# ntz: Helper function with aggregation, sending None to 0, so that the sum of an empty list is 0.
# AS IT FUCKING SHOULD BE.
ntz = lambda k: k if k is not None else 0
# }}}


# {{{ search: Helper function for performing searches
# search: Helper function for performing searches
def search(query, search_for=['players', 'teams', 'events'], strict=False):
# {{{ Split query
# Split query
lex = shlex.shlex(query, posix=True)
lex.wordchars += "'#-"
lex.commenters = ''
Expand All @@ -375,9 +359,8 @@ def search(query, search_for=['players', 'teams', 'events'], strict=False):
terms = [s.strip() for s in list(lex) if s.strip() != '']
if len(terms) == 0:
return None
# }}}

# {{{ Search for players, teams and events
# Search for players, teams and events
if 'players' in search_for:
players = find_player(lst=terms, make=False, soft=True, strict=strict)
else:
Expand All @@ -404,7 +387,5 @@ def search(query, search_for=['players', 'teams', 'events'], strict=False):

if 'teams' in search_for:
teams = teams.distinct()
# }}}

return players, teams, events
# }}}
6 changes: 2 additions & 4 deletions aligulac/aligulac/urls.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# {{{ Imports
# Imports
from os.path import normpath, dirname, join

from tastypie.api import Api
Expand Down Expand Up @@ -29,7 +29,6 @@

from django.contrib import admin
admin.autodiscover()
# }}}

handler404 = 'aligulac.views.h404'
handler500 = 'aligulac.views.h500'
Expand Down Expand Up @@ -139,7 +138,7 @@
url(r'^api/', include(v1_api.urls)),
)

# {{{ If in debug mode (i.e. with the django server), we must serve CSS and JS ourselves.
# If in debug mode (i.e. with the django server), we must serve CSS and JS ourselves.
if settings.DEBUG:
resources = join(dirname(normpath(settings.PROJECT_PATH)), 'resources')
urlpatterns += patterns('',
Expand All @@ -152,4 +151,3 @@
url(r'^img/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': join(resources, 'img')})
)
# }}}
39 changes: 13 additions & 26 deletions aligulac/aligulac/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# {{{ Imports
# Imports
from datetime import datetime
from itertools import zip_longest
import os
Expand Down Expand Up @@ -53,9 +53,8 @@
filter_active,
populate_teams,
)
# }}}

# {{{ DB table specification
# DB table specification
DBTABLES = [{
'name': 'player',
'desc': _('Contains player information.'),
Expand Down Expand Up @@ -330,9 +329,8 @@
]
},
]
# }}}

# {{{ Home page
# Home page
@cache_page
def home(request):
base = base_ctx(request=request)
Expand All @@ -357,9 +355,8 @@ def home(request):
})

return render_to_response('index.djhtml', base)
# }}}

# {{{ Language change page
# Language change page
def language(request):
base = base_ctx(request=request)

Expand All @@ -370,9 +367,8 @@ def language(request):
base['return'] = '/'

return render_to_response('language.djhtml', base)
# }}}

# {{{ db view
# db view
@cache_page
def db(request):
base = base_ctx('About', 'Database', request)
Expand Down Expand Up @@ -430,24 +426,22 @@ def db(request):
})

return render_to_response('db.djhtml', base)
# }}}

# {{{ API documentation and keys
# API documentation and keys
class APIKeyForm(forms.Form):
organization = StrippedCharField(max_length=200, required=True, label=_('Name/organization'))
contact = forms.EmailField(max_length=200, required=True, label=_('Contact'))

# {{{ Constructor
# Constructor
def __init__(self, request=None, player=None):
if request is not None:
super(APIKeyForm, self).__init__(request.POST)
else:
super(APIKeyForm, self).__init__()

self.label_suffix = ''
# }}}

# {{{ add_key: Adds key if valid, returns messages
# add_key: Adds key if valid, returns messages
def add_key(self):
ret = []

Expand All @@ -471,7 +465,6 @@ def add_key(self):
_("Your API key is <code>%s</code>. Please keep it safe.") % key.key, type=Message.SUCCESS))

return ret
# }}}

def api(request):
base = base_ctx('About', 'API', request)
Expand All @@ -497,9 +490,8 @@ def api(request):
})

return render_to_response('api.djhtml', base)
# }}}

# {{{ search view
# search view
@cache_page
def search(request):
base = base_ctx(request=request)
Expand All @@ -511,14 +503,13 @@ def search(request):

players, teams, events = results

# {{{ Redirect if only one hit
# Redirect if only one hit
if players.count() == 1 and teams.count() == 0 and events.count() == 0:
return redirect('/players/%i-%s/' % (players.first().id, urlfilter(players.first().tag)))
elif players.count() == 0 and teams.count() == 1 and events.count() == 0:
return redirect('/teams/%i-%s/' % (teams.first().id, urlfilter(teams.first().name)))
elif players.count() == 0 and teams.count() == 0 and events.count() == 1:
return redirect('/results/events/%i-%s/' % (events.first().id, urlfilter(events.first().fullname)))
# }}}

base.update({
'results': zip_longest(players, teams, events, fillvalue=None),
Expand All @@ -529,9 +520,8 @@ def search(request):
})

return render_to_response('search.djhtml', base)
# }}}

# {{{ auto-complete search view
# auto-complete search view
EXTRA_NULL_SELECT = {
'null_curr': 'CASE WHEN player.current_rating_id IS NULL THEN 0 ELSE 1 END'
}
Expand Down Expand Up @@ -587,9 +577,8 @@ def auto_complete_search(request):
} for e in events[:num]]

return JsonResponse(data)
# }}}

# {{{ Login, logout and change password
# Login, logout and change password
def login_view(request):
base = base_ctx(request=request)
login_message(base)
Expand Down Expand Up @@ -629,9 +618,8 @@ def changepwd(request):
)

return render_to_response('changepwd.djhtml', base)
# }}}

# {{{ Error handlers
# Error handlers
@cache_page
def h404(request):
base = base_ctx(request=request)
Expand All @@ -641,4 +629,3 @@ def h404(request):
def h500(request):
base = base_ctx(request=request)
return HttpResponseNotFound(render_to_string('500.djhtml', base))
# }}}
Loading