Skip to content

Commit cfb3a7c

Browse files
committed
Rework cron job to call postmark api just once
1 parent 0fb7f79 commit cfb3a7c

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

src/onegov/org/cronjobs.py

+15-10
Original file line numberDiff line numberDiff line change
@@ -773,12 +773,10 @@ def get_postmark_token() -> str:
773773

774774
return ''
775775

776-
token = get_postmark_token()
777-
778-
collections = (RecipientCollection, EntryRecipientCollection)
779-
for collection in collections:
780-
recipients = collection(request.session)
776+
def get_bounces() -> list[dict[str, Any]]:
777+
token = get_postmark_token()
781778
yesterday = utcnow() - timedelta(days=1)
779+
r = None
782780

783781
try:
784782
r = requests.get(
@@ -787,21 +785,28 @@ def get_postmark_token() -> str:
787785
f'{yesterday.date()}&inactive=true',
788786
headers={
789787
'Accept': 'application/json',
790-
'X-Postmark-Server-Token': token
791-
},
792-
timeout=30
788+
'X-Postmark-Server-Token': token,
789+
},
790+
timeout=30,
793791
)
794792
r.raise_for_status()
795793
bounces = r.json().get('Bounces', [])
796794
except requests.exceptions.HTTPError as http_err:
797-
if r.status_code == 401:
795+
if r and r.status_code == 401:
798796
raise RuntimeWarning(
799797
f'Postmark API token is not set or invalid: {http_err}'
800798
) from None
801799
else:
802800
raise
803801

804-
for bounce in bounces:
802+
return bounces
803+
804+
postmark_bounces = get_bounces()
805+
collections = (RecipientCollection, EntryRecipientCollection)
806+
for collection in collections:
807+
recipients = collection(request.session)
808+
809+
for bounce in postmark_bounces:
805810
email = bounce.get('Email', '')
806811
inactive = bounce.get('Inactive', False)
807812
recipient = recipients.by_address(email)

0 commit comments

Comments
 (0)