Workout With Friends
Stay fit with a little motivation
 All Classes Namespaces Files Functions Variables Properties
subscribers.py
Go to the documentation of this file.
1 ##
2 #
3 # Application event subscribers.
4 #
5 
6 from __future__ import unicode_literals
7 import datetime
8 from jinja2 import Markup
9 from pyramid.events import BeforeRender, ContextFound, subscriber
10 from pyramid.httpexceptions import HTTPBadRequest
11 from pyramid.threadlocal import get_current_request
12 from random import choice
13 from sqlalchemy import event
14 from wowf.config import settings
15 from wowf.lib import consts
16 from wowf.lib.fulltext import index
17 from wowf.lib.utils import Storage
18 from wowf.models.meta import DBSession
19 
20 
21 @subscriber(ContextFound, request_method='POST')
22 ##
23 #
24 # Perform CSRF validation on all POST requests early in the request cycle.
25 #
26 def csrf_validation(event):
27  request = event.request
28  token = request.POST.get('token')
29  if token is None:
30  raise HTTPBadRequest('CSRF token is missing')
31  elif token != request.session.get_csrf_token():
32  raise HTTPBadRequest('CSRF token is invalid')
33 
34 
35 @subscriber(BeforeRender)
36 ##
37 #
38 # Pass variables to the template.
39 #
41  request = get_current_request()
42  token = request.session.get_csrf_token()
43  token_field = Markup('<input type="hidden" name="token" value="%s" />' % token)
44  event['g'] = Storage(consts, settings=settings, token_field=token_field)
45  event['h'] = Storage(datetime=datetime, choice=choice)
46 
47 
48 @event.listens_for(DBSession, 'after_flush')
49 ##
50 #
51 # Automatically add, update, and delete indexes as necessary.
52 #
53 def update_indexes(session, flush_context):
54  writer = index.writer()
55  for obj in session.new:
56  obj.add_index(writer)
57  for obj in session.dirty:
58  obj.update_index(writer)
59  for obj in session.deleted:
60  obj.delete_index(writer)
61  writer.commit()
62