Skip to content

Commit f846582

Browse files
author
Sam Hames
authored
Merge pull request #632 from DocNow/flattened-errors
Fix an edge case where a response from the API with only an errors block would be passed through unchanged.
2 parents f162235 + 767517e commit f846582

File tree

4 files changed

+20
-3
lines changed

4 files changed

+20
-3
lines changed

test_twarc2.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -509,6 +509,14 @@ def test_ensure_flattened():
509509
twarc.expansions.ensure_flattened([[{"data": {"fake": "list_of_lists"}}]])
510510

511511

512+
def test_ensure_flattened_errors():
513+
"""
514+
Test that ensure_flattened doesn't return tweets for API responses that only contain errors.
515+
"""
516+
data = {"errors": ["fake error"]}
517+
assert twarc.expansions.ensure_flattened(data) == []
518+
519+
512520
def test_ensure_user_id():
513521
"""
514522
Test _ensure_user_id's ability to discriminate correctly between IDs and

twarc/client2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1178,7 +1178,7 @@ def _stream(self, url, params, event, record_keepalive, tries=30):
11781178
log.error(f"too many consecutive errors ({tries}). stopping")
11791179
return
11801180
else:
1181-
secs = errors ** 2
1181+
secs = errors**2
11821182
log.info("sleeping %s seconds before reconnecting", secs)
11831183
time.sleep(secs)
11841184

twarc/decorators2.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ def new_f(*args, **kwargs):
9191
if errors > tries:
9292
log.warning(f"too many errors ({tries}) from Twitter, giving up")
9393
resp.raise_for_status()
94-
seconds = errors ** 2
94+
seconds = errors**2
9595
log.warning(
9696
"caught %s from Twitter API, sleeping %s", resp.status_code, seconds
9797
)
@@ -142,7 +142,7 @@ def new_f(self, *args, **kwargs):
142142
if errors > tries:
143143
log.error(f"giving up, too many request exceptions: {tries}")
144144
raise e
145-
seconds = errors ** 2
145+
seconds = errors**2
146146
log.info("sleeping %s", seconds)
147147
time.sleep(seconds)
148148
self.connect()

twarc/expansions.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,15 @@ def ensure_flattened(data):
242242
log.warning(f"Unable to expand dictionary without includes: {data}")
243243
return flatten(data)
244244

245+
# If it's just an object with errors return an empty list
246+
elif (
247+
isinstance(data, dict)
248+
and "data" not in data
249+
and "includes" not in data
250+
and "errors" in data
251+
):
252+
return []
253+
245254
# If it's a single response and both "includes" and "data" are missing, it is already flattened
246255
elif isinstance(data, dict) and "data" not in data and "includes" not in data:
247256
return [data]

0 commit comments

Comments
 (0)