Skip to content

Commit

Permalink
Change how db is instantiated, cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
beaugunderson committed Feb 8, 2014
1 parent 6bb0a7c commit 5dfa5ee
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 60 deletions.
11 changes: 6 additions & 5 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@

from flask import Flask, request, render_template, url_for
from flask.ext.jsonpify import jsonify
from flask.ext.sqlalchemy import SQLAlchemy
from raven.contrib.flask import Sentry
from twilio import TwilioRestException

from models import aggregate_stats, log_call, call_count
from models import db, aggregate_stats, log_call, call_count
from political_data import PoliticalData

app = Flask(__name__)

app.config.from_object('config.ConfigProduction')

db = SQLAlchemy(app)
sentry = Sentry(app)

db.init_app(app)

call_methods = ['GET', 'POST']

data = PoliticalData()
Expand Down Expand Up @@ -259,7 +259,7 @@ def make_single_call():
def call_complete():
params, campaign = parse_params(request)

log_call(db, params, campaign, request)
log_call(params, campaign, request)

resp = twilio.twiml.Response()

Expand Down Expand Up @@ -296,9 +296,10 @@ def call_complete_status():
def demo():
return render_template('demo.html')


@app.route('/count')
def count():
return jsonify(call_count(db))
return jsonify(count=call_count())


@app.route('/stats')
Expand Down
89 changes: 34 additions & 55 deletions models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,19 @@
import logging

from datetime import datetime
from flask.ext.sqlalchemy import SQLAlchemy
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func, Column, Integer, String, DateTime
from sqlalchemy.exc import SQLAlchemyError

db = SQLAlchemy()


def hash_phone(number):
# takes phone number and returns 64 charachter string
return hashlib.sha256(number).hexdigest()


def to_dict(model):
d = model.__dict__
d.pop('_sa_instance_state')

return d


db.Model.to_dict = to_dict


class Call(db.Model):
__tablename__ = 'calls'

id = Column(Integer, primary_key=True)
timestamp = Column(DateTime)
campaign_id = Column(String(10))
campaign_id = Column(String(32))
member_id = Column(String(10)) # congress member sunlight identifier

# user attributes
Expand All @@ -42,6 +28,13 @@ class Call(db.Model):
status = Column(String(25)) # twilio call status
duration = Column(Integer) # twilio call time in seconds

@classmethod
def hash_phone(cls, number):
"""
Takes a phone number and returns a 64 character string
"""
return hashlib.sha256(number).hexdigest()

def __init__(self, campaign_id, member_id, zipcode=None, phone_number=None,
call_id=None, status='unknown', duration=0):
self.timestamp = datetime.now()
Expand All @@ -53,7 +46,7 @@ def __init__(self, campaign_id, member_id, zipcode=None, phone_number=None,

if phone_number:
phone_number = phone_number.replace('-', '').replace('.', '')
self.user_id = hash_phone(phone_number)
self.user_id = self.hash_phone(phone_number)
self.areacode = phone_number[:3]
self.exchange = phone_number[3:6]

Expand All @@ -64,7 +57,7 @@ def __repr__(self):
self.areacode, self.exchange, self.member_id)


def log_call(db, params, campaign, request):
def log_call(params, campaign, request):
try:
i = int(request.values.get('call_index'))

Expand All @@ -73,53 +66,39 @@ def log_call(db, params, campaign, request):
'member_id': params['repIds'][i],
'zipcode': params['zipcode'],
'phone_number': params['userPhone'],
'call_id': request.values.get('CallSid', None), # twilio call id
'call_id': request.values.get('CallSid', None),
'status': request.values.get('DialCallStatus', 'unknown'),
'duration': request.values.get('DialCallDuration', 0)
}

db.session.add(Call(**kwds))
db.session.commit()
except Exception:
logging.error('Failed to log call: Exception: {}'.format(kwds),
exc_info=True)
except SQLAlchemyError:
logging.error('Failed to log call:', exc_info=True)


def call_count(db):
def call_count():
try:
return {
'count': db.session.query(func.Count(Call.zipcode)).all()[0][0]
}
except:
return 0


def aggregate_stats(cid):
zipcodes = db.session.query(Call.zipcode, func.Count(Call.zipcode)) \
.filter(Call.campaign_id == cid) \
.group_by(Call.zipcode).all()

reps = db.session.query(Call.member_id, func.Count(Call.member_id)) \
.filter(Call.campaign_id == cid) \
.group_by(Call.member_id).all()
return db.session.query(func.Count(Call.zipcode)).all()[0][0]
except SQLAlchemyError:
logging.error('Failed to get call_count:', exc_info=True)

return dict(calls=dict(
zipcodes=dict(tuple(z) for z in zipcodes),
reps=dict(tuple(r) for r in reps)))


def setUp(app):
db.app = app
db.drop_all()
db.create_all()
return 0


def tearDown(app):
db.app = app
db.drop_all()
def aggregate_stats(campaign_id):
zipcodes = (db.session.query(Call.zipcode, func.Count(Call.zipcode))
.filter(Call.campaign_id == campaign_id)
.group_by(Call.zipcode).all())

reps = (db.session.query(Call.member_id, func.Count(Call.member_id))
.filter(Call.campaign_id == campaign_id)
.group_by(Call.member_id).all())

if __name__ == "__main__":
# initialize db
from app import app
setUp(app)
return {
'campaign': campaign_id,
'calls': {
'zipcodes': dict(tuple(z) for z in zipcodes),
'reps': dict(tuple(r) for r in reps)
}
}

0 comments on commit 5dfa5ee

Please sign in to comment.