Python, App Engine: Http Multipart Post To Vk.ads Api
I tried to sole this problem myself for a few days searching on examples and documentations, also it wasn't solved on ruSO. So, I hope that solution will be found here, on enSO. I
Solution 1:
After a lot of experiments and investigating of different HTTP requests content I found out the only difference between wrong and working code. It was about 4 bytes only: file name MUST contain the extension. Vk API even ignores Content-Type: image/png
, but needs .png
or similar in filename. So, this doesn't work:
requests.post(upload_url, files={
'file': BytesIO('<binary file content>')
})
But this option works properly:
requests.post(upload_url, files={
'file': ('file.png', BytesIO('<binary file content>'), 'image/png')
})
Just like this one, which is not available for GAE:
requests.post(upload_url, files={
'file': open('/path/to/image.png', 'rb')
})
Both StringIO
and StringIO
are appropriate for that task. As mentioned, Content-Type
does not matter, it can be just multipart/form-data
.
Solution 2:
Not sure if it can help, but I'll post it anyway
I used requests
to upload an image to ads
import requests
token = '***'
url = f'https://api.vk.com/method/ads.getUploadURL?access_token={token}&ad_format=1' # I set add_format randomly just to avoid an error of this parameter was missing
upload_url = requests.get(url).json()['response']
post_fields = {
'access_token': token
}
data_fields = {
'file': open('/path/to/image.png', 'rb')
}
response = requests.post(upload_url, data=post_fields, files=data_fields)
print(response.text)
The result looks like valid photo upload, the data received can be used in further actions with ad API.
Post a Comment for "Python, App Engine: Http Multipart Post To Vk.ads Api"