Skip to content
This repository was archived by the owner on Nov 22, 2024. It is now read-only.

Commit c5a5587

Browse files
committed
improved date/time rfc/iso code, lint fixes
1 parent 9dca32b commit c5a5587

File tree

4 files changed

+57
-44
lines changed

4 files changed

+57
-44
lines changed

CloudFlare/tests/test_graphql.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22

33
import os
44
import sys
5-
import time
65
import random
76
import datetime
8-
import pytz
97
import json
108

119
sys.path.insert(0, os.path.abspath('.'))
@@ -45,12 +43,12 @@ def test_find_zone(domain_name=None):
4543
assert len(zone_id) == 32
4644
print('zone: %s %s' % (zone_id, zone_name), file=sys.stderr)
4745

48-
def now_iso8601_time(h_delta):
49-
"""need a yyyy-mm-dd string"""
50-
t = time.time() - (h_delta * 3600)
51-
# only use yyyy-mm-dd part for httpRequests1dGroups below
52-
r = datetime.datetime.fromtimestamp(int(t), tz=pytz.timezone("UTC")).strftime('%Y-%m-%d')
53-
return r
46+
def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
47+
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
48+
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
49+
if with_hms:
50+
return dt.isoformat().replace('+00:00', 'Z')
51+
return dt.strftime('%Y-%m-%d')
5452

5553
def test_graphql_get():
5654
""" /graphql_get test """
@@ -129,8 +127,8 @@ def test_graphql_post_empty():
129127

130128
def test_graphql_post():
131129
""" /graphql_post test """
132-
date_before = now_iso8601_time(0) # now
133-
date_after = now_iso8601_time(3 * 24) # 3 days worth
130+
date_before = rfc3339_iso8601_time(0) # now
131+
date_after = rfc3339_iso8601_time(-3 * 24) # 3 days worth
134132

135133
query = """
136134
query {

CloudFlare/tests/test_images_v2_direct_upload.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,13 @@
1414

1515
cf = None
1616

17+
def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
18+
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
19+
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
20+
if with_hms:
21+
return dt.isoformat().replace('+00:00', 'Z')
22+
return dt.strftime('%Y-%m-%d')
23+
1724
def test_cloudflare(debug=False):
1825
""" test_cloudflare """
1926
global cf
@@ -52,7 +59,7 @@ def test_find_account(find_name=None):
5259
})
5360

5461
# format future time in RFC3339 format (and do it UTC time)
55-
time_plus_one_hour_in_iso = (datetime.datetime.utcnow().replace(microsecond=0) + datetime.timedelta(hours=1)).isoformat() + 'Z'
62+
time_plus_one_hour_in_iso = rfc3339_iso8601_time(1, True)
5663

5764
def test_images_v2_direct_upload():
5865
""" test_images_v2_direct_upload """

examples/example_graphql.py

Lines changed: 15 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,19 +3,18 @@
33

44
import os
55
import sys
6-
import time
76
import datetime
8-
import pytz
97

108
sys.path.insert(0, os.path.abspath('..'))
119
import CloudFlare
1210

13-
def now_iso8601_time(h_delta):
14-
"""Cloudflare API code - example"""
15-
t = time.time() - (h_delta * 3600)
16-
# only use yyyy-mm-dd part for httpRequests1dGroups below
17-
r = datetime.datetime.fromtimestamp(int(t), tz=pytz.timezone("UTC")).strftime('%Y-%m-%d')
18-
return r
11+
def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
12+
""" rfc3339_iso8601_time """
13+
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
14+
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
15+
if with_hms:
16+
return dt.isoformat().replace('+00:00', 'Z')
17+
return dt.strftime('%Y-%m-%d')
1918

2019
def main():
2120
"""Cloudflare API code - example"""
@@ -25,20 +24,18 @@ def main():
2524
zone_name = sys.argv[1]
2625
params = {'name':zone_name, 'per_page':1}
2726
except IndexError:
28-
exit('usage: example_graphql zone')
27+
sys.exit('usage: example_graphql zone')
2928

3029
cf = CloudFlare.CloudFlare()
3130

3231
# grab the zone identifier
3332
try:
3433
zones = cf.zones.get(params=params)
3534
except CloudFlare.exceptions.CloudFlareAPIError as e:
36-
exit('/zones.get %d %s - api call failed' % (e, e))
37-
except Exception as e:
38-
exit('/zones - %s - api call failed' % (e))
35+
sys.exit('/zones.get %d %s - api call failed' % (int(e), str(e)))
3936

40-
date_before = now_iso8601_time(0) # now
41-
date_after = now_iso8601_time(7 * 24) # 7 days worth
37+
date_before = rfc3339_iso8601_time(0) # now
38+
date_after = rfc3339_iso8601_time(-7 * 24) # 7 previous days worth
4239

4340
zone_id = zones[0]['id']
4441
query = """
@@ -58,14 +55,14 @@ def main():
5855
try:
5956
r = cf.graphql.post(data={'query':query})
6057
except CloudFlare.exceptions.CloudFlareAPIError as e:
61-
exit('/graphql.post %d %s - api call failed' % (e, e))
58+
sys.exit('/graphql.post %d %s - api call failed' % (int(e), str(e)))
6259

6360
# only one zone, so use zero'th element!
6461
zone_info = r['data']['viewer']['zones'][0]
6562

66-
httpRequests1dGroups = zone_info['httpRequests1dGroups']
63+
http_requests1d_groups = zone_info['httpRequests1dGroups']
6764

68-
for h in sorted(httpRequests1dGroups, key=lambda v: v['dimensions']['date']):
65+
for h in sorted(http_requests1d_groups, key=lambda v: v['dimensions']['date']):
6966
result_date = h['dimensions']['date']
7067
result_info = h['sum']['countryMap']
7168
print(result_date)
@@ -74,4 +71,4 @@ def main():
7471

7572
if __name__ == '__main__':
7673
main()
77-
exit(0)
74+
sys.exit(0)

examples/example_images_v2_direct_upload.py

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,16 @@
3232
# released between then require at-least one paramater send via files= in order to not trigger a backend API bug
3333
#
3434

35+
def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
36+
""" rfc3339_iso8601_time """
37+
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
38+
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
39+
if with_hms:
40+
return dt.isoformat().replace('+00:00', 'Z')
41+
return dt.strftime('%Y-%m-%d')
42+
3543
def method_from_library_version():
44+
""" method_from_library_version """
3645
if CloudFlare.__version__ <= '2.14.2':
3746
print('Using %s version of Cloudflare python library - hence do not need data= or files=; but use files= if passing anything' % (CloudFlare.__version__))
3847
return ''
@@ -44,6 +53,7 @@ def method_from_library_version():
4453
return 'USE-DATA'
4554

4655
def doit(account_name, image_filename):
56+
""" doit """
4757

4858
# https://developers.cloudflare.com/stream/uploading-videos/direct-creator-uploads/
4959
# https://developers.cloudflare.com/api/operations/cloudflare-images-create-authenticated-direct-upload-url-v-2
@@ -53,16 +63,16 @@ def doit(account_name, image_filename):
5363
params = {'name': account_name, 'per_page': 1}
5464
accounts = cf.accounts.get(params=params)
5565
except CloudFlare.exceptions.CloudFlareAPIError as e:
56-
exit('%s: %d %s - api call failed' % ('/accounts', e, e))
66+
sys.exit('%s: %d %s - api call failed' % ('/accounts', int(e), str(e)))
5767
try:
5868
account_id = accounts[0]['id']
5969
except IndexError:
60-
exit('%s: account name not found' % (account_name))
70+
sys.exit('%s: account name not found' % (account_name))
6171

6272
try:
6373
image_fp = open(image_filename, 'rb')
6474
except Exception as e:
65-
exit('%s: %s - file read failed' % (image_filename, e))
75+
sys.exit('%s: %s - file read failed' % (image_filename, e))
6676

6777
image_filesize = os.fstat(image_fp.fileno()).st_size
6878
if image_filesize > 1024*1024*1024:
@@ -75,7 +85,7 @@ def doit(account_name, image_filename):
7585
print('%s: filesize = %d Bytes' % (image_filename, image_filesize))
7686

7787
# format future time in RFC3339 format (and do it UTC time)
78-
time_plus_one_hour_in_iso = (datetime.datetime.utcnow().replace(microsecond=0) + datetime.timedelta(hours=1)).isoformat() + 'Z'
88+
time_plus_one_hour_in_iso = rfc3339_iso8601_time(1, True)
7989

8090
# direct_upload uses multipart/form-data and hence this info is passed as files (but None for filename)
8191
# these are the four form values
@@ -115,7 +125,7 @@ def doit(account_name, image_filename):
115125
try:
116126
r = cf.accounts.images.v2.direct_upload.post(account_id, data=data, files=files)
117127
except CloudFlare.exceptions.CloudFlareAPIError as e:
118-
exit('%s: %d %s - api call failed' % ('/accounts/images/v2/direct_upload', e, e))
128+
sys.exit('%s: %d %s - api call failed' % ('/accounts/images/v2/direct_upload', int(e), str(e)))
119129
print('v2 new image post results')
120130
print(json.dumps(r, indent=4))
121131

@@ -128,9 +138,9 @@ def doit(account_name, image_filename):
128138
# https://upload.videodelivery.net/f65014bc6ff5419ea86e7972a047ba22
129139

130140
try:
131-
r = requests.post(image_url, files={('file', image_fp) })
141+
r = requests.post(image_url, files={('file', image_fp)}, timeout=5)
132142
except Exception as e:
133-
exit('%s: %s - api call failed' % (image_url, e))
143+
sys.exit('%s: %s - api call failed' % (image_url, e))
134144

135145
image_fp.close()
136146

@@ -139,20 +149,20 @@ def doit(account_name, image_filename):
139149
print('403 means you need to enable images in your account')
140150
if r.status_code == 403:
141151
print('415 means the file is a bad image format')
142-
exit('%s: HTTP Error %s' % (image_url, r.status_code))
152+
sys.exit('%s: HTTP Error %s' % (image_url, r.status_code))
143153

144154
j = r.json()
145-
if j['success'] == True:
155+
if j['success'] is True:
146156
print('Image upload results')
147157
print(json.dumps(j['result'], indent=4))
148158
else:
149-
exit('Error:\n errors: %s\n messages: %s' % (image_url, j['errors'], j['messages']))
159+
sys.exit('Error:\n errors: %s\n messages: %s' % (j['errors'], j['messages']))
150160

151161
# list all images
152162
try:
153163
r = cf.accounts.images.v2(account_id)
154164
except CloudFlare.exceptions.CloudFlareAPIError as e:
155-
exit('%s: %d %s - api call failed' % ('/accounts/images/v1', e, e))
165+
sys.exit('%s: %d %s - api call failed' % ('/accounts/images/v1', int(e), str(e)))
156166

157167
print('All account images:')
158168
for img in r['images']:
@@ -167,21 +177,22 @@ def doit(account_name, image_filename):
167177
try:
168178
r = cf.accounts.images.v1.delete(account_id, image_id)
169179
except CloudFlare.exceptions.CloudFlareAPIError as e:
170-
exit('%s: %d %s - api call failed' % ('/accounts/images/v1', e, e))
180+
sys.exit('%s: %d %s - api call failed' % ('/accounts/images/v1', int(e), str(e)))
171181
print('Image delete')
172182
print(json.dumps(r, indent=4))
173183

174184
def main():
185+
""" main """
175186
try:
176187
account_name = sys.argv[1]
177188
except IndexError:
178-
exit('usage: example_images_v2_direct_upload.py account_name image_filename')
189+
sys.exit('usage: example_images_v2_direct_upload.py account_name image_filename')
179190
try:
180191
image_filename = sys.argv[2]
181192
except IndexError:
182-
exit('usage: example_images_v2_direct_upload.py account_name image_filename')
193+
sys.exit('usage: example_images_v2_direct_upload.py account_name image_filename')
183194
doit(account_name, image_filename)
184-
exit(0)
195+
sys.exit(0)
185196

186197
if __name__ == '__main__':
187198
main()

0 commit comments

Comments
 (0)