Skip to content

Commit adb6f0d

Browse files
committed
Black formatting.
1 parent 7273baa commit adb6f0d

File tree

11 files changed

+321
-292
lines changed

11 files changed

+321
-292
lines changed

farmOS/__init__.py

+34-28
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,15 @@
1616
class farmOS:
1717
"""A client that connects to the farmOS server."""
1818

19-
def __init__(self,
20-
hostname,
21-
client_id='farm',
22-
client_secret=None,
23-
scope='user_access',
24-
token=None,
25-
token_updater=None):
19+
def __init__(
20+
self,
21+
hostname,
22+
client_id="farm",
23+
client_secret=None,
24+
scope="user_access",
25+
token=None,
26+
token_updater=None,
27+
):
2628
"""
2729
Initialize instance of the farmOS client that connects to a single farmOS server.
2830
@@ -35,12 +37,12 @@ def __init__(self,
3537
:param token_updater: A function used to save OAuth tokens outside of the client.
3638
"""
3739

38-
logger.debug('Creating farmOS client.')
40+
logger.debug("Creating farmOS client.")
3941

4042
# Load the token updater function.
4143
self.token_updater = None
4244
if token_updater is not None:
43-
logger.debug('Using provided token_updater utility.')
45+
logger.debug("Using provided token_updater utility.")
4446
self.token_updater = token_updater
4547

4648
self.session = None
@@ -54,7 +56,7 @@ def __init__(self,
5456
# Add a default scheme if not provided.
5557
if not parsed_url.scheme:
5658
parsed_url = parsed_url._replace(scheme=default_scheme)
57-
logger.debug('No scheme provided. Using %s', default_scheme)
59+
logger.debug("No scheme provided. Using %s", default_scheme)
5860

5961
# Check for a valid scheme.
6062
if parsed_url.scheme not in valid_schemes:
@@ -63,7 +65,7 @@ def __init__(self,
6365
# If not netloc was provided, it was probably parsed as the path.
6466
if not parsed_url.netloc and parsed_url.path:
6567
parsed_url = parsed_url._replace(netloc=parsed_url.path)
66-
parsed_url = parsed_url._replace(path='')
68+
parsed_url = parsed_url._replace(path="")
6769

6870
# Check for netloc.
6971
if not parsed_url.netloc:
@@ -75,53 +77,57 @@ def __init__(self,
7577

7678
# Build the url again to include changes.
7779
hostname = urlunparse(parsed_url)
78-
logger.debug('Complete hostname configured as %s', hostname)
80+
logger.debug("Complete hostname configured as %s", hostname)
7981

8082
else:
8183
raise Exception("No hostname provided and could not be loaded from config.")
8284

83-
logger.debug('Creating an OAuth Session.')
84-
token_url = hostname + '/oauth2/token'
85+
logger.debug("Creating an OAuth Session.")
86+
token_url = hostname + "/oauth2/token"
8587

8688
# Check the token expiration time.
87-
if token is not None and 'expires_at' in token:
89+
if token is not None and "expires_at" in token:
8890
# Create datetime objects for comparison.
8991
now = datetime.now()
90-
expiration_time = datetime.fromtimestamp(float(token['expires_at']))
92+
expiration_time = datetime.fromtimestamp(float(token["expires_at"]))
9193

9294
# Calculate seconds until expiration.
9395
timedelta = expiration_time - now
9496
expires_in = timedelta.total_seconds()
9597

9698
# Update the token expires_in value
97-
token['expires_in'] = expires_in
99+
token["expires_in"] = expires_in
98100

99101
# Unset the 'expires_at' key.
100-
token.pop('expires_at')
102+
token.pop("expires_at")
101103

102104
# Create an OAuth Session
103-
self.session = OAuthSession(hostname=hostname,
104-
client_id=client_id,
105-
client_secret=client_secret,
106-
scope=scope,
107-
token=token,
108-
token_url=token_url,
109-
token_updater=self.token_updater)
105+
self.session = OAuthSession(
106+
hostname=hostname,
107+
client_id=client_id,
108+
client_secret=client_secret,
109+
scope=scope,
110+
token=token,
111+
token_url=token_url,
112+
token_updater=self.token_updater,
113+
)
110114

111115
self._client_id = client_id
112116
self._client_secret = client_secret
113117

114118
if self.session is None:
115-
raise Exception("Could not create a session object. Supply authentication credentials when "
116-
"initializing a farmOS Client.")
119+
raise Exception(
120+
"Could not create a session object. Supply authentication credentials when "
121+
"initializing a farmOS Client."
122+
)
117123

118124
self.log = LogAPI(self.session)
119125
self.asset = AssetAPI(self.session)
120126
self.area = AreaAPI(self.session)
121127
self.term = TermAPI(self.session)
122128
self.info = partial(info, self.session)
123129

124-
def authorize(self, username=None, password=None, scope='user_access'):
130+
def authorize(self, username=None, password=None, scope="user_access"):
125131
"""Authorize with the farmOS server.
126132
127133
The client must be authorized with the farmOS server before making requests.

farmOS/client.py

+67-46
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
logger = logging.getLogger(__name__)
55
logger.addHandler(logging.NullHandler())
66

7+
78
class BaseAPI(object):
89
"""Base class for API methods
910
@@ -24,17 +25,21 @@ def __init__(self, session, entity_type=None):
2425
def _get_single_record_data(self, id):
2526
"""Retrieve one record given the record ID"""
2627
# Set path to return record type by specific ID
27-
path = self.entity_type + '/' + str(id) + '.json'
28+
path = self.entity_type + "/" + str(id) + ".json"
2829

29-
logger.debug('Getting single record data for id: %s of entity type: %s', id, self.entity_type)
30+
logger.debug(
31+
"Getting single record data for id: %s of entity type: %s",
32+
id,
33+
self.entity_type,
34+
)
3035
response = self.session.http_request(path=path)
3136

3237
return response.json()
3338

3439
def _get_record_data(self, filters):
3540
"""Retrieve one page of raw record data from the farmOS API."""
3641
# Set path to return record type + filters
37-
path = self.entity_type + '.json'
42+
path = self.entity_type + ".json"
3843
# Combine instance filters and filters from the method call
3944
filters = {**self.filters, **filters}
4045

@@ -44,12 +49,12 @@ def _get_record_data(self, filters):
4449
data = {}
4550

4651
response = response.json()
47-
if 'list' in response:
48-
data['list'] = response['list']
49-
data['page'] = {
50-
'self': _parse_api_page(url=response['self']),
51-
'first': _parse_api_page(url=response['first']),
52-
'last': _parse_api_page(url=response['last']),
52+
if "list" in response:
53+
data["list"] = response["list"]
54+
data["page"] = {
55+
"self": _parse_api_page(url=response["self"]),
56+
"first": _parse_api_page(url=response["first"]),
57+
"last": _parse_api_page(url=response["last"]),
5358
}
5459

5560
return data
@@ -59,31 +64,37 @@ def _get_all_record_data(self, filters, page=0, list=None):
5964
if list is None:
6065
list = []
6166

62-
filters['page'] = page
67+
filters["page"] = page
6368

64-
logger.debug('Getting page: %s of record data of entity type: %s', filters['page'], self.entity_type)
69+
logger.debug(
70+
"Getting page: %s of record data of entity type: %s",
71+
filters["page"],
72+
self.entity_type,
73+
)
6574
data = self._get_record_data(filters=filters)
6675

6776
# Append record data to list of all requested data
68-
if 'list' in data:
69-
list = list + data['list']
77+
if "list" in data:
78+
list = list + data["list"]
7079

7180
# Check to see if there are more pages
72-
if 'page' in data:
73-
last_page = data['page']['last']
81+
if "page" in data:
82+
last_page = data["page"]["last"]
7483
# Last page, return the list
7584
if last_page == page:
7685
data = {
77-
'page': {
78-
'first': data['page']['first'],
79-
'last': data['page']['last'],
86+
"page": {
87+
"first": data["page"]["first"],
88+
"last": data["page"]["last"],
8089
},
81-
'list': list,
90+
"list": list,
8291
}
8392
return data
8493
# Recursive call, get the next page
8594
else:
86-
return self._get_all_record_data(list=list, page=(page+1), filters=filters)
95+
return self._get_all_record_data(
96+
list=list, page=(page + 1), filters=filters
97+
)
8798

8899
def _get_records(self, filters=None):
89100
"""Helper function that checks to retrieve one record, one page or multiple pages of farmOS records"""
@@ -95,11 +106,17 @@ def _get_records(self, filters=None):
95106
return self._get_single_record_data(filters)
96107
elif isinstance(filters, dict):
97108
# Check if the caller requests a specific page
98-
if 'page' in filters:
99-
logger.debug('Getting page: %s of record data of entity type: %s', filters['page'], self.entity_type)
109+
if "page" in filters:
110+
logger.debug(
111+
"Getting page: %s of record data of entity type: %s",
112+
filters["page"],
113+
self.entity_type,
114+
)
100115
return self._get_record_data(filters=filters)
101116
else:
102-
logger.debug('Getting all record data of entity type: %s', self.entity_type)
117+
logger.debug(
118+
"Getting all record data of entity type: %s", self.entity_type
119+
)
103120
return self._get_all_record_data(filters=filters)
104121

105122
def get(self, filters=None):
@@ -110,43 +127,47 @@ def get(self, filters=None):
110127
return data
111128

112129
def send(self, payload):
113-
options = {'json': payload}
130+
options = {"json": payload}
114131

115132
# If an ID is included, update the record
116-
id = payload.pop('id', None)
133+
id = payload.pop("id", None)
117134
if id:
118-
logger.debug('Updating record id: of entity type: %s', id, self.entity_type)
119-
path = self.entity_type + '/' + str(id)
120-
response = self.session.http_request(method='PUT', path=path, options=options)
135+
logger.debug("Updating record id: of entity type: %s", id, self.entity_type)
136+
path = self.entity_type + "/" + str(id)
137+
response = self.session.http_request(
138+
method="PUT", path=path, options=options
139+
)
121140
# If no ID is included, create a new record
122141
else:
123-
logger.debug('Creating record of entity type: %s', self.entity_type)
142+
logger.debug("Creating record of entity type: %s", self.entity_type)
124143
path = self.entity_type
125-
response = self.session.http_request(method='POST', path=path, options=options)
144+
response = self.session.http_request(
145+
method="POST", path=path, options=options
146+
)
126147

127148
# Handle response from POST requests
128149
if response.status_code == 201:
129-
logger.debug('Record created.')
150+
logger.debug("Record created.")
130151
return response.json()
131152

132153
# Handle response from PUT requests
133154
if response.status_code == 200:
134-
logger.debug('Record updated.')
155+
logger.debug("Record updated.")
135156
# farmOS returns no response data for PUT requests
136157
# response_data = response.json()
137158

138159
# Hard code the entity ID, path, and resource
139160
entity_data = {
140-
'id': id,
141-
'uri': path,
142-
'resource': self.entity_type,
161+
"id": id,
162+
"uri": path,
163+
"resource": self.entity_type,
143164
}
144165
return entity_data
145166

146167
def delete(self, id):
147-
logger.debug('Deleted record id: %s of entity type: %s', id, self.entity_type)
148-
path = self.entity_type + '/' + str(id)
149-
response = self.session.http_request(method='DELETE', path=path)
168+
logger.debug("Deleted record id: %s of entity type: %s", id, self.entity_type)
169+
path = self.entity_type + "/" + str(id)
170+
response = self.session.http_request(method="DELETE", path=path)
150171

151172
return response
152173

@@ -156,15 +177,15 @@ class TermAPI(BaseAPI):
156177

157178
def __init__(self, session):
158179
# Define 'taxonomy_term' as the farmOS API entity endpoint
159-
super().__init__(session=session, entity_type='taxonomy_term')
180+
super().__init__(session=session, entity_type="taxonomy_term")
160181

161182
def get(self, filters=None):
162183
"""Get method that supports a bundle name as the 'filter' parameter"""
163184

164185
# Check if filters parameter is a str
165186
if isinstance(filters, str):
166187
# Add filters to instance requests.session filter dict with keyword 'bundle'
167-
self.filters['bundle'] = filters
188+
self.filters["bundle"] = filters
168189
# Reset filters to empty dict
169190
filters = {}
170191

@@ -178,23 +199,23 @@ class LogAPI(BaseAPI):
178199

179200
def __init__(self, session):
180201
# Define 'log' as the farmOS API entity endpoint
181-
super().__init__(session=session, entity_type='log')
202+
super().__init__(session=session, entity_type="log")
182203

183204

184205
class AssetAPI(BaseAPI):
185206
"""API for interacting with farm assets"""
186207

187208
def __init__(self, session):
188209
# Define 'farm_asset' as the farmOS API entity endpoint
189-
super().__init__(session=session, entity_type='farm_asset')
210+
super().__init__(session=session, entity_type="farm_asset")
190211

191212

192213
class AreaAPI(TermAPI):
193214
"""API for interacting with farm areas, a subset of farm terms"""
194215

195216
def __init__(self, session):
196217
super().__init__(session=session)
197-
self.filters['bundle'] = 'farm_areas'
218+
self.filters["bundle"] = "farm_areas"
198219

199220
def get(self, filters=None):
200221
"""Retrieve raw record data from the farmOS API.
@@ -208,7 +229,7 @@ def get(self, filters=None):
208229
tid = str(filters)
209230
# Add tid to filters object
210231
filters = {
211-
'tid': tid,
232+
"tid": tid,
212233
}
213234

214235
data = self._get_records(filters=filters)
@@ -219,7 +240,7 @@ def get(self, filters=None):
219240
def info(session):
220241
"""Retrieve info about the farmOS server."""
221242

222-
logger.debug('Retrieving farmOS server info.')
243+
logger.debug("Retrieving farmOS server info.")
223244
response = session.http_request("farm.json")
224245
return response.json()
225246

@@ -233,6 +254,6 @@ def _parse_api_page(url):
233254
"""
234255

235256
parsed_url = urlparse(url)
236-
page_num = parse_qs(parsed_url.query)['page'][0]
257+
page_num = parse_qs(parsed_url.query)["page"][0]
237258

238259
return int(page_num)

0 commit comments

Comments
 (0)