Code does not post all output using jira-python in Jira - python

So I’m having some difficulty with my code. The code works but for some reason it only post one string instead of having all the strings posted in Jira. for example, up to the point that you see the #print(username, response), in the terminal I see all responses being printed in on screen. So it works great up to that point but the moment I send the same variable such as response through the Jira Dictionary called issue_dict, it creates the Jira but with only one of the responses and not all. I’ve tried doing something like response[x] but it just gives me an error that string indices must be integers. I’m not quite sure what else to do to be able to iterate through this so I can post all the results in the Description/body of a Jira ticket.
Ideally I would love to have both the user and the response in the description part. I’ve tried to do this with a List but I seem to get the same results where only one string gets printed. Anyone have done anything similar to post results in Jira?
Here is the code:
import jira from JIRA
for i in range(1,3):
user = os.getenv(‘USER’ + str(i))
pass = os.getenv(‘PASS’+ str(i))
headers = {
'X-Requested-With': 'Curl',
}
response =requests post('https://API-Address', headers=headers, auth=(USER,PASS))
root = ET.fromString(response.text) # Parses the JSON into text
for x in root.iter(’text’): #all this is doing is iterating through the file root and finding the text and saving the substring in response.
response = x[2].text
#print(username, response)
issue_dict = {
'project': {'id': 123},
'summary’:’My Jira Using Py',
'description': response, #This is the current issue!
'issuetype': {'name': 'Bug'},
}
new_issue = jira.create_issue(fields=issue_dict)

Related

Am I sending a this json data correctly using the python requests library?

I'm trying to send this json array to an API using request.post():
{
"insert": [
{
"data": "48bPRVkgvHwjG2VUTkPLaGazynZ6RxETuNGsYZNBrtb7ZkAUqY1NE2iGqoLd8EFsvhbDGW8gNb96Jce8fg2aiY8A5mbd8zf",
"tag": "0x1001"
}
]
}
I was told the json post has to be in an array by one of the devs at the site I'm posting to.
I also pored over these two examples in the API docs.1(edit emojiId section),2(adding an emoji id record)
What I tried so far is posting this dictionary:
{'insert': [{'data': '48bPRVkgvHwjG2VUTkPLaGazynZ6RxETuNGsYZNBrtb7ZkAUqY1NE2iGqoLd8EFsvhbDGW8gNb96Jce8fg2aiY8A5mbd8zf', 'tag': '0x1001'}]}
Using both of these post requests:
requests.post(base_url + '/emoji_id/🤘🐺🤘', json=dict_data, headers=headers)
requests.post(base_url + '/emoji_id/🤘🐺🤘', data=dict_data, headers=headers)
I then converted the dictionary to a string using
dict_data = json.dumps(dict_data, skipkeys=True, separators=(',', ':'))
and again sent it using both json and data.
Each returned a 405 error.
The next thing I tried is using the example this stack post to send a nested json. Here's my code for that attempt:
params = [{'data':'48bPRVkgvHwjG2VUTkPLaGazynZ6RxETuNGsYZNBrtb7ZkAUqY1NE2iGqoLd8EFsvhbDGW8gNb96Jce8fg2aiY8A5mbd8zf','tag':'0x1001'}]
# Tried above both with [ ] on outside making it a list and without
payload = {'insert': json.dumps(params, skipkeys=True, separators=(',', ':'))}
requests.post(base_url + '/emoji_id/🤘🐺🤘', json=payload, headers=headers)
Again, I used both json=payload and data=payload and again I tried it both as a dictionary and converting to a string using the same json.dumps method as above. Same as before each returned a 405 response.
My question is, am I using request.post() correctly in at least one of these attempts? If so, I must be missing something about what the API expects and can start down that rabbit hole.
#ewong nailed it. I didn't realize I had to use the patch method instead of the post method.
So my issue was fixed using:
requests.patch(base_url + '/emoji_id/🤘🐺🤘', json=dict_data, headers=headers)
instead of request.post. The difference between the two still seems subtle to me at this point but the example given in the API docs clearly show a patch method being used and that's what worked.

How to forward webhook data from JIRA using Google Cloud Functions?

I want to make a simple middle-man script which receives data from a JIRA webhook and then parses it and sends it over (to Discord, but that's not important).
From the looks of it, Cloud Functions was a perfect match, so I made a short script which just forwards the request json to a message on Discord to see what data it sends.
import requests
import json
def forward(request):
data = request.json
#tried:
#data = request.get_json()
#data = request.data
#data = request.values
url = 'discord webhook receiver url'
myobj = {'content': str(data)}
requests.post(url, data = myobj)
return '', 200
Set up the webhook on the JIRA side and it kinda works, but not really. First of all it doesn't trigger on some events, like adding a comment or editing a task, only for important(?) events, like adding a new task.
And secondly, it doesn't even send the right looking data for it. This is all i'm getting
{'timestamp': 1609851709546, 'webhookEvent': 'issuelink_created', 'issueLink': {'id': 10016, 'sourceIssueId': 10007, 'destinationIssueId': 10022, 'issueLinkType': {'id': 10004, 'name': 'jira_subtask_link', 'outwardName': 'jira_subtask_outward', 'inwardName': 'jira_subtask_inward', 'style': 'jira_subtask', 'isSubTaskLinkType': True, 'isSystemLinkType': True}, 'sequence': 12, 'systemLink': True}}
And I know those 2 things are wrong because while testing it I've also set up another webhook for Pipedream, where it reacts to all changes, and the data contains names of issues, avatars, links. Everything that's needed for what I'm trying to do. And there aren't any differences between those 2 webhook settings, I have them both with all events selected.
So I've been at it for 2 days now with no breakthrough. Maybe I'm misunderstanding how webhooks work, or maybe cloud functions isn't the service to use for this. So while the question is how to do it in cloud functions, I'm also open to alternatives. (not the ones which do the formatting for you, as that's why I started making this in the first place)
Apparently Jira sends 2 requests on webhook trigger and the one containing all the useful info was just over the limit to be put into a Discord message so it never sent it.
That's what I get for using it for logging.
If anyone is also on the same dumbass path, then what I did to find that out is to save all the request data into a hastebin and send the link to it, like so.
#pack it all into a hastebin
everything = str(request.headers) + "\n" + str(request.data) + "\n" + str(request.args) + "\n" + str(request.form) + "\n" + str(request.method) + "\n" + str(request.remote_addr)
req = requests.post('https://hastebin.com/documents', data=everything)
#send the link id to discord
myobj = {'content': req.text}
x = requests.post(url, data = myobj)
All that's left is to parse and format the json.

Mapbox API PUT Datasets Feature return "Provide a single Feature to insert"

I am trying to add a feature to the Dataset via Mapbox API using Python. I'm following this instruction https://docs.mapbox.com/api/maps/#update-a-dataset but keep getting this error:
{'message': 'Provide a single Feature to insert'}
The code looks like this:
rs = []
dictionary = {
"id":1,
"type":"Feature",
"properties":{},
"geometry":{"coordinates":[-83.750246, 42.269375],"type":"Point"}}
url = "https://api.mapbox.com/datasets/v1/voratima/"+dataset+"/features/1?access_token="+access_token
rs.append(grequests.put(url, data=dictionary, hooks = {'response' : do_something}))
grequests.map(rs, exception_handler=exception_handler)
I've tried the following but none of them work:
using requests instead of grequests
wrapping the dictionary with json.dumps()
changing the put parameter from data=dictionary to json=dictionary
Making sure the id for both data and URL are set to 1.
Postman of the exact same request does not have the error. What am I missing?
Given a dataset with dataset ID dataset exists, your request body looks ok.
Please add the header
headers = {'Content-type': 'application/json'}
Also can you check if you meet these specs:
This should be one individual GeoJSON feature, not a GeoJSON
FeatureCollection. If the GeoJSON feature has a top-level id property,
it must match the feature_id you use in the URL endpoint.
It turns out I forgot the header. Thanks to Mortiz for pointing that out. After the update I got
<Response [400]> {'message': 'Unexpected token i'}
That's because I need to wrap the dictionary inside json.dumps(). Then the error became
<Response [422]> {'message': 'Request URI does not match feature id'}
That's because the id in the dictionary has to be a string i.e. "id":"1" not "id":1. Here's the code that works:
rs = []
dictionary = {
"id":"1",
"type":"Feature",
"properties":{},
"geometry":{"coordinates":[-83.750246, 42.269375],"type":"Point"}}
headers = {'Content-type': 'application/json'}
url = "https://api.mapbox.com/datasets/v1/voratima/"+dataset+"/features/1?access_token="+access_token
rs.append(grequests.put(url, data=json.dumps(dictionary), headers=headers, hooks = {'response' : do_something}))
grequests.map(rs, exception_handler=exception_handler)

Python request.post Missing Required Param

I've been looking around and trying to get a post request to work, but I haven't found any luck. I keep getting a MISSING_REQUIRED_PARAM each time the request is being made. My following code is shown below.
def create_sign_group(group_name, header, url):
temp_header = header
temp_header['Content-Type'] = 'application/json'
temp_header['Accept'] = 'application/json'
data = {
"GroupCreationInfo": {
"groupName": group_name
}
}
res = requests.post(url + 'groups', headers=temp_header, data=json.dumps(data))
if res.status_code == 200:
print('{} Group Created...'.format(group_name))
else:
print(res.status_code)
print(res.headers)
print(res.text)
exit(res.status_code)
I've tried using json instead of data, but still getting the same error. Using a the REST API client I was able to successfully make the call. The rest client is shown below:
If anyone can point shine some knowledge and point me in the right direction I would greatly appreciate it. Take care.
You should assign headers=temp_header not headers=header. MISSING_REQUIRED_PARAM is often griping about the content type header, which, as you can see IS being included in your screenshot test.
So I figured it out, I guess I was passing the wrong payload into the data param. I changed the code to:
data = {
"groupName": group_name
}
It looks like I didn't need the "GroupCreationInfo" parameter.

Printing out post data

i have a small script that reads and parse emails and check them against a database to assist me with resetting passwords,
unfortunately i have a bug and i can't seems to find it, currently i'm trying to visually check if there's a difference in the details (hopefully finding a pattern).
this is the relevant parts of the code:
def send_device_match_reset(username, email):
return requests.post(
'https://api.parse.com/1/requestPasswordReset',
headers=parse_headers,
data=json.dumps({
'username': username.upper(),
'email': email.encode('ascii', 'xmlcharrefreplace'),
'code': '*********'
})
)
and
if user.has_key('emailAddress'):
if user.get('emailAddress') == email:
reset_response = send_device_match_reset(username.encode('ascii', 'xmlcharrefreplace'), email.encode('ascii', 'xmlcharrefreplace'))
print "response code", reset_response.status_code
if reset_response.status_code != 200:
log.error('send_device_match_reset failed with %s:%s'%(username,email))
log.error('logging msg: %s'%(reset_response.text))
log.error('email: %s'%(email.encode('ascii', 'xmlcharrefreplace')))
log.error('username: %s'%(username.encode('ascii', 'xmlcharrefreplace')))
return
log.info('Recovered using verified email')
return message_processed(message, 'RecoveredByEmail', user=user)
now i'm trying to figure out how to print the actual headers from the #1st section "data"
inside my "log.error" debug lines.
i've been trying a direct approach by doing:
log.error(requests.post);
or
log.error(requests.post(data));
but it doesn't work - and i don't know python good enough to understand why.
log.error(requests.post); prints the function pointer
log.error(requests.post(data)); prints the result of the function, since data ist defined globally -> error
Try log.error(parse_headers) since this variable seems to be defined globally, it should work for you.
However, I normally stringify my variables like '{0}'.format(var) to enure, that I am working with a string afterwards.
EDITED:
def send_device_match_reset(username, email):
data = json.dumps({
'username': username.upper(),
'email': email.encode('ascii', 'xmlcharrefreplace'),
'code': '*********'
})
log.error('sending: data = {0}'.format(data))
return requests.post(
'https://api.parse.com/1/requestPasswordReset',
headers = parse_headers,
data = data
)

Categories

Resources