Jira Create Issue using python - python

I'm trying to create a Jira Issue with python, but while calling the new issue method getting below error, seems i'm missing something or not trying the right way, the fields of report frequency, report request type & due date is mandatory fields. Can anyone help me with the error?
jira.exceptions.JIRAError: JiraError HTTP 400 url: https://neomediaworld.atlassian.net/rest/api/2/issue
text: Field 'report frequency' cannot be set. It is not on the appropriate screen, or unknown., Field 'report request type' cannot be set. It is not on the appropriate screen, or unknown., Field 'due date' cannot be set. It is not on the appropriate screen, or unknown., Field 'market' cannot be set. It is not on the appropriate screen, or unknown.
response headers = {'X-AUSERNAME': 'Dharmendra.mishra', 'X-AREQUESTID': '675ecad3-1149-4673-b283-d86a55292d01', 'X-XSS-Protection': '1; mode=block', 'X-Content-Type-Options': 'nosniff', 'Transfer-Encoding': 'chunked', 'X-Seraph-LoginReason': 'OK', 'Strict-Transport-Security': 'max-age=315360000; includeSubDomains; preload', 'ATL-TraceId': '49a1e4174e1f0c65', 'ATL-TCS-Time': 'Cache Hit', 'Server': 'Atlassian Proxy/1.13.6.2', 'Connection': 'close', 'Cache-Control': 'no-cache, no-store, no-transform', 'Date': 'Mon, 29 Oct 2018 08:15:59 GMT', 'Content-Type': 'application/json;charset=UTF-8'}
response text = {"errorMessages":[],"errors":{"market":"Field 'market' cannot be set. It is not on the appropriate screen, or unknown.","due date":"Field 'due date' cannot be set. It is not on the appropriate screen, or unknown.","report frequency":"Field 'report frequency' cannot be set. It is not on the appropriate screen, or unknown.","report request type":"Field 'report request type' cannot be set. It is not on the appropriate screen, or unknown."}}
The code is as below.
from jira import JIRA
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import datetime
class JiraException(Exception):
pass
class Jira(object):
def __init__(self, **kwargs):
self.options = {
'server': 'https://neomediaworld.atlassian.net',
'verify': False
}
self.client = None
if len(kwargs) != 2:
raise JiraException(
'In order to use this class you need to specify a user and a password as keyword arguments!')
else:
if 'username' in kwargs.keys():
self.username = kwargs['username']
else:
raise JiraException('You need to specify a username as keyword argument!')
if 'password' in kwargs.keys():
self.password = kwargs['password']
else:
raise JiraException('You need to specify a password as keyword argument!')
try:
self.client = JIRA(self.options, basic_auth=(self.username, self.password))
except Exception:
raise JiraException('Could not connect to the API, invalid username or password!')
def get_projects(self, raw=False):
projects = []
for project in self.client.projects():
if raw:
projects.append(project)
else:
projects.append({'Name': str(project.key), 'Description': str(project.name)})
return projects
def new_issue(self):
issue_dict = {
'project': {'key': 'MOS'},
'issuetype': {'name': 'Reporting'},
'summary': 'Test',
'market': 'AUS',
'report request type': 'Ad hoc',
'report frequency': 'Monthly',
'description': 'test',
'due date': '29/Oct/18'}
new_issue = self.client.create_issue(fields=issue_dict)

Related

Django simplejwt: How to add refresh token to dict?

I am using simplejwt to get an access and refresh tokens. In a view I need to create a dict, where the both will be stored as well as access token claims and another additional data. Everything works but by some reason when the refrsh token is added to dict, it returns its decoded value, but not the token.
my views.py
#csrf_exempt
##api_view(('GET',))
def check_token(request):
token_refresh = RefreshToken.for_user(request.user)
print('REFRESH', token_refresh)
token = request.META.get('HTTP_AUTHORIZATION', " ").split(' ')[1]
data = {'token': token, 'refresh_token': token_refresh}
try:
valid_data = TokenBackend(algorithm='HS256').decode(token, verify=False)
data['uui'] = valid_data['user_id']
data['validUntil'] = valid_data['exp']
data['clientId'] = 'default'
print(data)
return JsonResponse(data)
except ValidationError as v:
print("Validation error", v)
print('REFRESH', token_refresh) returns the token:
'REFRESH eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...'
but data object returns:
{'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': {'token_type': 'refresh', 'exp': 1628664751, 'jti': '38f0e3a4d7bb452681834a6b149aa496', 'user_id': 'None'}, 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'}
my ideal result:
{'token': 'eyJ0eXAiOiJKV1QiLCJhbGci...', 'refresh_token': 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI...', 'uui': 1, 'validUntil': 1628059131, 'clientId': 'default'}
if you want to create tokens manually for user in djangorestframework-simplejwt you can do this:
from rest_framework_simplejwt.tokens import RefreshToken
def get_tokens_for_user(user):
refresh = RefreshToken.for_user(user)
return {
'refresh': str(refresh),
'access': str(refresh.access_token),
# Add additional fields here
}
now you can use this function in your views.

How to get object from MinIO response?

I am using python API to save and download model from MinIO. This is a MinIO installed on my server. The data is in binary format.
a = 'Hello world!'
a = pickle.dumps(a)
client.put_object(
bucket_name='my_bucket',
object_name='my_object',
data=io.BytesIO(a),
length=len(a)
)
I can see object saved through command line :
mc cat origin/my_bucket/my_object
Hello world!
However, when i try to get it through Python API :
response = client.get_object(
bucket_name = 'my_bucket',
object_name= 'my_object'
)
response is a urllib3.response.HTTPResponse object here.
I am trying to read it as :
response.read()
b''
I get a blank binary string. How can I read this object? It won't be possible for me to know its length at the time of reading it.
and here is response.__dict__ :
{'headers': HTTPHeaderDict({'Accept-Ranges': 'bytes', 'Content-Length': '27', 'Content-Security-Policy': 'block-all-mixed-content', 'Content-Type': 'application/octet-stream', 'ETag': '"75687-1"', 'Last-Modified': 'Fri, 16 Jul 2021 14:47:35 GMT', 'Server': 'MinIO/DEENT.T', 'Vary': 'Origin', 'X-Amz-Request-Id': '16924CCA35CD', 'X-Xss-Protection': '1; mode=block', 'Date': 'Fri, 16 Jul 2021 14:47:36 GMT'}), 'status': 200, 'version': 11, 'reason': 'OK', 'strict': 0, 'decode_content': True, 'retries': Retry(total=5, connect=None, read=None, redirect=None, status=None), 'enforce_content_length': False, 'auto_close': True, '_decoder': None, '_body': None, '_fp': <http.client.HTTPResponse object at 01e50>, '_original_response': <http.client.HTTPResponse object at 0x7e50>, '_fp_bytes_read': 0, 'msg': None, '_request_url': None, '_pool': <urllib3.connectionpool.HTTPConnectionPool object at 0x790>, '_connection': None, 'chunked': False, 'chunk_left': None, 'length_remaining': 27}
Try with response.data.decode()
The response is a urllib3.response.HTTPResponse object.
See urllib3 Documentation:
Backwards-compatible with http.client.HTTPResponse but the response body is loaded and decoded on-demand when the data property is accessed.
Specifically, you should read the answer like this:
response.data # len(response.data)
Or, if you want to stream the object, you have examples on the minio-py repository: examples/get_objects.

400 Bad Request: Failed to decode JSON object; PUT request (Flask)

Upon trying to test the JSON payload to a PUT request, I'm getting the following error. I'm not sure if its my test that's causing the error or if there is something else that is causing the issue? If I comment out that line the HTTP verb responds with no error.
werkzeug.exceptions.BadRequest:
400 Bad Request: Failed to decode JSON object: Expecting value: line 1 column 1 (char 0)
-> args = self.put_request_parser.parse_args()
Upon debugging, here what is actually being sent when parse_args() is invoked. I'm not sure why unparsed_arguments is an empty dictionary in this case?
EnvironHeaders([('User-Agent', 'werkzeug/0.14.1'), ('Host', 'localhost'),
('Content-Type', 'application/json'), ('Content-Length', '0'),
('Authorization', 'Bearer <token>')]),
'url': 'http://localhost/api/v1/todos/3', 'unparsed_arguments': {}}
tests.py
class TestUpdateTodoResource(ApiTestCase):
'''Verify that a client succesfully updates an existing todo.'''
def test_put_update_user_todo(self):
with app.test_client() as client:
http_response = client.put(
"api/v1/todos/3",
headers={
'content-type': 'application/json',
'authorization': f"Bearer {token}"
},
data = {
"name": "Never do this todo!"
}
)
self.assertEqual(http_response.status_code, 204)
todos.py
class ApiTodo(Resource):
put_request_parser = reqparse.RequestParser()
put_request_parser.add_argument(
'name',
required=True,
location=['form', 'json'],
help="Cannot accept a blank description"
)
#auth.login_required
def put(self, id):
try:
user_todo = Todo.select().join(User).where(
(Todo.id == id) & (User.id == g.user.id)
).get()
except Todo.DoesNotExist:
abort(404, description="That todo no longer exists")
args = self.put_request_parser.parse_args()
if not args['name']:
abort(400, description="Must provide a todo description")
updated_todo = user_todo.update(**args)
updated_todo.execute()
return marshal(set_todo_creator(updated_todo), todo_fields, 'todo'), 204

Find oldest to youngest record Python

I am trying to retrieve data from the first available date to present date from an API. I've tried using min and max in parameter.
def getcomplete(cid, pid, tag, type):
api_endpoint = ''
headers = {'token': get_token()['access_token'], 'Content-Type': 'application/json'}
params = {'cid': str(cid),
'from-date': datetime.datetime.min,
'to-date': datetime.datetime.max,
'tag': str(tag),
'type': str(type),
'pid': str(pid)
}
r = requests.post(url=api_endpoint, headers=headers, params=params)
return r.json()
getcomplete(10,12,'x','y')
This returns {'status': 'success', 'message': 'success', 'data': []}.
Is there anything wrong with the written function.
Thanks
Pythons min() and max() have an optional default parameter. This will prevent them from throwing errors
min("", default="")

Shopify API: delete discounts and price rules

I'm using the Shopify Python library to work with my store's orders, discounts, etc. I'm writing some tests that involve creating and deleting price rules and discounts.
def test_get_discount(self):
random_number_string = str(randint(0,10000))
price_rule = shopify.PriceRule.create({
'title': 'TEST-PRICERULE-' + random_number_string,
'target_type': 'line_item',
'target_selection': 'all',
'allocation_method': 'across',
'value_type': 'fixed_amount',
'value': -1000,
'once_per_customer': True,
'customer_selection': 'all',
'starts_at': datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
discount = shopify.DiscountCode.create({
'price_rule_id': price_rule.id,
'code': 'TEST-DISCOUNT-' + random_number_string,
'usage_count': 1,
'value_type': 'fixed_amount',
'value': -1000
})
fetched_price_rule = shopify_utils.get_discount_codes('TEST-PRICERULE-' + random_number_string)
self.assertIsNotNone(fetched_price_rule)
#deleted_discount = discount.destroy()
#self.assertIsNone(deleted_discount)
deleted_price_rule = price_rule.delete('discounts')
self.assertIsNone(deleted_price_rule)
Everything up to deleting works properly. I'm also able to delete a discount with no problem, but when i try to delete a price rule, it errors out with the following:
deleted_price_rule = price_rule.delete()
TypeError: _instance_delete() missing 1 required positional argument: 'method_name'
I believe that it's asking me for the nested resource name, so I've tried passing things like discounts, discount_code, etc, but no luck. I see that pyactiveresouce is using that method_name to construct a url to delete the related resource, just don't know what their API looks like as it's not very well documented for cases like this.
When i do specify a (wrong) method name, I get this error:
pyactiveresource.connection.ClientError: Response(code=406, body="b''", headers={'Server': 'nginx', 'Date': 'Sun, 10 Sep 2017 00:57:28 GMT', 'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', 'Connection': 'close', 'X-Sorting-Hat-PodId': '23', 'X-Sorting-Hat-PodId-Cached': '0', 'X-Sorting-Hat-ShopId': '13486411', 'X-Sorting-Hat-Section': 'pod', 'X-Sorting-Hat-ShopId-Cached': '0', 'Referrer-Policy': 'origin-when-cross-origin', 'X-Frame-Options': 'DENY', 'X-ShopId': '13486411', 'X-ShardId': '23', 'X-Shopify-Shop-Api-Call-Limit': '3/40', 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT': '3/40', 'X-Stats-UserId': '0', 'X-Stats-ApiClientId': '1807529', 'X-Stats-ApiPermissionId': '62125531', 'Strict-Transport-Security': 'max-age=7776000', 'Content-Security-Policy': "default-src 'self' data: blob: 'unsafe-inline' 'unsafe-eval' https://* shopify-pos://*; block-all-mixed-content; child-src 'self' https://* shopify-pos://*; connect-src 'self' wss://* https://*; script-src https://cdn.shopify.com https://checkout.shopifycs.com https://js-agent.newrelic.com https://bam.nr-data.net https://dme0ih8comzn4.cloudfront.net https://api.stripe.com https://mpsnare.iesnare.com https://appcenter.intuit.com https://www.paypal.com https://maps.googleapis.com https://stats.g.doubleclick.net https://www.google-analytics.com https://visitors.shopify.com https://v.shopify.com https://widget.intercom.io https://js.intercomcdn.com 'self' 'unsafe-inline' 'unsafe-eval'; upgrade-insecure-requests; report-uri /csp-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin_api&source%5Buuid%5D=72550a71-d55b-4fb2-961f-f0447c1d04c6", 'X-Content-Type-Options': 'nosniff', 'X-Download-Options': 'noopen', 'X-Permitted-Cross-Domain-Policies': 'none', 'X-XSS-Protection': '1; mode=block; report=/xss-report?source%5Baction%5D=error_404&source%5Bapp%5D=Shopify&source%5Bcontroller%5D=admin%2Ferrors&source%5Bsection%5D=admin_api&source%5Buuid%5D=72550a71-d55b-4fb2-961f-f0447c1d04c6', 'X-Dc': 'ash,chi2', 'X-Request-ID': '72550a71-d55b-4fb2-961f-f0447c1d04c6'}, msg="Not Acceptable")
Any ideas hugely appreciated!
As #Tim mentioned in his response, the destroy method worked for me and successfully deleted all children instances as well as parent instance.

Categories

Resources