File size: 7,778 Bytes
fdd9b49 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 | import json
import requests
import datetime
from . import exceptions
class FreckleClient(object):
"""Simple client implementation to fetch json data from the v1 API."""
def __init__(self, account_name, api_token):
"""
Creates a ``FreckleClient`` instance.
:account_name: Your Freckle account name.
:api_token: Your Freckle API token.
"""
self.account_name = account_name
self.api_token = api_token
def fetch_json(self, uri_path, http_method='GET', headers=None,
query_params=None, post_args=None):
"""
Fetch some JSON from Letsfreckle.
For example, fetch some entries like so:
entries = self.fetch_json(
'entries',
query_params={
'per_page': 1000,
'search[from]': '2015-01-01',
'search[to]': '2015-01-31',
'search[projects]': [1423, 24545, ]),
}
)
"""
# explicit values here to avoid mutable default values
if headers is None:
headers = {}
if query_params is None:
query_params = {}
if post_args is None:
post_args = {}
# set content type and accept headers to handle JSON
headers['Accept'] = 'application/json'
query_params['token'] = self.api_token
# construct the full URL without query parameters
url = 'https://{0}.letsfreckle.com/api/{1}.json'.format(
self.account_name, uri_path)
# perform the HTTP requests, if possible uses OAuth authentication
response = requests.request(
http_method, url, params=query_params, headers=headers,
data=json.dumps(post_args))
if response.status_code != 200:
raise exceptions.FreckleClientException(
"Freckle API Response is not 200", response.text)
return response.json()
class FreckleClientV2(object):
"""Simple client implementation to fetch json data from the v2 API."""
def __init__(self, access_token):
"""
Creates a ``FreckleClient`` instance.
:account_name: Your Freckle account name.
:api_token: Your Freckle API token.
"""
self.access_token = access_token
def fetch_json(self, uri_path, http_method='GET', headers=None,
query_params=None, post_args=None):
"""
Fetch some JSON from Letsfreckle.
For example, fetch some entries like so:
entries = self.fetch_json(
'entries',
query_params={
'per_page': 1000,
'search[from]': '2015-01-01',
'search[to]': '2015-01-31',
'search[projects]': [1423, 24545, ]),
}
)
"""
# explicit values here to avoid mutable default values
if headers is None:
headers = {}
if query_params is None:
query_params = {}
if post_args is None:
post_args = {}
# set content type and accept headers to handle JSON
headers['Accept'] = 'application/json'
headers['User-Agent'] = "python-freckle-client/0.1",
headers['X-FreckleToken'] = self.access_token
# construct the full URL without query parameters
url = 'https://api.letsfreckle.com/v2/{0}'.format(uri_path)
# perform the HTTP requests, if possible uses OAuth authentication
response = requests.request(
http_method, url, params=query_params, headers=headers,
data=json.dumps(post_args))
if response.status_code != 200:
raise exceptions.FreckleClientException(
"Freckle API Response is not 200", response.text)
return response.json()
class Freckle(object):
def __init__(self, token, account=None, api_version=1):
"""Ensures that the appropraite API ebdpoint is been called."""
if api_version == 1 and not account:
raise AttributeError
if api_version == 1:
self.client = FreckleClient(account, token)
else:
self.client = FreckleClientV2(token)
def get_entries(self, projects, start_date, end_date): # pragma: no cover
"""
Returns the entries for the given project and time frame.
:param start_date: String representing the start date (YYYY-MM-DD).
:param end_date: String representing the end date (YYYY-MM-DD).
"""
entries = self.client.fetch_json(
'entries',
query_params={
'per_page': 1000,
'search[from]': start_date,
'search[to]': end_date,
'search[projects]': ','.join(
[str(project['project']['id']) for project in projects]),
}
)
return entries
def get_project_times(self, projects, entries):
"""
Returns a dict with total time tracked per project / employee.
The dict should look like this:
{
month: {
project_id: {
user_id-1: XX,
user_id-2: YY,
total: XX + YY,
},
},
}
"""
result = {}
projects = projects[0]
for obj in entries:
entry = obj['entry']
entry_date = datetime.datetime.strptime(
entry['date'], '%Y-%m-%d')
if entry_date.month not in result:
result[entry_date.month] = {}
project_id = entry['project']['id']
project_name = entry['project']['name']
user_id = entry['user_id']
print projects[0], 'Function call'
# for key, project in projects:
# print key, project
# if project_id not in result[entry_date.month]:
# result[entry_date.month][project_id] = {
# 'total': 0, 'project_name': project_name, }
# if project is None:
# result[entry_date.month][project_id]['is_planned'] = False
# else:
# result[entry_date.month][project_id]['is_planned'] = True
# if user_id not in result[entry_date.month][project_id]:
# result[entry_date.month][project_id][user_id] = 0
# if (project and project.is_investment) or entry['billable']:
# minutes = entry['minutes']
# result[entry_date.month][project_id][user_id] += minutes
# result[entry_date.month][project_id]['total'] += minutes
return result
def get_users(self):
"""Get users from Freckle"""
return self.client.fetch_json('users')
def get_projects(self):
"""Get projects from Freckle"""
return self.client.fetch_json('projects')
def boolean_as_python(self, val):
"""Convert text to boolean"""
if val == 'true':
return True
else:
return False
def date_as_python(self, val):
"""Convert text to date"""
return datetime.date(*[int(x) for x in val.split("-")])
def datetime_as_python(self, val):
"""Convert text to datetime"""
return parse_date(val)
def integer_as_python(self, val):
"""Convert text to integer"""
return int(val)
def array_as_python(self, val):
"""Convert text to list"""
return val.split(",")
def json_as_python(self, val):
"""Convert JSON to dict"""
return json.load(val) |