Page 1 of 1

Python3: adding a picture to the push notification

Posted: 26. Oct 2017, 14:52
by ElFred
Hi all,

For those who are using Pushsafer API with Python3, I can share this bit of help code here. Hope others find it useful as well!

Start by adding the "p" parameter to the post fields. Please note that the instructions on h T T ps://w W w.pushsafer.com/en/pushapi are not complete for this.

Code: Select all

from urllib.parse import urlencode
from urllib.request import Request, urlopen

url = 'https://www.pushsafer.com/api'
post_fields = {
	"t" : title,
	"m" : message,
	"s" : sound,
	"v" : vibration,
	"i" : icon,
	"c" : iconcolor,
	"d" : device,
	"u" : url,
	"ut" : urltitle,
	"p" : picture,
	"k" : private_key
	}
request = Request(url, urlencode(post_fields).encode())
json = urlopen(request).read().decode()
print(json)
Now, to get the correct string for "p", you can use this helper code.
Start by importing base64:

Code: Select all

import base64
The encoded string of your image file can then be fetched after opening the file. Enter the correct path to your picture under 'path_to_picture':

Code: Select all

with open(path_to_picture, 'rb') as image_file:
				
	encoded_string = base64.b64encode(image_file.read())
					
base64coded = encoded_string.decode('ascii')
Once we have the encoded data, we only need to add the data header:

Code: Select all

picture_base64 = 'data:image/jpeg;base64,' + base64coded
Now your post fields can be updated as:

"p" : picture_base64

That's it!

And a big thank you to the Pushsafer developers! Great work!!

Re: Python3: adding a picture to the push notification

Posted: 26. Oct 2017, 17:57
by admin
Thank you for sharing this :D

Kevin