Twitter media/upload image by its web url - python-2.7

I followed the steps in media/upload. I wrote this function in python
def upload_media(self,access_token,image_url):
client = self.get_client(access_token)
message = {'media' : image_url}
encoded_status = urllib.urlencode(message)
url = "https://upload.twitter.com/1.1/media/upload.json?"+ encoded_status
resp, content = client.request(url,'post')
return content
And I got this :
{"request":"\/1.1\/media\/upload.json","error":"media type unrecognized."}

As far as I can tell, the error is in trying to upload a URL. The Twitter API requires you to upload a base64-encoded image.
See: https://dev.twitter.com/rest/reference/post/media/upload
So instead of the image's URL, it should be the file content:
with open('example.jpg', 'rb') as f:
data = f.read()
message = {'media':data}
Optionally (I still haven't figured out whether this is required or not, as different people give different answers), you could encode the image in base-64 encoding:
with open('example.jpg', 'rb') as f:
data = f.read()
data = data.encode('base64')
message = {'media':data}

Related

Graph API issue while Instagram Video Posting - Media upload has failed with error code 2207026"

My program is working perfectly fine when I try to upload Pictures through graph API on Instagram.
But when I try to upload videos through graph API it gives this error
{"id":"17907424258891270","status":"Error: Media upload has failed with error code 2207026","status_code":"ERROR"}
Loop Continue y/n-> n
{"error":{"message":"The video file you selected is in a format that we don't support.","type":"OAuthException","code":352,"error_subcode":2207026,"is_transient":false,"error_user_title":"Unsupported format","error_user_msg":"The video format is not supported. Please check spec for supported streams format","fbtrace_id":"AfZ_9eCYSY3iJ6g0QRX0bM-"}}
I have tried different video formats. Tried videos with different codecs too. Have also tried publicly accessible videos and local videos too but I am having the same error
Here is my code
def uploadToInstagram(ig_user_id,access_token,video_url,caption=""):
url1 = "https://graph.facebook.com/v11.0/"+str(ig_user_id)+ "/media?caption=" +caption+"&video_url="+ video_url+ "&media_type=VIDEO&access_token="+ access_token
r = requests.post(url1)
print(r.text)
creation_id = json.loads(r.text)['id']
print(creation_id)
while True:
x = input("Loop Continue y/n-> ")
if x == "n":
break
else:
pass
url3 = "https://graph.facebook.com/v11.0/" +creation_id+"?fields=id,status,status_code&access_token="+ access_token
status_check = requests.get(url3)
print(status_check.text)
#status_code = json.loads(status_check.text)["status_code"]
url2 = "https://graph.facebook.com/v11.0/" +str(ig_user_id)+"/media_publish?creation_id="+ creation_id+"&access_token="+access_token
r = requests.post(url2)
print(r.text)
if __name__ == "__main__":
#video_path = "https://pixabay.com/videos/download/video-4006_large.mp4?attachment"
#Check this one v
video_path ='https://player.vimeo.com/external/176282263.hd.mp4?s=5ae9c441e89ee36646286c22fddc6c8781946c7d&profile_id=169'
#video_path ="1000_general_Fall.mp4"
video_path="https://vod-progressive.akamaized.net/exp=1625867691~acl=%2Fvimeo-prod-skyfire-std-us%2F01%2F256%2F7%2F176282263%2F572345167.mp4~hmac=e4378a5d76e659bd11289e1b3dcfe7bb95eaf0b20de9cbb22c9b5ed1b418100d/vimeo-prod-skyfire-std-us/01/256/7/176282263/572345167.mp4?filename=Sea+-+4006.mp4"
enter code here

What encoding does blob.download_as_string() return?

I am downloading a file from Google Storage as a byte string, b64 encoding it, and using that as input into the Google Vision API.
storage_client = storage.Client(project=[PROJECT])
bucket = storage_client.get_bucket([BUCKET])
blob = bucket.blob([KEY])
content = blob.download_as_string()
b64content = base64.b64encode(content)
client = vision.ImageAnnotatorClient()
image = vision.types.Image(content=b64content)
I am getting a bad image error using the b64content. However, if I use the non base64 content, my call to the Vision API succeeds:
image = vision.types.Image(content=content)
Does blob.download_as_string() return a byte string that is already base64 encoded?
Short answer: no, it is not base64 encoded. Then why does it work with the non-encoded string?
Using the Python Client as you do, you don't need to encode the string, as seen here. You need to encode it if you post a Vision API request in JSON, like this one. This is why you get it working already without base64.b64encode().

How to make a request to get minimum data from server?

I want to make a HTTP request, so that I get minimum data from the server. For eg : If the user device is a mobile, the server will send less data.
I was doing this in python ::
req = urllib2.Request(__url, headers={'User-Agent' : "Magic Browser"})
html = urllib2.urlopen(req).read()
But it still takes some time to download all this.
If it helps this is the domain from which I want to download pages : https://in.bookmyshow.com
Is there any other way so that I can download a page, quickly with minimum data? Is it even possible?
you can use request for upload files get datas example for get cookies:
import requests
r = requests.get('https://in.bookmyshow.com')
print r.cookies.get_dict()
or for upload file:
import requests
file = {'file':('filename.txt', open('filename.txt', 'r'), multipart/from-data)}
data = {
"ButtonValueNameInHtml" : "Submit",
}
r = requests.post('https://in.bookmyshow.com', files=file, data=data)
replace in.bookmyshow.com by your own url
you can do many Thigs With requests

Django Rest Framework - Unit test image file upload

I am trying to unit test my file uploading REST API. I found online some code generating the image with Pillow but it can't be serialized.
This is my code for generating the image :
image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0))
file = BytesIO(image.tobytes())
file.name = 'test.png'
file.seek(0)
Then I try to upload this image fille :
return self.client.post("/api/images/", data=json.dumps({
"image": file,
"item": 1
}), content_type="application/json", format='multipart')
And I get the following error:
<ContentFile: Raw content> is not JSON serializable
How can I transform the Pillow image so it's serializable?
I wouldn't recommend submitting your data as JSON in this case, as it complicates the issue. Just make a POST request with the parameters and files you want to submit. Django REST Framework will handle it just fine without you needing to serialise it as JSON.
I wrote a test for uploading a file to an API endpoint a while back which looked like this:
def test_post_photo(self):
"""
Test trying to add a photo
"""
# Create an album
album = AlbumFactory(owner=self.user)
# Log user in
self.client.login(username=self.user.username, password='password')
# Create image
image = Image.new('RGB', (100, 100))
tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')
image.save(tmp_file)
# Send data
with open(tmp_file.name, 'rb') as data:
response = self.client.post(reverse('photo-list'), {'album': 'http://testserver/api/albums/' + album.pk, 'image': data}, format='multipart')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
In this case, I used the tempfile module to store an image generated using Pillow. The with syntax used in the example allows you to pass the content of the file in the request body comparatively easily.
Based on this, something like this should work for your use case:
image = Image.new('RGBA', size=(50, 50), color=(155, 0, 0))
file = tempfile.NamedTemporaryFile(suffix='.png')
image.save(file)
with open(file.name, 'rb') as data:
return self.client.post("/api/images/", {"image": data, "item": 1}, format='multipart')
Incidentally, depending on your use case it might be more convenient to accept the image data as a base 64 encoded string.
You converted the file to bytes, which is not JSON serializable.
Without knowing what your API expects to receive, I'll have to take a guess that you have to encode file as a string: "image": file.decode('utf-8').
While there are many solutions to your general issue of unit testing image uploads to a REST API

Uploading file Webservice

I'm trying to upload a file into my web service (written using DJango REST framework). I have written the following code but I get data can not be converted to utf-8 error
with open('/images/img.jpg', 'rb') as imgFile:
content = imgFile.read ()
json = { 'fileName': 'img.jpg', 'img': content}
json_data = simplejson.dumps(json)
reqURL = urllib2.Request("http://localhost:8000/uploadfile/",json_data)
opener = urllib2.build_opener()
f = opener.open(reqURL)
What is the right way of passing file content over JSON?
You don't send files like this. File contents are sent by embedding them inside the request body.
You may be better of by using the beautiful python-request library. Check out the file upload section.