Would like to access orion data using a python script (not using curlor Postman). Below show the python script in my orion.pyscript:
import json
import requests
orion_endpoint="some-endpoint"
url_query=("orion_url" % (orion_endpoint))
body_dict = {
'entities': [
{
'type': 'AirQualityObserved',
'idPattern': '.*',
}
],
}
r_headers = {'Content-Type': 'application/json'}
#print(data["coordinates"][0][0])
r = requests.post(
url=url_query,
data=json.dumps(body_dict),
headers=r_headers
)
print(r.content)
Running this script dumps the entity information to the console. How do I use the script to subscribe for notification so I get notified (not just dumping context)?
Orion Context Broker implements a REST API so any programming language able to do HTTP requests (and Python is one of them, e.g. using the requests module) can be used.
To create a subscription you can use the same requests.post() you are using but with a different parametrization. In particular:
url will be the one corresponding to subscritions recourses in the API, i.e. /v2/entities.
data should follow the syntax of a subscription, according to the "Subscriptions" section in the NGSIv2 specification.
headers can be the same.
In the case it may help, this script shows how to create subscriptions in Python.
Related
AM currently writing a rest api python script to interact with azure devops and I wanted to create a work item but am getting 401 or 404 errors. I followed the url query to do a post but I seem not to find the solution.
You can refer this official Azure DevOps Python API doc.
It contains Python APIs for interacting with and managing Azure
DevOps. These APIs power the Azure DevOps Extension for Azure CLI. To
learn more about the Azure DevOps Extension for Azure CLI, visit the
Microsoft/azure-devops-cli-extension repo.
Here is some example code for creating work item in python.
Besides, it is supported to use requests to call Azure DevOps REST API. In this way, you need to create a personal access token (PAT) first. (Make sure you select the correct scope, in your scenario at least have the create work item permission).
Then you can use the PAT to create the basic auth header, and make the request:
import requests
import base64
pat = 'tcd******************************tnq'
authorization = str(base64.b64encode(bytes(':'+pat, 'ascii')), 'ascii')
headers = {
'Accept': 'application/json-patch+json',
'Authorization': 'Basic '+authorization
}
url = "https://dev.azure.com/fabrikam/{project}/_apis/wit/workitems/${type}?api-version=6.0"
payload = "[\n {\n \"op\": \"add\",\n \"path\": \"\/fields\/System.Title\",\n \"from\": null,\n \"value\": \"Sample task\"\n }\n]"
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
i have this python scriptt that allows me to to make an api call to a url very easily . if i try the same thing with groovy it is not working .. Tried many things but still failing .
I am very noob in groovy but i need an alternative to below python api call which can be easily called from jenkins pipeline
token = 'xxxx-yyy-zzz-aaa'
headers = {'Authorization': "some-name%s" % token}
tar_endpoint = 'https://abc#hello.com'
r = requests.post(tar_endpoint, data=json.dumps(som_json_payload), headers=headers)
The code snippet below should do the job for you
def post = new URL("url_goes_here").openConnection();
def message = '{"message":"this is the data we want to post"}'
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
// add more headers if needed
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(200)) {
println(post.getInputStream().getText());
}
Have you eliminated using any of the plugins that might support this?
HTTP Post
HTTP Request
Pipeline: Groovy HTTP
Pipeline: REST API
REST List Parameter
That's the thing w/Jenkins, most of the time, "there's a plugin fot that", you just need to be able to find it.
I am using the Requests python module to do RESTFUL POST API calls to create a new item.
PROBLEM: Items are being duplicated. Sometimes 3 of each item get created. No check for existing data is in place in the final api prevent duplication.
GOAL: I want to send data to create a single new item in a third party application called Netbox which is made with Django.
WHAT HAVE I DONE?:
I have tried writing code to check for existing items and it still
makes duplicates.
I have tried set a timer to pause execution of code by 10 seconds until the request is complete.
The process flow looks like this:
Python Backend (Flask) ---> Python Backend (Flask) --> Netbox (Django)
Data Origin sent via Requests ---> Data Netbox Calls (Via PyNetBox) --> Final DataStore
The two backends are hosted in Cloud Foundry while Netbox is spun up on a Linux on Prem Server.
I have a dictionary like below that represents each item I need to create in Netbox.
Ex. payload = {'site':'1', 'device':'switch01'}
I send each piece of data to my middleware backend via a loop to make the final api call to netbox via pynetbox. I am not able to hit netbox directly.
for payload in payloads:
URL = f'{MIDDLEWARE_URL}/netbox/create_item'
print(f'URL is: {URL} | Payload is {payload}')
headers = { 'content-type': 'application/json', 'cache-control': "no-cache"}
proxies={'http' : None, 'https': None}
r = requests.post(URL, data=json.dumps(payload), headers=headers, verify=False, proxies=proxies)
I would appreciate any help as to why this is happening and any best practices to improving my baseline code logic.
All the best,
Faraz
So I figured it out after some more research and it turns out flask was creating two processes and therefore running my functions twice each time.
This was due to debug being true so used this:
app.run(debug=True, use_reloader=False)
Trying to set up a spreadsheet to take in data via an http post. To test it, I set up a simple python script to just send an http request. I dont want to use a specific google api on python or somewhere else, because I want some other people to be able to simply send a request how they would like. So, In my google script I just have:
function doPost(e){
sheet = SpreadsheetApp.getActiveSheet();
range = sheet.getRange(1, 1)
ange.setValue(e.text)
}
In python I simply have:
import requests
if __name__== "__main__":
params = {'Authorization': "Bearer [token]",
'contentType': 'application/json',
'text': "is working?"}
r = requests.post("https://script.google.com/macros/s/[uniquekey]/exec", params)
print(r.status_code, r.reason)
All I get is
"401 Unauthorized"
I've also tried sending this over python as well as running JS in a webserver and through chrome (which i guessed raised security issues). everything gave me the same response. I'm sure I'm just not authorizing properly, but I havent been able to find the correct way to do it. thanks in advance. I'm sure theres some other issues too, but I cant seem to even get access.
How about this modification?
Modified script:
In this modified script supposes as follows.
Web Apps is deployed as
Execute the app as is Me
Who has access to the app is Only myself or Anyone
Your access token can be used for accessing to your Web Apps.
If your access token cannot be used for it, please try to set the Web Apps as follows.
- Execute the app as is Me
- Who has access to the app is Anyone, even anonymous
- In this setting, you can access to Web Apps without the access token.
Python:
import requests
if __name__== "__main__":
params = {
'text': "is working?",
}
headers = {
'Authorization': "Bearer [token]",
}
r = requests.post("https://script.google.com/macros/s/[uniquekey]/exec", data=params, headers=headers)
print(r.status_code, r.reason)
Note:
Please put the access token to the header.
Google Apps Script:
When you modified your script, please redeploy as new version. By this, the latest script is reflected to the Web Apps.
function doPost(e) {
const sheet = SpreadsheetApp.getActiveSheet();
const range = sheet.getRange(1, 1);
range.setValue(e.parameter.text);
return ContentService.createTextOutput("Done.");
}
Note:
By returning ContentService.createTextOutput(), Web Apps returns the status code of 200.
You can retrieve the value of 'text': "is working?" as e.parameter.text.
When you use SpreadsheetApp.getActiveSheet(), the value of e.parameter.text is put to the 1st page of Spreadsheet.
References:
Web Apps
ContentService
In my environment, I could confirm that this modification worked. But if in your environment, this modified scripts didn't work, I'm sorry.
I am trying to retrieve the access token for the Yahoo API, using the explicit grant flow as described in this document:
https://developer.yahoo.com/oauth2/guide/flows_authcode
Everything is fine until Step 4: Exchange authorization code for Access Token
I wrote the following python script to retrieve the code:
import urllib2
import requests
import json
url = 'https://api.login.yahoo.com/oauth2/get_token'
body = "grant_type=authorization_code&redirect_uri=oob&code=************"
headers = {
'Authorization': 'Basic **************',
'Content-Type': 'application/json'
}
r = requests.post(url, data=body, headers=headers)
print r
Note: I replaced sensitive data with "****"
Now, when I execute the script, I only get the "401" error message.
I am 100% sure that the login credentials are fine, so it seems to be related to the way I make the request. It's also the first time that I am using "requests" in python.
Would be great, if you could give me some feedback on the code, and if I am passing the header and body information correctly. I am especially unsure about the passing of the body. The documentation only states the following:
Sample Request Body: grant_type=authorization_code&redirect_uri=https%3A%2F%2Fwww.example.com&code=abcdef
Change your body variable to a dict, i.e.,
body = {
'grant_type': 'authorization_code',
'redirect_uri': 'oob',
'code': '************',
}
No other changes are needed. Hope it helps.
Tough the problem already solved. But may be other user can still get the same 401 error even if they use correct dict as me. The problem is that the code generated in step 2 in the link can be only use ONCE. And this will get the same 401 error. This took me some time to figure it out. Hope this helps others.