Scrapes hours from Pivotal Trackers optional time tracker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import datetime | |
import decimal | |
import logging | |
from StringIO import StringIO | |
from lxml import html | |
import twill | |
from twill import commands as twl | |
logging.basicConfig(level=logging.WARNING) | |
class PivotalTracker(object): | |
""" | |
Pivotal Tracker object with handy methods for grabbing time | |
Example usage:: | |
pt = PivotalTracker('username', 'password') | |
pt.get_hours() | |
""" | |
def __init__(self, username, password): | |
self.browser = twill.get_browser() | |
twill.set_output(StringIO()) | |
twl.go('https://www.pivotaltracker.com') | |
self.login(username, password) | |
def login(self, username, password): | |
"""Login to Pivotal Tracker""" | |
twl.go('/signin') | |
twl.fv('1', 'credentials[username]', username) | |
twl.fv('1', 'credentials[password]', password) | |
twl.submit() | |
assert(self.browser.get_url() == 'https://www.pivotaltracker.com/dashboard') | |
def get_hours(self, start_date=None, end_date=None, project_id=-1): | |
""" | |
Get logged hours. | |
Defaults to getting all hours to date for all projects | |
""" | |
start_date = start_date or datetime.date(1900, 1, 1) | |
end_date = end_date or datetime.date.today() | |
# load time report | |
twl.go('/time_shifts?date_period[start]=%s&date_period[finish]=%s&project=%s&person=none&grouped_by=&commit=Submit' % \ | |
(start_date.strftime('%m/%d/%Y'), end_date.strftime('%m/%d/%Y'), | |
project_id)) | |
# scrape total hours | |
parsed = html.document_fromstring(self.browser.get_html()) | |
try: | |
hours_element = parsed.cssselect('.total')[1] | |
hours = decimal.Decimal(hours_element.text_content()) | |
except (IndexError, TypeError): | |
logging.error("Could not find total hours using %s", | |
self.browser.get_url()) | |
hours = decimal.Decimal('0') | |
return hours |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment