Skip to content
This repository has been archived by the owner on May 7, 2024. It is now read-only.

Commit

Permalink
improved date/time rfc/iso code, lint fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
mahtin committed Feb 22, 2024
1 parent 9dca32b commit c5a5587
Show file tree
Hide file tree
Showing 4 changed files with 57 additions and 44 deletions.
18 changes: 8 additions & 10 deletions CloudFlare/tests/test_graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@

import os
import sys
import time
import random
import datetime
import pytz
import json

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

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

def test_graphql_get():
""" /graphql_get test """
Expand Down Expand Up @@ -129,8 +127,8 @@ def test_graphql_post_empty():

def test_graphql_post():
""" /graphql_post test """
date_before = now_iso8601_time(0) # now
date_after = now_iso8601_time(3 * 24) # 3 days worth
date_before = rfc3339_iso8601_time(0) # now
date_after = rfc3339_iso8601_time(-3 * 24) # 3 days worth

query = """
query {
Expand Down
9 changes: 8 additions & 1 deletion CloudFlare/tests/test_images_v2_direct_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@

cf = None

def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
if with_hms:
return dt.isoformat().replace('+00:00', 'Z')
return dt.strftime('%Y-%m-%d')

def test_cloudflare(debug=False):
""" test_cloudflare """
global cf
Expand Down Expand Up @@ -52,7 +59,7 @@ def test_find_account(find_name=None):
})

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

def test_images_v2_direct_upload():
""" test_images_v2_direct_upload """
Expand Down
33 changes: 15 additions & 18 deletions examples/example_graphql.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,18 @@

import os
import sys
import time
import datetime
import pytz

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

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

def main():
"""Cloudflare API code - example"""
Expand All @@ -25,20 +24,18 @@ def main():
zone_name = sys.argv[1]
params = {'name':zone_name, 'per_page':1}
except IndexError:
exit('usage: example_graphql zone')
sys.exit('usage: example_graphql zone')

cf = CloudFlare.CloudFlare()

# grab the zone identifier
try:
zones = cf.zones.get(params=params)
except CloudFlare.exceptions.CloudFlareAPIError as e:
exit('/zones.get %d %s - api call failed' % (e, e))
except Exception as e:
exit('/zones - %s - api call failed' % (e))
sys.exit('/zones.get %d %s - api call failed' % (int(e), str(e)))

date_before = now_iso8601_time(0) # now
date_after = now_iso8601_time(7 * 24) # 7 days worth
date_before = rfc3339_iso8601_time(0) # now
date_after = rfc3339_iso8601_time(-7 * 24) # 7 previous days worth

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

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

httpRequests1dGroups = zone_info['httpRequests1dGroups']
http_requests1d_groups = zone_info['httpRequests1dGroups']

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

if __name__ == '__main__':
main()
exit(0)
sys.exit(0)
41 changes: 26 additions & 15 deletions examples/example_images_v2_direct_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,16 @@
# released between then require at-least one paramater send via files= in order to not trigger a backend API bug
#

def rfc3339_iso8601_time(hour_delta=0, with_hms=False):
""" rfc3339_iso8601_time """
# format time (with an hour offset in RFC3339 ISO8601 format (and do it UTC time)
dt = (datetime.datetime.now(datetime.UTC).replace(microsecond=0) + datetime.timedelta(hours=hour_delta))
if with_hms:
return dt.isoformat().replace('+00:00', 'Z')
return dt.strftime('%Y-%m-%d')

def method_from_library_version():
""" method_from_library_version """
if CloudFlare.__version__ <= '2.14.2':
print('Using %s version of Cloudflare python library - hence do not need data= or files=; but use files= if passing anything' % (CloudFlare.__version__))
return ''
Expand All @@ -44,6 +53,7 @@ def method_from_library_version():
return 'USE-DATA'

def doit(account_name, image_filename):
""" doit """

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

try:
image_fp = open(image_filename, 'rb')
except Exception as e:
exit('%s: %s - file read failed' % (image_filename, e))
sys.exit('%s: %s - file read failed' % (image_filename, e))

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

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

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

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

try:
r = requests.post(image_url, files={('file', image_fp) })
r = requests.post(image_url, files={('file', image_fp)}, timeout=5)
except Exception as e:
exit('%s: %s - api call failed' % (image_url, e))
sys.exit('%s: %s - api call failed' % (image_url, e))

image_fp.close()

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

j = r.json()
if j['success'] == True:
if j['success'] is True:
print('Image upload results')
print(json.dumps(j['result'], indent=4))
else:
exit('Error:\n errors: %s\n messages: %s' % (image_url, j['errors'], j['messages']))
sys.exit('Error:\n errors: %s\n messages: %s' % (j['errors'], j['messages']))

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

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

def main():
""" main """
try:
account_name = sys.argv[1]
except IndexError:
exit('usage: example_images_v2_direct_upload.py account_name image_filename')
sys.exit('usage: example_images_v2_direct_upload.py account_name image_filename')
try:
image_filename = sys.argv[2]
except IndexError:
exit('usage: example_images_v2_direct_upload.py account_name image_filename')
sys.exit('usage: example_images_v2_direct_upload.py account_name image_filename')
doit(account_name, image_filename)
exit(0)
sys.exit(0)

if __name__ == '__main__':
main()

0 comments on commit c5a5587

Please sign in to comment.