how to call the API from SkyBiometry in a python script - python

I am new at stackoverflow and to programming with python and I am trying to get an emotion analyses for images from my hard disk by using the service of skybiometry.com. The example link of them is like: "http://api.skybiometry.com/fc/faces/detect.json?api_key=aa754b54b37&api_secret=4b3a4c6d4c&urls=http://theweeklyworld.com/wp-content/uploads/2014/08/child-happy-face1.jpg&attributes=all" and I want to do this in my python-script with my image. On their website https://skybiometry.com/documentation/ on point 4.13 they said that the request has to be formed as a MIME if I want to analyze images from my hard disk. I do not know how to handle this. In an other project of mine I have done the request like this
import requests
auth_headers = {
'api_key': api_key,
'api_secret': api_secret,
}
url = 'http://api.skybiometry.com/fc/faces/detect'
files = { 'source': open(path + ".jpg", 'rb')
}
data = { 'timeout': 60
}
response = requests.post(url, files=files, data=data, headers=auth_headers)
print (response.json())
Can anyone help me to adjust this request to make it work?
Thanks a lot!

You need to change api_key and api_secret for your own skybiometry credentials to use that python script.
Anyway, I prefer installing the api client skybiometry first for python and then use your python scripts. To install it you need to follow these steps:
git clone git#github.com:SkyBiometry/python-face-client.git
cd python-face-client
python setup.py build
python setup.py install
Then you can use the api-client using import with your skybiometry credentials, for example:
from face_client import FaceClient
client = FaceClient('API_KEY', 'API_SECRET')
Changing the API_KEY and API_SECRET for your own skybiometry credentials.
For more examples and how to use the api-client, you can watch this: https://github.com/SkyBiometry/python-face-client
Greetings.

Related

Import cucumber test result with XRay API using Python

I'm trying to perform an import of a cucumber test with the Xray API on Python, to be more specific I'm trying to translate this curl on Python side (it's a multipart form) :
curl -u usr:pass -F info=#$xrayResultFilePath -F result=#$pathToCucumberJson $jiraUrl/rest/raven/1.0/import/execution/cucumber/multipart
I tried in many different ways the python code I'm stucked on looks something like this:
response = requests.post(
atc_xray_url,
auth=(creds.username, creds.password),
files={"info": open("cucumber.result.json", "rb"),
"result": open("xray_result.json", "rb")},
)
response.raise_for_status()
I also tried to change the tags, to add them in a tuple like I found on the internet, solutions found here, but no result everytime I get this error:
<status><status-code>404</status-code><message>null for uri:
The curl is working, but the Python code is not. I could use the subprocess library but this shoud be a multiplatform solution so if this could be done with a thing in Python, it would be nice.
This repository that I made available some time ago provides several code snippets, including one precisely for that use case.
Your code is similar to the following one though; you may use basic auth or personal auth tokens, if you have a Jira DC version >= 8.14.
Given the result code you obtain, the problem may be on the URL that you use, which is not clear whether it's the same or not that you have on your curl. Note that you can also use v2 of the endpoint, as I show ahead.
import requests
import json
jira_base_url = "http://192.168.56.102"
jira_username = "admin"
jira_password = "admin"
personal_access_token = "OTE0ODc2NDE2NTgxOnrhigwOreFoyNIA9lXTZaOcgbNY"
...
files = {
'result': ('cucumber.json', open(r'cucumber.json', 'rb')),
'info': ('info.json', json.dumps(info_json) )
}
# importing results using HTTP basic authentication
# response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', params=params, files=files, auth=(jira_username, jira_password))
# importing results using Personal Access Tokens
headers = {'Authorization': 'Bearer ' + personal_access_token}
response = requests.post(f'{jira_base_url}/rest/raven/2.0/import/execution/cucumber/multipart', files=files, headers=headers)

Retrieving Azure Active Directory and Local Accounts' Data

I'm creating an app that has to show data of an active directory (which is hosted in microsoft azure) i have been told, that this request of data is going to be accomplished by using the Microsoft Graph API through HTTP GET requests.
Apart from “checking” the active directory data in azure, my app has to be capable of read the local accounts’ permissions, so to acomplish that this wouldn’t be possible to be read from the active directory, which means that I will have to check in the computers itself. For that problem, I've been told that I have to do it through powershell programming (to retrieve data of the local accounts).
At the end my application has to run on AWS Lambda.
More than code i would like guys if you can give me an approach of what to use to get to the solution.
What I have done so far:
I created a python file with this code to connect to the microsoft graph API:
There I added a token to access to the graph API, but i couldn't succeed.
I obtained the token from here, that is supposed to be a sample token of microsoft. For now instead of running my app on AWS Lambda, im running it on pycharm.
My Code on python to access to Azure Active Directory:
import http.client, urllib.request, urllib.parse, urllib.error, base64
# OAuth2 is required to access this API. For more information visit: https://msdn.microsoft.com/en-us/office/office365/howto/common-app-authentication-tasks
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU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=='
}
params = urllib.parse.urlencode({
# Specify values for the following required parameters
'api-version': '1.6'})
try:
conn = http.client.HTTPSConnection('graph.windows.net')
# Specify values for path parameters (shown as {...}) and request body if needed
conn.request("GET", "/myorganization/groups/f795caea-121d-49c7-8ae6-a95623add8aa?%s" % params, "", headers)
response = conn.getresponse()
data = response.read()
print(data)
conn.close()
except Exception as e:
print("[Errno {0}] {1}".format(e.errno, e.strerror))
This is the error I get after executing my code:
C:\Users\Joan\PycharmProjects\Prueba\venv\Scripts\python.exe C:/Users/Joan/PycharmProjects/Prueba/GraphTest.py
b'{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2018-07-02T21:01:26","requestId":"c3429e83-9cee-4f79-bfa5-642aa8da482a","values":null}}'
Process finished with exit code 0
This section:
headers = {
'Authorization': 'Bearer' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
Requests an additional space between 'Bearer' and the token itself:
headers = {
'Authorization': 'Bearer ' 'EwAoA8l6BAAU7p9QDpi/D7xJLwsTgCg3TskyTaQAAXu71AU9f4aS4rOK5xoO/SU5HZKSXtCsDe0Pj7uSc5Ug008qTI+a9M1tBeKoTs7tHzhJNSKgk7pm5e8d3oGWXX5shyOG3cKSqgfwuNDnmmPDNDivwmi9kmKqWIC9OQRf8InpYXH7NdUYNwN+jljffvNTewdZz42VPrvqoMH7hSxiG7A1h8leOv4F3Ek/oeJX6U8nnL9nJ5pHLVuPWD0aNnTPTJD8Y4oQTp5zLhDIIfaJCaGcQperULVF7K6yX8MhHxIBwek418rKIp11om0SWBXOYSGOM0rNNN59qNiKwLNK+MPUf7ObcRBN5I5vg8jB7IMoz66jrNmT2uiWCyI8MmYDZgAACPoaZ9REyqke+AE1/x1ZX0w7OamUexKF8YGZiw+cDpT/BP1GsONnwI4a8M7HsBtDgZPRd6/Hfqlq3HE2xLuhYX8bAc1MUr0gP9KuH6HDQNlIV4KaRZWxyRo1wmKHOF5G5wTHrtxg8tnXylMc1PKOtaXIU4JJZ1l4x/7FwhPmg9M86PBPWr5zwUj2CVXC7wWlL/6M89Mlh8yXESMO3AIuAmEMKjqauPrgi9hAdI2oqnLZWCRL9gcHBida1y0DTXQhcwMv1ORrk65VFHtVgYAegrxu3NDoJiDyVaPZxDwTYRGjPII3va8GALAMVy5xou2ikzRvJjW7Gm3XoaqJCTCExN4m5i/Dqc81Gr4uT7OaeypYTUjnwCh7aMhsOTDJehefzjXhlkn//2eik+NivKx/BTJBEdT6MR97Wh/ns/VcK7QTmbjwbU2cwLngT7Ylq+uzhx54R9JMaSLhnw+/nIrcVkG77Hi3neShKeZmnl5DC9PuwIbtNvVge3Q+V0ws2zsL3z7ndz4tTMYFdvR/XbrnbEErTDLWrV6Lc3JHQMs0bYUyTBg5dThwCiuZ1evaT6BlMMLuSCVxdBGzXTBcvGwihFzZbyNoX+52DS5x+RbIEvd6KWOpQ6Ni+1GAawHDdNUiQTQFXRxLSHfc9fh7hE4qcD7PqHGsykYj7A0XqHCjbKKgWSkcAg=='
}
I'm assuming this is just some scratch POC code but, just in case, keep in mind that your token will expire after 1hr so hardcoding it like this doesn't make sense. You'll want to fetch a new token as needed and inject it into the header when making the call.

How to upload image to imgur as a specific user?

I am trying to upload images to imgur, and I found the way to do it below:
img = requests.post(
'https://api.imgur.com/3/upload.json',
headers = {'Authorization': 'Client-ID <my client-id>'},
data = {
'key': '<my secret key>',
'title': 'test'
'image': <path to image>
}
)
j = json.loads(img.text)
print j
Imgur API for image upload: https://api.imgur.com/endpoints/image#image-upload
This works fine, but I want to be able to upload the images as a user. Where do I put my username and password?
You'll need to authenticate your requests to imgur via oauth2. The account that is used to authenticate will be the account that does the uploads.
A full description of oauth is a bit beyond the scope of this answer, but in short, you're using the right http library in requests because it is often simpler than other approaches.
I like requests-oauthlib library which is recommended by requests. It works well with twitter's api too.
I should also note that imgur has a sample python app called imgur-python. Check out main.py for a bit more of a lead on things.

Python Uploading Files using Requests. Server running PHP

i have this situation where in i am uploading files to a server using Python. here is my python script. this uses apache2 certified requests library
def Upload(self):
Url = 'http://x.php'
Payload = {
'Location' : self.Location,
'Version' : self.Version,
'Variant' : self.Variant,
}
#employing requests
File = {'file' : ('TestFile', open(self.Location, 'rb'))}
response = requests.post(Url, files=File, data=Payload)
The data is received by an apache2 server running on ubuntu machine. I would want to know how to access the sent file from the PHP code and save it in the desired location. Can you please suggest the way to achieve this.
Is there any way like HTTP, where i can specify the that this is like so, i can access using $_FILE["TestFile"]
Please help
-sreekanth

Python 3 script to upload a file to a REST URL (multipart request)

I am fairly new to Python and using Python 3.2. I am trying to write a python script that will pick a file from user machine (such as an image file) and submit it to a server using REST based invocation. The Python script should invoke a REST URL and submit the file when the script is called.
This is similar to multipart POST that is done by browser when uploading a file; but here I want to do it through Python script.
If possible do not want to add any external libraries to Python and would like to keep it fairly simple python script using the core Python install.
Can some one guide me? or share some script example that achieve what I want?
Requests library is what you need. You can install with pip install requests.
http://docs.python-requests.org/en/latest/user/quickstart/#post-a-multipart-encoded-file
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)
A RESTful way to upload an image would be to use PUT request if you know what the image url is:
#!/usr/bin/env python3
import http.client
h = http.client.HTTPConnection('example.com')
h.request('PUT', '/file/pic.jpg', open('pic.jpg', 'rb'))
print(h.getresponse().read())
upload_docs.py contains an example how to upload a file as multipart/form-data with basic http authentication. It supports both Python 2.x and Python 3.
You could use also requests to post files as a multipart/form-data:
#!/usr/bin/env python3
import requests
response = requests.post('http://httpbin.org/post',
files={'file': open('filename','rb')})
print(response.content)
You can also use unirest . Sample code
import unirest
# consume async post request
def consumePOSTRequestSync():
params = {'test1':'param1','test2':'param2'}
# we need to pass a dummy variable which is open method
# actually unirest does not provide variable to shift between
# application-x-www-form-urlencoded and
# multipart/form-data
params['dummy'] = open('dummy.txt', 'r')
url = 'http://httpbin.org/post'
headers = {"Accept": "application/json"}
# call get service with headers and params
response = unirest.post(url, headers = headers,params = params)
print "code:"+ str(response.code)
print "******************"
print "headers:"+ str(response.headers)
print "******************"
print "body:"+ str(response.body)
print "******************"
print "raw_body:"+ str(response.raw_body)
# post sync request multipart/form-data
consumePOSTRequestSync()
You can check out this post http://stackandqueue.com/?p=57 for more details

Categories