How can I get "assignments" key of the incidents in PagerDuty? I have a python script which returns info on particular incident, but the list with assignments is empty.
#!/usr/bin/env python
import requests
import json
API_KEY = 'iiiiiiiiiiiiiiiiii'
# incident ID
ID = 'PPPPP'
def get_incident():
url = 'https://api.pagerduty.com/incidents/{id}'.format(id=ID)
headers = {
'Accept': 'application/vnd.pagerduty+json;version=2',
'Authorization': 'Token token={token}'.format(token=API_KEY)
}
params = {
'include': 'assignees',
'time_zone': 'Europe/Sofia'
}
r = requests.get(url, headers=headers,data=json.dumps(params))
print ('Status Code: {code}'.format(code=r.status_code))
print (r.json())
if __name__ == '__main__':
get_incident()
In their documentation here there are entries for that key, see on the picture bellow:
How can I achieve that?
Based on experimentation, it appears that assignments are only populated while an incident is still active. I just queried /incidents/id for an incident in the triggered state and in the resolved state, the triggered one shows an assignment while the resolved one does not.
It's kind of frustrating, because I want to look at the LogEntrys for an incident via their API and I haven't figured that out yet.
The alert_counts field always seems to contain zeros too, which doesn't make any sense.
Related
I'm working with Python 3.x
Previously, I had a function to create tickets that looks like this
def jira_incident(jira_subject, jira_description):
user = "username"
apikey = 'apikey'
server = 'https://serverName.atlassian.net'
options = {
'server': server,
'verify': False
}
issue_dict = {
'project': {'key': 'project_name'},
'summary': str(jira_subject),
'description': str(jira_description),
'issuetype': {'name': 'Incident'},
'assignee': {'name': my_username},
'priority': {'name': 'Low'},
'customfield_10125':
{'value': 'Application Ops'}
}
jira = JIRA(options, basic_auth=(user, apikey))
new_issue = jira.create_issue(fields=issue_dict)
return new_issue
my_username is a global variable that's used for other things as well.
Anyway, the assignee is no longer working as of about 2 days ago. I did some googling and found that it now needs the accountId instead of the name, I can get this via the web UI by leaving a comment as #'ing someone in a comment. As a temporary solution I've populated a dictionary to reference (and that works), however I'd like to make this more dynamic for future proofing the script.
'assignee': {'accountId': jira_dict[my_username]},
I can't seem to really find any documentation on looking up the accountId from the name, and I figured I'd go ahead and ask the community to see if anyone else has run into/solved this issue.
I was thinking about just writing a new function that performs this query for me, then returns the accountId.
EDIT
I did find this:
import requests
from requests.auth import HTTPBasicAuth
import json
url = "/rest/api/3/user/bulk/migration"
auth = HTTPBasicAuth("email#example.com", "<api_token>")
headers = {
"Accept": "application/json"
}
response = requests.request(
"GET",
url,
headers=headers,
auth=auth
)
print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
However it 404's on me, I add the server address to the beginning of the url, and replace user, with the username in question.
Okay, I found a solution, it's not an elegant solution, but it does exactly what I need it to. So here is the new function:
def jira_account_id_from_username(username):
r = requests.get('https://serverName.atlassian.net/rest/api/3/user?username=' + username, auth=("username",api_key), verify=False)
value = re.search('"accountId":"(.*?)",', str(r.text)).group(1)
return value
I strongly encourage you to not rely on the username anymore. The endpoint you are using is deprecated, see also https://developer.atlassian.com/cloud/jira/platform/deprecation-notice-user-privacy-api-migration-guide/.
The "new" or probably better way is to use the /user/search endpoint as described here: https://developer.atlassian.com/cloud/jira/platform/rest/v3/#api-rest-api-3-user-search-get There you can define a query that is matching against certain properties of a user (displayName or emailAddress), or search for the accountId if you already have it. Therefore, if you are linking users from the cloud to some other "user directory" (or just a scripts where you have stored some usernames), replace it by using either email address or accountId so you can properly link your users.
I am totally new to python flask and encountered a problem when writing some code using the requests and flask modules.
I am working on a project using the web API offered by the Panther platform. The project provided an example using Apache Java.
The source code is as below (see more for details).
public class TestProject {
public static void main(String args[]) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?");
StringBody organism = new StringBody("Homo sapiens", ContentType.TEXT_PLAIN);
FileBody fileData = new FileBody(new File("c:\\data_files\\gene_expression_files\\7_data\\humanEnsembl"), ContentType.TEXT_PLAIN);
StringBody enrichmentType = new StringBody("process", ContentType.TEXT_PLAIN);
StringBody testType = new StringBody("FISHER", ContentType.TEXT_PLAIN);
//StringBody cor = new StringBody("FDR", ContentType.TEXT_PLAIN);
//StringBody cor = new StringBody("BONFERRONI", ContentType.TEXT_PLAIN);
//StringBody cor = new StringBody("NONE", ContentType.TEXT_PLAIN);
StringBody type = new StringBody("enrichment", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("organism", organism)
.addPart("geneList", fileData)
.addPart("enrichmentType", enrichmentType)
.addPart("test_type", testType)
.addPart("type", type)
//.addPart("correction", cor)
.build();
httppost.setEntity(reqEntity);
CloseableHttpResponse response = httpclient.execute(httppost);
try {
//System.out.println("----------------------------------------");
//System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println(IOUtils.toString(resEntity.getContent(), StandardCharsets.UTF_8));
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
The part I am mostly interested in is .addPart("organism", organism) and all the other code with similar structures. They will help pass the parameters from a third-party website to the web API offered by Panther.
I remade the JAVA code into python3 using requests. The code is as follows:
uploadTemp = {'file':open('./app/static/data_temp/temp.txt','rb')}
url="http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"
params = {"organism":organism,"geneList":pantherName,"enrichmentType":"fullGO_process","test_type":"BINOMIAL","type":"enrichment","correction":"BONFERRONI"}
# or params = {"organism":organism,"geneList":uploadTemp,"enrichmentType":"fullGO_process","test_type":"BINOMIAL","type":"enrichment","correction":"BONFERRONI"}
Pantherpost= requests.post(url, params = params)
print(Pantherpost.text)
I am expecting an XML object from the web API including some basic biological information. However, the result I got was null (or \n\n\rnull\n when I print Pantherpost.content)
It seems that the parameters I have got from my own web were not correctly sent to the web API.
In addition to this getting null problem, as a beginner, I am also not quite sure about whether the "geneList" part should be receiving a plain-text object or a file. The manual says it is expecting a file, however, it may have been reformatted into plain-text by this command
FileBody fileData = new FileBody(new File("c:\\data_files\\gene_expression_files\\7_data\\humanEnsembl"), ContentType.TEXT_PLAIN);
Anyway, I did try both interpretations: pantherName is a list with name correctly formatted in plain-text and uploadTemp is a .txt file generated for the project. There must be some extra bugs in my code since it returned null in both cases.
Can someone please help out? Thank you very much.
I've found the following issues with your python code:
One. If you want to POST a file using requests, you should use keyword files=.
Two. Keys in files object should match respective parameters of the request (you're using file instead).
Three. You put your parameters in the wrong place of the request by writing params=params.
Function annotation from requests source code:
:param params: (optional) Dictionary or bytes to be sent in the query string for the :class:Request.
In example Java code StringBody is used to create parameters, which implies that parameters should be placed inside the body of HTTP request, not query string. So you should use data= keyword instead. If you use params=, output will be null.
SO article on difference between data and params keywords in requests.
So I've spent some time reading thier manual and made a test script:
import requests
url = "http://pantherdb.org/webservices/garuda/tools/enrichment/VER_2/enrichment.jsp?"
filepath = "C:\\data\\YOUR_DATA.txt" # change to your file location
# all required parameters according to manual, except geneList which is a file (see below)
params = { # using defaults from manual
"type": "enrichment",
"organism": "Homo sapiens",
"enrichmentType": "process",
"test_type": "FISHER",
"correction": "FDR",
}
# note that the key here is the name of paramter: geneList
files = {'geneList': open(filepath, 'rb')}
# it outputs null, when 'params=params' is used
r = requests.post(url, data=params, files=files)
print(r.status_code)
print(r.text)
Output:
200
Id Name GeneId raw P-value FDR
I am very newbie with the Google DialogFlow, As I am exploring with the Api.ai. I got to know about the userEntity(V1) or SessionEntity(V2).
I have created the session entity using fulfilment with the below code:
import requests
REQUIRED_SCOPES = 'https://www.googleapis.com/auth/dialogflow'
access_token = generate_access_token()
url = 'https://dialogflow.googleapis.com/v2/'+ session_id +'/entityTypes'
headers = {'Authorization': 'Bearer '+ access_token,'Content-Type': 'application/json'}
entity_data = json.dumps({"entityOverrideMode": "ENTITY_OVERRIDE_MODE_OVERRIDE", "entities": [{"synonyms":["sugarcane", "sugar"],"value": "sweet"}], "value": str(session_id)+'fruit'})
response = requests.post(url,headers=headers,data=entity_data)
It creates the sessionEntity with success and also able to list the entity from the session.
It's working while I tried from the same page of console with TryMe-Intents.
But while I tried using simulator or mobile to pass some phrases for my Intent I am not getting the newly created entity to map with the matching phrases.
For Example, I want Sugarcane, at this point, I suppose to get sugarcane as mapped with the entity with the current session for followup intents.
But it was not happening, don't know if I am missing anything. Let me know if anything is wrong or missing.
Suggestions are always welcome.
Reference Links which I have referred to achieve:
https://cloud.google.com/dialogflow-enterprise/docs/reference/rest/v2/projects.agent.sessions.entityTypes/create
https://cloud.google.com/dialogflow-enterprise/docs/entities-session
I am trying to figure out why I cannot pass my two variables to get the API call to work. I know the API call works when I put static name/key in their places.
Any help would be appreciated.
import httplib
#Print my list to choose from.
servers = {'server1.com':'#######','server2.com':'######'}
for server, key in servers.items():
print server
#User chooses which node, it should print what they chose, then store into
variable to send for API Post.
node = raw_input("Which node would you like to check Network Bytes for? ")
if node == server:
print serves.item(server)
print servers.item(key)
box = servers.item(server)
api = servers.item(key)
headers = {'Content-Type': 'application/json', 'Accept': 'application/json',
'Authorization': 'GetData apikey=' + api}
body = r"""{
"cycle": "5min",
"from": 0,
"metric_category": "net",
"metric_specs": [
{
"name": "bytes_in"
}
],
"object_ids": [
0
],
"object_type": "device",
"until": 0
}
"""
conn = httplib.HTTPSConnection(box)
conn.request('POST', '/api/v1/metrics', headers=headers, body=body)
resp = conn.getresponse()
print resp.read()
You should use the json module to translate the Python dict (headers) into a json object. Although they are similar the syntax is subtly different.
The other issue I see here is that server is undefined when you are testing for it. You created server in the for loop, but it's fallen out of scope before you if node == server:. Perhaps you could replace that part with:
#User chooses which node, it should print what they chose, then store into
variable to send for API Post.
box = raw_input("Which node would you like to check Network Bytes for? ")
api = servers.get(node, None):
print "box/node:", box
print " api :", api
Your loop logic is incorrect, as it iterates the dictionary but always will hold the last k,v pair.
servers = {'server1.com':'#######','server2.com':'######'}
for server, key in servers.items():
print server
That basically means every time this runs, it will end holding the same value from the dict. You shouldn't use server / key variables outside of your loop, it's not right and you can expect strange behavior
But the issue resides in your dict retrieval
if node == server:
**print serves.item(server)** # there's a typo here
print servers.item(key)
box = servers.item(server)
api = servers.item(key)
If you want to get the value of a key from a dict, use servers.get(server) or servers[server].
And I'm not sure why are you checking if node == server? you can eliminate that and just ask for node directly from servers dict: box = servers.get(node)
Right now I am writing a snippet allowing submitting code to http://www.spoj.com/ from command line, i.e. something like python spoj_cl.py test.cpp
I understand that I need to send a POST request to the corresponding URL with specified parameters and cookie, but I'm still confused on which parameters to include on. Right now I'm doing it in a trial-and-error method, which seems not to be very effective. My questions are:
How to check systematically which parameters to be included in when sending a POST request?
How can I check immediately if the POST request I send is successful? One way I could think of is to get the content of the submission page http://www.spoj.com/status/, but checking the request directly should be preferable.
Below is the snippet I'm working on. Hopefully it should be readable.
import requests, sys
# if __name__ == "__main__":
base_url = "http://spoj.com"
autologin_hash = "*************" # Your user hash, taken from cookie
autologin_login = "************" # Your user name
session_id = "************" # Login session, can be retrieved when logged in
cookies_info = {
"autologin_login": autologin_login,
"autologin_hash": autologin_hash
}
ext_id = {
"cpp": "1"
}
filename = "test.cpp"
problem_name = str(filename.split(".")[0]).upper()
extension = filename.split(".")[1]
submit_url = base_url + "/submit/"
parts = {
"PHPSESSID": session_id,
"action": "/submit/complete",
"file": open(filename, "rb"),
"subm_file": "",
"lang": ext_id[extension],
"problemcode": problem_name
}
requests.post(submit_url,
params={"PHPSESSID": session_id},
files=parts,
cookies=cookies_info)
print "Submission sent!"
How to check systematically which parameters to be included in when sending a POST request?
I am not a member of the site spoj.com, but what you are asking for is basic web scraping. Find the HTML form for submitting code on the website, then use Firebug or Chrome developer console to find the HTML input elements with name attributes. Once you have found them, you can make a Python script to check for these elements systematically. If one day the elements are missing, the page probably changed.
Example Code:
webpage = requests.get(form_url, params={"PHPSESSID": session_id}, cookies=cookies_info)
html = BeautifulSoup(webpage.text)
form = html.find('form')
inputs = form.findAll('input')
names = []
for i in inputs:
names.append(i['name'])
How can I check immediately if the POST request I send is successful?
Check the status code of the response. It should be 200 for successful requests.
# Make the request
r = requests.post(submit_url,
params={"PHPSESSID": session_id},
files=parts,
cookies=cookies_info)
# Check the response code
if r.status_code == '200':
print "Submission successful!"
else:
print "Submission met a status code of: %s" % r.status_code