Inserting dynamic Acceptance Criteria into Customfield via Python - python-jira

i am quiet lost currently.
i want to load some data from my sqlite3 db and then create from this data some acceptance criteria and update the respective issue with these acc.
The issue i have is that i dont understand where my problem is regarding the "build" of the list element that contains the data for the acceptance criteria
i iterate over the data i did load from my DB to create a string variable.
for entry in accDict:
strAcc = (
strAcc
+ '{"name":'
+ entry["NAME"]
+ ',"checked": False,"Mandatory":'
+ entry["MANDATORY"]
+ ',"option": False,"id":'
+ str(cnt_id)
+ ',"rank": '
+ str(cnt_rank)
+ ",} "
)
cnt_id += 1
cnt_rank += 1
strAcc = "[{" + strAcc + "}]"
next i want to insert this string and update the customfields for the respective issue.
new_issue.update(fields={"customfield_11100": [strAcc]})
the code in strAcc looks as follows
[{
{"name":Create Testcases,"checked": False,"Mandatory":True,"option": False,"id":1,"rank": 0,},
{"name":Request Testdata,"checked": False,"Mandatory":True,"option": False,"id":2,"rank": 1,},
{"name":Verify Testressources,"checked": False,"Mandatory":True,"option": False,"id":3,"rank": 2,},
}]
this means the complete insert looks as this
new_issue.update(fields={"customfield_11100":[{
{"name":Create Testcases,"checked": False,"Mandatory":True,"option": False,"id":1,"rank": 0,},
{"name":Request Testdata,"checked": False,"Mandatory":True,"option": False,"id":2,"rank": 1,},
{"name":Verify Testressources,"checked": False,"Mandatory":True,"option": False,"id":3,"rank": 2,},
}]})
the error i receive is
response text = {"errorMessages":["Internal server error"],"errors":{}}
if i create the string by hand and place it as in the last code block it works perfectly...

I think you're missing quotes in the "name" attribute...
Furthermore I'd suggest you write actual python dicts, and not json strings, as they can be translated easily, plus improves readability:
strAcc = []
for entry in accDict:
strAcc.append({
"name": entry["NAME"],
"checked": False,
"mandatory": entry["MANDATORY"],
"option": False,
"id": str(cnt_id),
"rank": str(cnt_rank)
})
cnt_id += 1
cnt_rank += 1

Related

Pagination not working in Python Session.put()

I am trying to upload a file to a website (that has an inbuilt API) using the following code. The code reads a list of medical codes/diagnoses codes etc. (1 column in a text file) and uploads it to the required page.
Issue:
After uploading the file, I noticed that the number pages is not coming out properly. There can be up to 4000 codes (lines) in the file. The code list page in the website will show 20 lines per page, which means, I would expect at least 200 pages to be there after uploading. This is not happening. I am not sure what is the mistake that I am doing.
Also, I am new to Python (primarily SAS) and have been working on automating bits and pieces of code. One such automation is this exercise. Here, the goal is to upload multiple files to the said URL. Today the team is uploading them one by one manually. With the knowledge I picked up from tutorials and other sources, I was able to come up with this.
import requests
import json
import os
import random
import pandas as pd
import time
token = os.environ.get("USER_TOKEN")
user_id = os.environ.get("USER_ID")
user_name = os.environ.get("USER_NAME")
headers = {"X-API-Key": token}
url = 'https://XXXXXXXXXXXX.com/api/code_lists'
session=requests.session()
cl = session.get(url, headers=headers).json()
def uploading_files(file,name,kind,coding_system,rand_id):
df = pd.read_table(file, converters={0:str}, header=None)
print("Came In")
CODES = df[0].astype('str').tolist()
codes = {"codes": CODES}
new_cl = {"_id": rand_id, "name": name, "project_group": "TEST BETA", "kind": kind,
"coding_system": coding_system, "user": user_id, "creator": user_name, "creation_method": "Upload", "is_category_mapping": False,
"assoc_users": [], "global": True, "readonly": False, "description": "", "num_codes": len(CODES)}
request_json = json.dumps(new_cl)
print(request_json)
codes_json = json.dumps(codes)
print(codes_json)
session.post(url, data=request_json)
session.put(url + '/' + rand_id, data=codes_json)
text_Files= os.listdir(r'C://Users//XXXXXXXXXXXXX//data')
for i in text_Files:
if ".txt" in i:
x=i.split("_")
file='C://Users//XXXXXXXXXXXXX//data//' + i
name=""
for j in i[:-4]:
if j!="_":
name+=j
elif j=="_":
name+=" "
kind=x[2]
coding_system=x[3][:-4]
rand_id = "".join(random.choice("0123456789abcdef") for i in range(24))
print("-------------START-----------------")
print("file : ", file)
print("name : ", name)
print("kind : ", kind)
print("coding system : ", coding_system)
print("Rand_Id : ", rand_id)
uploading_files(file, name, kind, coding_system, rand_id)
time.sleep(2)
print("---------------END---------------")
print("")
break ''' to upload only 1 file in the directory'''
Example data in the file (testfile.txt)
C8900
C8901
C8902
C8903
C8904
C8905
C8906
C8907
C8908
C8909
C8910
C8911
C8912
C8913
C8914
C8918
C8919
C8920
C8921
C8922
C8923
C8924
C8925
C8926
C8927
C8928
C8929
C8930
C8931
C8932
C8933
C8934
C8935
C8936
C9723
C9744
C9762
C9763
C9803
D0260
Sample Data Snapshot
Wrong Representation
Expected

Hotbit REST API's PUT_LIMIT function gives error RET_SIGN_ERROR

So basically the hotbit's documentation you can find on
https://github.com/hotbitex/hotbit.io-api-docs/blob/master/readme_en.md
https://github.com/hotbitex/hotbit.io-api-docs/blob/master/rest_api_en.md#orderput_limit
a point need to be remember in hashing SIGN parameter is :
sort the strings that require to be signed according to the parameter names(first compare the first letter of all parameter names and sort them based on alphabetical order; in case that the first letter of more than one parameters is the same, sort these parameters based on the second letter of their names according to alphabetical order, and so on)
parameters that need to be hashed according to alphabets are api_key, secret_key, market, isfee, market, price, amount
import hashlib, requests
url = "https://api.hotbit.io/v2/p2/order.put_limit"
sign_string = "amount=" + str(amount) + "&api_key=" + str(api_key) + "&isfee=0&market=" + str(market) + "&price=" + str(price) + "&secret_key=" + str(secret_key) + "&side=" + str(side)
sign = hashlib.md5(sign_string.encode('utf-8')).hexdigest()
sign = sign.upper()
body = {
"api_key" : str(api_key),
"amount" : amount,
"isfee" : 0 ,
"market" : str(market),
"price" : price,
"side" : side,
"sign": str(sign) }
params = "?amount=" + str(amount) + "&api_key=" + str(api_key) + "&isfee=0&market=" + str(market) + "&price=" + str(price) + "&side=" + str(side) + "&sign=" + str(sign)
print (params)
response = requests.request('POST', url, data = body )
print (response.text)
and here is the response we get from Hotbit API
{"error":{"code":6,"message":"RET_SIGN_ERROR"},"result":null,"id":0}
Please help me solving this problem..!
Thanks in advance.!
Ohk so i got answer what was wrong in it you can compare your code , (sign_string was not configured properly in alphabetical order)
ORDER_PUT_LIMIT = "https://api.hotbit.io/v2/p2/order.put_limit"
def sell(self, amount=0, price=0, market=settings.MARKET, isfee=settings.ISFEE):
"""
Response:
{
"error": null,
"result":
{
"id":8688803, #order-ID
"market":"ETHBTC",
"source":"web", #The source identification of data request
"type":1, #Type of order pladement 1-limit order
"side":2, #Identification of buyers and sellers 1-Seller,2-buyer
"user":15731,
"ctime":1526971722.164765, #Time of order establishment(second)
"mtime":1526971722.164765, #Time of order update(second)
"price":"0.080003",
"amount":"0.4",
"taker_fee":"0.0025",
"maker_fee":"0",
"left":"0.4",
"deal_stock":"0",
"deal_money":"0",
"deal_fee":"0",
"status":0 , #Sign of order status when 0x8 is true, it means the current order is cancelled, when 0x80 is true, it means that the current order is deducted by deductable tokens "fee_stock":"HTB", #Name of deductable token
"alt_fee":"0.5", #The discount of deductable tokens
"deal_fee_alt":"0.123" #Amount deducted
},
"id": 1521169460
}
"""
side = 1 # 1 for sell and 2 for buy
sign_string = "amount=" + str(amount) + "&api_key=" + str(settings.API_KEY) + "&isfee=0&market=" + str(market) + "&price=" + str(price) + "&side=" + str(side) + "&secret_key=" + str(settings.SECRET_KEY)
sign = hashlib.md5(sign_string.encode('utf-8')).hexdigest()
sign = sign.upper()
body = {
"api_key" : str(settings.API_KEY),
"amount" : amount,
"isfee" : 0 ,
"market" : str(market),
"price" : price,
"side" : side,
"sign": str(sign) }
response = requests.post(ORDER_PUT_LIMIT, data=body, headers=HEADERS).json()
print(response)
return response
and my problem was solved..
The api_key and private key are saved in settings.py file.

How to append multiple JSON object in a custom list using python?

I have two dictionary (business and business 1). I convert this dictionary into JSON file as (a and b). Then i append this two JSON object in a custom list called "all".
Here, list creation is static, i have to make it dynamic because the number of dictionary could be random. But output should be in same structure.
Here is my code section
Python Code
import something as b
business = {
"id": "04",
"target": b.YesterdayTarget,
'Sales': b.YSales,
'Achievements': b.Achievement
}
business1 = {
"id": "05",
"target": b.YesterdayTarget,
'Sales': b.YSales,
'Achievements': b.Achievement
}
# Convert Dictionary to json data
a= str(json.dumps(business, indent=5))
b= str(json.dumps(business1, indent=5))
all = '[' + a + ',\n' + b + ']'
print(all)
Output Sample
[{
"id": "04",
"target": 55500000,
"Sales": 23366927,
"Achievements": 42.1
},
{
"id": "05",
"target": 55500000,
"Sales": 23366927,
"Achievements": 42.1
}]
Thanks for your suggestions and efforts.
Try this one.
import ast, re
lines = open(path_to_your_file).read().splitlines()
result = [ast.literal_eval(re.search('({.+})', line).group(0)) for line in lines]
print(len(result))
print(result)

List comprehension to dynamically populate attribute of object

What’s the correct way to dynamically populate the list given to the attribute Value? At the moment its its fixed to 3 (0-2), but would be more useful if it was based on INSTANCE_PARAMS[i]["instances"].
I was thinking along the lines of list comprehension but unsure how to write it into the code.
for i in INSTANCE_PARAMS:
output = template.add_output([
Output(
str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
Value=Join(",", [
GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "0"), "PrivateIp"),
GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "1"), "PrivateIp"),
GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + "2"), "PrivateIp"),
],
),
)
],
)
INSTANCE_PARAMS = {
"masters": {
"name": "master",
"instances": 3,
"image_id": "ami-xxxxxxxxxx",
"instance_type": "t1.micro",
"security_group_id": [
"MasterSG",
"ClusterSG"
],
},
}
Achieved it with the following:
template = Template()
for i in INSTANCE_PARAMS:
# declared a new list
tag_value = []
# got the counter
for r in range(INSTANCE_PARAMS[i]["instances"]):
# added each one to the new list
tag_value.append(GetAtt(ec2.Instance(INSTANCE_PARAMS[i]["name"] + str(r)), "PrivateIP"))
output = template.add_output([
Output(
str(INSTANCE_PARAMS[i]["name"]).capitalize() + "Ips",
Description="IPs for " + str(INSTANCE_PARAMS[i]["name"]),
# passed in the list
Value=Join(",", tag_value,
),
)
],
)
print(template.to_yaml())

PyMongo: how to query a series and find the closest match

This is a simplified example of how my data is stored in MongoDB of a single athlete:
{ "_id" : ObjectId('5bd6eab25f74b70e5abb3326'),
"Result" : 12,
"Race" : [0.170, 4.234, 9.170]
"Painscore" : 68,
}
Now when this athlete has performed a race I want to search for the race that was MOST similar to the current one, and hence I want to compare both painscores.
IOT get the best 'match' I tried this:
query = [0.165, 4.031, 9.234]
closestBelow = db[athlete].find({'Race' : {"$lte": query}}, {"_id": 1, "Race": 1}).sort("Race", -1).limit(2)
for i in closestBelow:
print(i)
closestAbove = db[athlete].find({'Race' : {"$gte": query}}, {"_id": 1, "Race": 1}).sort("Race", 1).limit(2)
for i in closestAbove:
print(i)
This does not seem to work.
Question1: How can I give the mentioned query IOT find the race in Mongo that matches the best/closes?.. When taken in account that a race is almost never exactly the same.
Question2: How can i see a percentage of match per document so that an athlete knows how 'serious' he must interpreted the pain score?
Thank you.
Thanks to this website I found a solution: http://dataaspirant.com/2015/04/11/five-most-popular-similarity-measures-implementation-in-python/
Step 1: find your query;
Step 2: make a first selection based on query and append the results into a list (for example average);
Step 3: use a for loop to compare every item in the list with your query. Use Euclidean distance for this;
Step 4: when you have your matching processed, define the best match into a variable.
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
Database = 'Firstclass'
def newSearch(Athlete):
# STEP 1
db = client[Database]
lastDoc = [i for i in db[Athlete].find({},{ '_id': 1, 'Race': 1, 'Avarage': 1}).sort('_id', -1).limit(1)]
query = { '$and': [ { 'Average' : {'$gte': lastDoc[0].get('Average')*0.9} }, { 'Average' : {'$lte': lastDoc[0].get('Average')*1.1} } ] }
funnel = [x for x in db[Athlete].find(query, {'_id': 1, 'Race': 1}).sort('_id', -1).limit(15)]
#STEP 2
compareListID = []
compareListRace = []
for x in funnel:
if lastDoc[0].get('_id') != x.get('_id'):
compareListID.append(x.get('_id'))
compareListRace.append(x.get('Race'))
#STEP 3
for y in compareListRace:
ED = euclidean_distance(lastDoc[0].get('Race'),y)
ESlist.append(ED)
#STEP 4
matchObjID = compareListID[numpy.argmax(ESlist)]
matchRace = compareListRace[numpy.argmax(ESlist)]
newSearch('Jim')

Resources