Exemple #1
0
    def register_smoke(self, **kw):
        """Try to add the smoking data."""
        error = False
        try:
            parse_date = datetime.strptime(kw['date'], '%Y-%m-%d %H:%M:%S')
        except ValueError:
            kw['error.date'] = 'Date must be in format YYYY-MM-DD HH:MM:SS'
            error = True

        if kw.get('nosmoke'):
            # This is a nonsmoking event
            # Sanity Check: unsmoke should not occurr on a day with a
            # registered smoke, or on a day with and existing unsmoke.
            today = parse_date.date()
            tomorrow = today + timedelta(days=1)

            unsmoke = DBSession.query(Unsmoke.date) \
                .filter_by(user=request.identity['repoze.who.userid']) \
                .filter_by(date=today).all()
            smoke = DBSession.query(Cigarette.date) \
                .filter_by(user=request.identity['repoze.who.userid']) \
                .filter(Cigarette.date.between(today, tomorrow)).all()
            if smoke:
                flash("You already registered a smoke for {}".format(today), 'error')
                redirect('/smoke', params=kw)
            elif unsmoke:
                flash("You already marked {} as a non-smoking day.".format(today), 'info')
                redirect('/smoke', params=kw)
            else:
                smoke_data = Unsmoke()
                smoke_data.date = parse_date.date()
        else:
            # If there exists an unsmoke for today, probably best to delete it?
            unsmoke = DBSession.query(Unsmoke) \
                .filter_by(user=request.identity['repoze.who.userid']) \
                .filter_by(date=parse_date.date()).all()
            for event in unsmoke:
                DBSession.delete(event)
            DBSession.flush()

            smoke_data = Cigarette()
            smoke_data.date = parse_date
            smoke_data.submit_date = datetime.now()
            if kw['justification']:
                smoke_data.justification = kw['justification']
            else:
                kw['error.justification'] = 'justification is required'
                error = True

        if not error:
            smoke_data.user = request.identity['repoze.who.userid']
            DBSession.add(smoke_data)
            redirect('/')
        else:
            redirect('/smoke', params=kw)
Exemple #2
0
def time_chart(user, weeks, period=1):
    """Get information from a specified interval."""

    date_range = weeks * 7 // period
    period = timedelta(days=period)

    # 'now' is technically tomorrow at 0:00, so that today's smokes have
    # somewhere to go.
    now = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) \
        + timedelta(days=1)
    past = now - timedelta(weeks=weeks)

    data = DBSession.query(Cigarette).filter_by(user=user.user_name) \
                                     .filter(Cigarette.date >= past).all()
    # pre-fill the dictionary with zeroes
    freq_data = {(past + x*period): 0 for x in range(date_range)}
    for datum in data:
        distance = (datum.date - past).total_seconds() // period.total_seconds()
        freq_data[past + (int(distance) * period)] += 1

    if not freq_data:
        chart = 'No data to display.'
    else:
        chart = DateY(LineConfig())
        chart.add(user.display_name, sorted(freq_data.items()))
        chart = chart.render(is_unicode=True)
    return chart
Exemple #3
0
def punch_chart(user):
    cigarettes = DBSession.query(Cigarette).filter_by(user=user.user_name).all()

    chart_data = collections.defaultdict(lambda: [0]*24)
    for cigarette in cigarettes:
        dow = cigarette.date.strftime('%A')
        hour = cigarette.date.hour
        chart_data[dow][hour] += 1

    chart = Dot(DotConfig())
    days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    for dow in days:
        chart.add(dow, chart_data[dow])

    return chart.render(is_unicode=True)
Exemple #4
0
    def pick_a_user(self, user_name=None):
        public_users = DBSession.query(User).filter_by(public=True)
        all_public = public_users.all()

        # The currently logged in user should be selectable regardless of
        # publicity.
        if request.identity:
            authenticated_user = request.identity['user']
            if authenticated_user not in all_public:
                all_public.append(authenticated_user)

        # Try to use a provided user name.
        try:
            user = public_users.filter_by(display_name=user_name).one()
        except Exception:
            if request.identity:
                user = authenticated_user
            else:
                user = public_users.first()
        return all_public, user
Exemple #5
0
 def by_user_name(cls, username):
     """Return the user object whose user name is ``username``."""
     return DBSession.query(cls).filter_by(user_name=username).first()
Exemple #6
0
 def by_email_address(cls, email):
     """Return the user object whose email address is ``email``."""
     return DBSession.query(cls).filter_by(email_address=email).first()
Exemple #7
0
 def test_query_obj(self):
     """Model objects can be queried"""
     obj = DBSession.query(self.klass).one()
     for key, value in self.attrs.iteritems():
         assert_equals(getattr(obj, key), value)