API connection and getting the returned result - python

I'm sorry for my bad english
Hello, I am using a brokerage firm for payment instrument. The API connection is successful and I get the result. But I can't use the returned result information.
payment_card = {
'cardHolderName': kartisim,
'cardNumber': kartno,
'expireMonth': kartskt_ay,
'expireYear': '2030',
'cvc': karcvc,
'registerCard': '0'
}
buyer = {
'id': adres.id,
'name': adres.adres_uye.username,
'surname': 'Doe',
'gsmNumber': '+905350000000',
'email': adres.adres_uye.email,
'identityNumber': '74300864791',
'lastLoginDate': '2015-10-05 12:43:35',
'registrationDate': '2013-04-21 15:12:09',
'registrationAddress': adres.adres_detay,
'ip': '85.34.78.112',
'city': 'Istanbul',
'country': 'Turkey',
'zipCode': '34732'
}
address = {
'contactName': 'Jane Doe',
'city': 'Istanbul',
'country': 'Turkey',
'address': 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1',
'zipCode': '34732'
}
basket_items = []
for bas in uye:
basa = {
'id': str(bas.id),
'name': str(bas.sepet_urun.urun_baslik),
'category1': str(bas.sepet_urun.urun_anakategori.anakategori_baslik),
'category2': str(bas.sepet_urun.urun_altkategori.altkategori_baslik),
'itemType': 'VIRTUAL',
'price': str(bas.sepet_fiyat)
}
basket_items.append(basa)
print(basket_items)
request_payload = {
'locale': 'tr',
'conversationId': '123456789',
'price': str(sepetf),
'paidPrice': str(sepetf),
'currency': 'TRY',
'installment': '1',
'basketId': str(sepetid),
'paymentChannel': 'WEB',
'paymentGroup': 'PRODUCT',
'paymentCard': payment_card,
'buyer': buyer,
'shippingAddress': address,
'billingAddress': address,
'basketItems': basket_items
}
payment = iyzipay.Payment().create(request_payload, options)
print(payment.read().decode('utf-8'))
return HttpResponse(payment["status"])
I cannot use the returned result information. The returned result is as follows
The error I get is as follows:
'HTTPResponse' object is not subscriptable

Looks like the issue is here.
return HttpResponse(payment["status"])
payment returns an HTTPResponse response object and you cannot directly index the status. Instead you should use .status attribute.
If your intention is to return JSON back as response you could use JsonResponse class from django.http module.
return JsonResponse(json.loads(payment.read().decode('utf-8')))

Related

JSON viewers don't accept my pattern even after dict going through json.dumps() + json.loads()

The result when printing after a = json.dumps(dicter) and print(json.loads(a)) is this:
{
'10432981': {
'tournament': {
'name': 'Club Friendly Games',
'slug': 'club-friendly-games',
'category': {
'name': 'World',
'slug': 'world',
'sport': {
'name': 'Football',
'slug': 'football',
'id': 1
},
'id': 1468,
'flag': 'international'
},
'uniqueTournament': {
'name': 'Club Friendly Games',
'slug': 'club-friendly-games',
'category': {
'name': 'World',
'slug': 'world',
'sport': {
'name': 'Football',
'slug': 'football',
'id': 1
},
'id': 1468,
'flag': 'international'
},
'userCount': 0,
'hasPositionGraph': False,
'id': 853,
'hasEventPlayerStatistics': False,
'displayInverseHomeAwayTeams': False
},
'priority': 0,
'id': 86
}
}
}
But when trying to read in any json viewer, they warn that the format is incorrect but don't specify where the problem is.
If it doesn't generate any error when converting the dict to JSON and not even when reading it, why do views warn of failure?
You must enclose the strings using double quotes ("). The json.loads returns a python dictionary, so it is not a valid JSON object. If you want to get valid JSON you can get the string that json.dumps returns.

Remove item in JSON if key has value

I have tried everything I can possible come up with, but the value wont go away.
I have a JSON user and if user['permissions'] have key permission = "DELETE PAGE" remove that index of del user['permissions'][1] (in this example)
I want to have a list of possible values as "DELETE PAGE" and so on. If value in key, then delete that index.
Then return the users json without those items found.
I have tried del user['permission][x] and .pop() and so on but it is still there.
{
'id': 123,
'name': 'My name',
'description': 'This is who I am',
'permissions': [{
'id': 18814,
'holder': {
'type': 'role',
'parameter': '321',
'projectRole': {
'name': 'Admin',
'id': 1,
}
},
'permission': 'VIEW PAGE'
}, {
'id': 18815,
'holder': {
'type': 'role',
'parameter': '123',
'projectRole': {
'name': 'Moderator',
'id': 2
}
},
'permission': 'DELETE PAGE'
}]
}
Here's the code:
perm = a['permissions']
for p in perm:
if p['permission'] == 'DELETE PAGE':
perm.remove(p)
print(a)
Output:
{'id': 123, 'name': 'My name', 'description': 'This is who I am', 'permissions': [{'id': 18814, 'holder': {'type': 'role', 'parameter': '321', 'projectRole': {'name': 'Admin', 'id': 1}}, 'permission': 'VIEW PAGE'}]}

How to parse json.response dict

I'm looking to parse the following dictionary received json response and am running into issues. My dictionary name is results.
This is a simple json response that appears to be dict.
{'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
Type confirms that:
<class 'dict'>
Ultimately what I'd like to do is something along the lines of:
for key, value in results.items():
(rx_error, rx_error_freq) = value[16]
In order to get the value 0.00009262475396549728 from above. How would I go about doing this?
One great way to visualize nested dictionaries is to use pprint which comes built into python3
from pprint import pprint
d = {'resultType': 'vector', 'result': [{'metric': {'agent_host':
'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch',
'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance':
'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack',
'site_name': 'test_site'}, 'value': [1631917506.324,
'0.00009262475396549728']}]}
pprint(d)
>>> {'result': [{'metric': {'agent_host': 'x.x.x.x',
'cluster_name': 'test_cluser',
'device_type': 'switch',
'hostname': 'myswitch',
'ifName': 'xe-0/0/10',
'instance': 'telegraf:1111',
'job': 'telegraf',
'rack_name': 'test_rack',
'site_name': 'test_site'},
'value': [1631917506.324, '0.00009262475396549728']}],
'resultType': 'vector'}
This allows us to see the different key value pairs a lot more easily. So the data you're looking to access would is
rx_error, rx_error_freq = d["result"][0]["value"]
Loop over the result list to get the value, then print the second element
>>> data = {'resultType': 'vector', 'result': [{'metric': {'agent_host': 'x.x.x.x', 'cluster_name': 'test_cluser', 'device_type': 'switch', 'hostname': 'myswitch', 'ifName': 'xe-0/0/10', 'instance': 'telegraf:1111', 'job': 'telegraf', 'rack_name': 'test_rack', 'site_name': 'test_site'}, 'value': [1631917506.324, '0.00009262475396549728']}]}
>>> for r in data['result']:
... print(r['value'][1])
...
0.00009262475396549728

Python steamlit select box menu returns string, but I need dict or list

Stack on this case, Python steamlit select box menu returns string, but I need dict or list, to use it further in my code.
I want to see company1, company2, company3 in dropdown menu, and if user's choice was for example 'company2' get ['ID': 'zxc222’, 'NAME': 'company2','DESC': 'comp2'].
BaseObject = [{
'ID': 'zxc123',
'NAME': 'company1',
'DESC': 'comp1'
}, {
'ID': 'zxc222',
'NAME': 'company2',
'DESC': 'comp2'
}, {
'ID': 'zxc345',
'NAME': 'company3',
'DESC': 'comp3'
}]
lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
options.append((BaseObject[i])['NAME'])
st.selectbox('Subdivision:', options)
You can do the conversion to a dict after the selectbox:
import streamlit as st
BaseObject = [{
'ID': 'zxc123',
'NAME': 'company1',
'DESC': 'comp1'
}, {
'ID': 'zxc222',
'NAME': 'company2',
'DESC': 'comp2'
}, {
'ID': 'zxc345',
'NAME': 'company3',
'DESC': 'comp3'
}]
lenbo = len(BaseObject)
options = []
for i in range(0, lenbo):
options.append((BaseObject[i])['NAME'])
choice = st.selectbox('Subdivision:', options)
chosen_base_object = None
for base_object in BaseObject:
if base_object["NAME"] == choice:
chosen_base_object = dict(base_object)
print(chosen_base_object) # {'ID': 'zxc345', 'NAME': 'company3', 'DESC': 'comp3'}

1 sock.execute transaction with 2 data structures

I have read that it is possible to record a partner and their addresses, all in a single call to the web service. The examples always call 2 sock.execute
partner = {
'name': 'Fabien Pinckaers',
'lang': 'fr_FR',
}
partner_id = sock.execute(dbname, uid, pwd, 'res.partner', 'create', partner)
address = {
'partner_id': partner_id,
'type' : 'default',
'street': 'Chaussée de Namur 40',
'zip': '1367',
'city': 'Grand-Rosière',
'phone': '+3281813700',
'fax': '+3281733501',
}
address_id = sock.execute(dbname, uid, pwd, 'res.partner.address', 'create', address)
But how do i call this as 1 transaction in 1 sock.execute?
Try like this:
partner = {
'name': 'Fabien Pinckaers',
'lang': 'fr_FR',
'address': [(0,0,{
'type': 'default',
'street': 'Chaussée de Namur 40',
'zip': '1367',
'city': 'Grand-Rosière',
'phone': '+3281813700',
'fax': '+3281733501',
})]
}
or try like this:
address = {
'type' : 'default',
'street': 'Chaussée de Namur 40',
'zip': '1367',
'city': 'Grand-Rosière',
'phone': '+3281813700',
'fax': '+3281733501',
}
partner = {
'name': 'Fabien Pinckaers',
'lang': 'fr_FR',
}
partner.update({'address': [(0,0,address)]})
Hope this helpful

Categories

Resources