I have a code which which fetches company logos from clearbit API. Please find the code below:
url = "https://logo.clearbit.com/shopify.com"
payload={}
headers = {}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
I need to render it as an image instead of text. Please help me
An image is binary data. You will find the following solution in the documentation.
url = 'https://logo.clearbit.com/shopify.com'
resp = requests.get(url)
resp.raise_for_status()
data = resp.content
Related
I am sending a file as an object via postman POST or PUT API like below:
How can I in Python -
get this file object
read and save
If you have a working request in Postman, you could copy autogenerated Code Snippet in Python - Requests format:
It might look like this:
import requests
url = "localhost:8080"
payload="<file contents here>"
headers = {
'Content-Type': 'application/octet-stream'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
Answer to this question which i finally implemented without url -
#app.route('/uploadFIle', methods=['PUT'])
def uploadFile():
chunk_size = 4096
with open("/Users/xyz/Documents/filename", 'wb') as f:
while True:
chunk = request.stream.read(chunk_size)
if len(chunk) == 0:
break
f.write(chunk)
return jsonify({"success":"File transfer initiated"})
I am attempting to use a local image in my text recognition script, the documentation has the following example (https://learn.microsoft.com/en-us/azure/cognitive-services/computer-vision/quickstarts/python-hand-text):
But when I change the image_url to a local file path, it sends a HTTPError: 400 Client Error: Bad Request for url. I have tried following other tutorials but nothing seems to work.
Any help would be greatly appreciated :)
The Cognitive services API will not be able to locate an image via the URL of a file on your local machine. Instead you can call the same endpoint with the binary data of your image in the body of the request.
Replace the following lines in the sample Python code
image_url = "https://raw.githubusercontent.com/MicrosoftDocs/azure-docs/master/articles/cognitive-services/Computer-vision/Images/readsample.jpg"
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
data = {'url': image_url}
response = requests.post(
text_recognition_url, headers=headers, json=data)
with
headers = {'Ocp-Apim-Subscription-Key': subscription_key,'Content-Type': 'application/octet-stream'}
with open('YOUR_LOCAL_IMAGE_FILE', 'rb') as f:
data = f.read()
response = requests.post(
text_recognition_url, headers=headers, data=data)
And replace the following line:
image = Image.open(BytesIO(requests.get(image_url).content))
with
image = Image.open('./YOUR_LOCAL_IMAGE_FILE.png')
I've tried to do a POST request using python's request library, which looked something like below:
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url,data='Datasets/rtHereTest.csv')
The response I've been getting a code 400
{'faultCode': '16a6f70f-1fa3-4b57-9ef3-a0a440f8a42e',
'responseCode': '400 Bad Request',
'message': 'Column LATITUDE missing'}
However, in my dataset, here I have all the headings that's required from the HERE API documentation to be able to make a call.
Is there something I'm doing wrong, I don't quite understand the POST call or the requirement as the HERE documentation doesn't explicitly give many examples.
The data field of your post request should contain the actual data, not just a filename. Try loading the file first:
f = open('Datasets/rtHereTest.csv', 'r')
url = "https://rme.api.here.com/2/matchroute.json?routemode=car&filetype=CSV&app_id={id}&app_code={code}"
response = requests.post(url, data=f.read())
f.close()
Here's what I use in my own code, with the coordinates defined before:
query = 'https://rme.api.here.com/2/matchroute.json?routemode=car&app_id={id}&app_code={code}'.format(id=app_id, code=app_code)
coord_strings = ['{:.5f},{:.5f}'.format(coord[0], coord[1]) for coord in coords]
data = 'latitude,longitude\n' + '\n'.join(coord_strings)
result = requests.post(query, data=data)
You can try to post the data using below format.
import requests
url = "https://rme.api.here.com/2/matchroute.json"
querystring = {"routemode":"car","app_id":"{app_id}","app_code":"{app_code}","filetype":"CSV"}
data=open('path of CSV file','r')
headers = {'Content-Type': "Content-Type: text/csv;charset=utf-8",
'Accept-Encoding': "gzip, deflate",
}
response = requests.request("POST", url, data=data.read().encode('utf-8'), params=querystring,headers=headers)
print(response.status_code)
I need to upload a local picture to an URL.
My curl request looks like : "curl -T 'my_picture' 'the_url' ".
My purpose is to do it in Python, I saw, that I have to use : requests.put().
Everything I did before works nice, but this function give me a lot of trouble.
Solution is probably really easy, but I'm lost.
Thanks for any help.
def apithree(urlupload):
url = urlupload
picture = Image.open("test.png")
headers = {"content-type": "multipart/form-data"}
response = requests.put(url, headers=headers, data=picture)
response = response.json()
print(response)
Other Code I tried
def apithree(urlupload):
url = urlupload
files = {'image': open('test.png', 'rb')}
response = requests.post(url, data=files)
response = response.json()
print(response)
If the command works,the output should be empty, but I always have error messages.
I can add error messages if necessary.
Thanks for any help.
If server accepts multipart/form-data images, you probably need files= parameter for your request:
import requests
files = {'file_name': open(r'C:\data\...\image.png', 'rb')}
r = requests.post(YOUR_URL, files=files) # or requests.put(...)
print(r.status_code, r.json())
I have successfully used the requests module to upload a binary file (jpg), with something like the following:
upload_url = 'http:10.1.1.1:8080/api/media/photo'
headers = {'Authorization': token_string, 'Content-Type': 'image/jpg'}
data = open('photo.JPG', 'rb')
params = {'name': 'photo.JPG'}
r = requests.post(upload_url, params=params, data=data, headers=headers)
Now trying to do this with aiohttp client. This is what I have so far:
def upload_photos(token):
upload_url = '10.0.1.1:8080/api/media/photo'
headers = {'Authorization': token, 'Content-Type': 'image/jpg'}
data = {'file': open('photo.JPG', 'rb')}
params = {'name': 'photo.JPG'}
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers)
if __name__ == '__main__':
asyncio.get_event_loop().run_until_complete(upload_photos(token))
But I am getting a 400 back, with {"detail": "Specified value is invalid: Invalid Content-Length specified"}.
It's as if it's not properly sending the photo.jpg. The aiohttp docs mentione multi-part encoded files and streaming, but that's not whant I want here.
How do I form a similar POST w/ binary file like in requests, but with aiohttp?
Thank you for a bug report. As workaround I guess to use chunked transfer encoding:
headers['Transfer-Encoding'] = 'chunked'
r = yield from aiohttp.request('post', upload_url, params=params, data=data, headers=headers, chunked=1024)
The recipe should work, at least we have very simular code in our test suite: https://github.com/KeepSafe/aiohttp/blob/master/tests/test_client_functional.py#L322
I'll try to fix Content-Length calculation for your uploading way in next aiohttp release.