How to update dictionary values side by side? - python

I have a dictionary, I'm creating string with sorting values and adding the length of each field value at the beginning of dictionaries field value.
I have to update this values side by side and i have to hash it:
But this string format is like that.
25http://a1ff569e.ngrok.io/
2TR
17foootest#mail.com
3Adı
6Soyadı
1105316806562
3000
164355084355084358
212
42018
8OPU_TEST
192017-08-28 10:24:57
8Ürünkodu
15Ürün Açıklaması
9Ürün İsmi
3100
11
7Test123
15
218
8CCVISAMC
3TRY
How can i update this string values side by side like below ?
**I know i can print hashstring with end='' but this is not updating hashstring varabile's value like that just shown like that and **
25http://a1ff569e.ngrok.io/
2TR
17payutest#mail.com
3Adı
6Soyadı
1105316806562
3000
164355084355084358
212
42018
8PYKDMNSZ
192017-08-28 10:24:57
8Ürünkodu
15Ürün Açıklaması
9Ürün İsmi
3100
11
7Test123
15
218
8CCVISAMC
3TRY
# Importing required libraries for sample.
from datetime import datetime
import hmac
import hashlib
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# Endpoint
url = "https://secure.payu.com.tr/order/alu/v3"
# PayU Merchant's Secret Key
secret = 'SECRET_KEY'
# Array Begin
array = {
# PayU Merchant's Merchant ID
'MERCHANT': "OPU_TEST",
'ORDER_REF': "Test123",
'ORDER_DATE': datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S'),
'BACK_REF': "http://a1ff569e.ngrok.io/",
'ORDER_PNAME[0]': "Ürün İsmi",
'ORDER_PCODE[0]': "Ürünkodu",
'ORDER_PINFO[0]': "Ürün Açıklaması",
'ORDER_PRICE[0]': "100",
'ORDER_VAT[0]': "18",
'ORDER_QTY[0]': "1",
'ORDER_SHIPPING': "5",
'PRICES_CURRENCY': "TRY",
'PAY_METHOD': "CCVISAMC",
'SELECTED_INSTALLMENTS_NUMBER': "2",
'CC_NUMBER': "4355084355084358",
'EXP_MONTH': "12",
'EXP_YEAR': "2018",
'CC_CVV': "000",
'BILL_FNAME': "Adı",
'BILL_LNAME': "Soyadı",
'BILL_PHONE': "05316806562",
'BILL_EMAIL': "TEST#mail.com",
'BILL_COUNTRYCODE': "TR",
}
# Sorting Array params
for k, v in sorted(array.items()):
# Adding the length of each field value at the beginning of field value
hashstring = str(len(v)) + str(v)
print(hashstring)
# Calculating ORDER_HASH
signature = hmac.new(secret.encode('utf-8'), hashstring.encode('utf-8'), hashlib.md5).hexdigest()
# Adding ORDER_HASH param to dictionary
array['ORDER_HASH'] = signature
print(signature)
print()
# Sending Request to Endpoint
request = Request(url, urlencode(array).encode())
json = urlopen(request).read().decode()
# Printing result
print(json)

I'm not sure but maybe it's works.
Please try and share results with us.
hashstring=print(hashstring+" ", end="")

Related

Payload from a defined list in Python

I am pretty new to python and I am trying to create a script that will pull data from a ticketing platform.
I got the list of agents and their ids but when I try to pull the data it's giving me this error:
KeyError: 'data'
Is there a way for me to have the parameter "agents": to automatically update using the agent_id list?
Here is the code, I removed the links and the API key for privacy reasons:
import requests
import json
from cgitb import text
from openpyxl import Workbook
import openpyxl
import requests
from datetime import date
from datetime import timedelta
#Agents list
agents_list = ["Agent1", "Agent2", "Agent3"]
agent_id = []
agents_names = []
today = date.today()
yesterday = today - timedelta(days = 1)
start_date = str(yesterday)
end_date = str(yesterday)
def extragere_date_agenti():
url = "https://x.gorgias.com/api/users?limit=100&order_by=name%3Aasc&roles=agent&roles=admin"
headers = {
"accept": "application/json",
"authorization": "Basic"
}
response = requests.get(url, headers=headers)
text_name_id = json.loads(response.text)
for names in text_name_id["data"]:
agent_name = names["firstname"]
agents_id = names["id"]
if agent_name in agents_list:
agents_names.append(agent_name)
agent_id.append(agents_id)
extragere_date_agenti()
def extragere_numere():
url = "https://x.gorgias.com/api/stats/total-messages-sent"
payload = {"filters": {
"period": {
"start_datetime": start_date + "T00:00:00-05:00",
"end_datetime": end_date + "T23:59:59-05:00"
},
"agents": [agent_id], #This is the value that I want to modify
"channels": ["email"]
}}
headers = {
"accept": "application/json",
"content-type": "application/json",
"authorization": "Basic"
}
response = requests.post(url, json=payload, headers=headers)
text_numere = json.loads(response.text)
numere_finale = text_numere["data"]["data"]["value"]
print(numere_finale)
I've tried to do a for loop but it's giving me the same error. Any suggestions?
First, add the condition to check the response status code
Also, add another condition to prevent this type of key error:
if "data" in text_name_id:
Your Error:
KeyError: 'data'
Means that in text_name_id is no Key named "data".
Difficult to tell you how to fix it without any more info...
Are you sure, that request returns a positiv status?? I see no ErrorHandling, if respone.status_code == 200: should be enough to check.
Are you sure that the response json has a Key named "data"? Try this to set a default if key is missing:
text_name_id.get("data", [{"firstname": "error", "id": 0}])
--- Edit ---
Okay, is that the right one I don't see a "id" or "firstname" key. But if it is the right JSON, than you can't iterate over dict like you did in Python.
To do so you would want to do this:
for key, value in text_name_id['data']['data'].items():
...

When I attempt to create a JSON Object in Python, It errors, despite having validated the JSON Online

I believe that the issue is due to python formatting all ' to ", which would result in the error message which I recieved upon running the program.
My Code is as follows:
import requests
import json
import pandas as pd
username = input('enter username here: ')
print('')
passw = input('enter password here: ')
mcpayload = {"agent": {"name": "Minecraft", "version": 1}, "username": "{}".format(username), "password": "{}".format(passw), "requestUser": "true"}
header = {"Content-Type": "application/json"}
logintoken = requests.post('https://authserver.mojang.com/authenticate', data = mcpayload, headers = header)
print(logintoken.text)
print('')
print(logintoken.json)
print('')
print(logintoken.content)
It returns this err message on run:
{"error":"JsonParseException","errorMessage":"Unrecognized token 'agent': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')\n at [Source: (org.eclipse.jetty.server.HttpInputOverHTTP); line: 1, column: 7]"}
<bound method Response.json of <Response [400]>>
b'{"error":"JsonParseException","errorMessage":"Unrecognized token \'agent\': was expecting (JSON String, Number, Array, Object or token \'null\', \'true\' or \'false\')\\n at [Source: (org.eclipse.jetty.server.HttpInputOverHTTP); line: 1, column: 7]"}'
The problem is that you are not sending json string but you are sending a python dictionary. you would need to convert it to json first then send it.
You will need to use json.dumps to convert dictionary object to json string.
header=json.dumps(header) #converting dict to json
mcpayload=json.dumps(mcpayload) #converting dict to json
The code should look like this:
import requests
import json
import pandas as pd
username = input('enter username here: ')
print('')
passw = input('enter password here: ')
mcpayload = {"agent": {"name": "Minecraft", "version": 1}, "username": "{}".format(username), "password": "{}".format(passw), "requestUser": "true"}
header = {"Content-Type": "application/json"}
header=json.dumps(header) #converting dict to json
mcpayload=json.dumps(mcpayload) #converting dict to json
logintoken = requests.post('https://authserver.mojang.com/authenticate', data = mcpayload, headers = header)
print(logintoken.text)
print('')
print(logintoken.json)
print('')
print(logintoken.content)
If you want to send JSON, pass the JSON object via the kwarg json, not data:
logintoken = requests.post(
'https://authserver.mojang.com/authenticate',
json=mcpayload
)
Also, you can omit sending the custom header then, since requests.post() will automagically serialize the object for you and set appropriate headers.

Why am I getting this error "TypeError: string indices must be integers" when trying to fetch data from an api?

json file =
{
"success": true,
"terms": "https://curr
"privacy": "https://cu
"timestamp": 162764598
"source": "USD",
"quotes": {
"USDIMP": 0.722761,
"USDINR": 74.398905,
"USDIQD": 1458.90221
}
}
The json file is above. i deleted lot of values from the json as it took too many spaces. My python code is in below.
import urllib.request, urllib.parse, urllib.error
import json
response = "http://api.currencylayer.com/live?access_key="
api_key = "42141e*********************"
parms = dict()
parms['key'] = api_key
url = response + urllib.parse.urlencode(parms)
mh = urllib.request.urlopen(url)
source = mh.read().decode()
data = json.loads(source)
pydata = json.dumps(data, indent=2)
print("which curreny do you want to convert USD to?")
xm = input('>')
print(f"Hoe many USD do you want to convert{xm}to")
value = input('>')
fetch = pydata["quotes"][0]["USD{xm}"]
answer = fetch*value
print(fetch)
--------------------------------
Here is the
output
"fetch = pydata["quotes"][0]["USD{xm}"]
TypeError: string indices must be integers"
First of all the JSON data you posted here is not valid. There are missing quotes and commas. For example here "terms": "https://curr. It has to be "terms": "https://curr",. The same at "privacy" and the "timestamp" is missing a comma. After i fixed the JSON data I found a solution. You have to use data not pydata. This mean you have to change fetch = pydata["quotes"][0]["USD{xm}"] to fetch = data["quotes"][0]["USD{xm}"]. But this would result in the next error, which would be a KeyError, because in the JSON data you provided us there is no array after the "qoutes" key. So you have to get rid of this [0] or the json data has to like this:
"quotes":[{
"USDIMP": 0.722761,
"USDINR": 74.398905,
"USDIQD": 1458.90221
}]
At the end you only have to change data["quotes"]["USD{xm}"] to data["quotes"]["USD"+xm] because python tries to find a key called USD{xm} and not for example USDIMP, when you type "IMP" in the input.I hope this fixed your problem.

How to access certain values of a json site via python

This is the code i have so far:
import json
import requests
import time
endpoint = "https://www.deadstock.ca/collections/new-arrivals/products/nike-
air-max-1-cool-grey.json"
req = requests.get(endpoint)
reqJson = json.loads(req.text)
for id in reqJson['product']:
name = (id['title'])
print (name)
Feel free to visit the link, I'm trying to grab all the "id" value and print them out. They will be used later to send to my discord.
I tried with my above code but i have no idea how to actually get those values. I don't know which variable to use in the for in reqjson statement
If anyone could help me out and guide me to get all of the ids to print that would be awesome.
for product in reqJson['product']['title']:
ProductTitle = product['title']
print (title)
I see from the link you provided that the only ids that are in a list are actually part of the variants list under product. All the other ids are not part of a list and have therefore no need to iterate over. Here's an excerpt of the data for clarity:
{
"product":{
"id":232418213909,
"title":"Nike Air Max 1 \/ Cool Grey",
...
"variants":[
{
"id":3136193822741,
"product_id":232418213909,
"title":"8",
...
},
{
"id":3136193855509,
"product_id":232418213909,
"title":"8.5",
...
},
{
"id":3136193789973,
"product_id":232418213909,
"title":"9",
...
},
...
],
"image":{
"id":3773678190677,
"product_id":232418213909,
"position":1,
...
}
}
}
So what you need to do should be to iterate over the list of variants under product instead:
import json
import requests
endpoint = "https://www.deadstock.ca/collections/new-arrivals/products/nike-air-max-1-cool-grey.json"
req = requests.get(endpoint)
reqJson = json.loads(req.text)
for product in reqJson['product']['variants']:
print(product['id'], product['title'])
This outputs:
3136193822741 8
3136193855509 8.5
3136193789973 9
3136193757205 9.5
3136193724437 10
3136193691669 10.5
3136193658901 11
3136193626133 12
3136193593365 13
And if you simply want the product id and product name, they would be reqJson['product']['id'] and reqJson['product']['title'], respectively.

how can i take a specific element from this list in python?

I'm working with the Microsoft Azure face API and I want to get only the glasses response.
heres my code:
########### Python 3.6 #############
import http.client, urllib.request, urllib.parse, urllib.error, base64, requests, json
###############################################
#### Update or verify the following values. ###
###############################################
# Replace the subscription_key string value with your valid subscription key.
subscription_key = '(MY SUBSCRIPTION KEY)'
# Replace or verify the region.
#
# You must use the same region in your REST API call as you used to obtain your subscription keys.
# For example, if you obtained your subscription keys from the westus region, replace
# "westcentralus" in the URI below with "westus".
#
# NOTE: Free trial subscription keys are generated in the westcentralus region, so if you are using
# a free trial subscription key, you should not need to change this region.
uri_base = 'https://westcentralus.api.cognitive.microsoft.com'
# Request headers.
headers = {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscription_key,
}
# Request parameters.
params = {
'returnFaceAttributes': 'glasses',
}
# Body. The URL of a JPEG image to analyze.
body = {'url': 'https://upload.wikimedia.org/wikipedia/commons/c/c3/RH_Louise_Lillian_Gish.jpg'}
try:
# Execute the REST API call and get the response.
response = requests.request('POST', uri_base + '/face/v1.0/detect', json=body, data=None, headers= headers, params=params)
print ('Response:')
parsed = json.loads(response.text)
info = (json.dumps(parsed, sort_keys=True, indent=2))
print(info)
except Exception as e:
print('Error:')
print(e)
and it returns a list like this:
[
{
"faceAttributes": {
"glasses": "NoGlasses"
},
"faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
"faceRectangle": {
"height": 162,
"left": 177,
"top": 131,
"width": 162
}
}
]
I want just the glasses attribute so it would just return either "Glasses" or "NoGlasses"
Thanks for any help in advance!
I think you're printing the whole response, when really you want to drill down and get elements inside it. Try this:
print(info[0]["faceAttributes"]["glasses"])
I'm not sure how the API works so I don't know what your specified params are actually doing, but this should work on this end.
EDIT: Thank you to #Nuageux for noting that this is indeed an array, and you will have to specify that the first object is the one you want.
I guess that you can get few elements in that list, so you could do this:
info = [
{
"faceAttributes": {
"glasses": "NoGlasses"
},
"faceId": "0f0a985e-8998-4c01-93b6-8ef4bb565cf6",
"faceRectangle": {
"height": 162,
"left": 177,
"top": 131,
"width": 162
}
}
]
for item in info:
print (item["faceAttributes"]["glasses"])
>>> 'NoGlasses'
Did you try:
glasses = parsed[0]['faceAttributes']['glasses']
This looks more like a dictionary than a list. Dictionaries are defined using the { key: value } syntax, and can be referenced by the value for their key. In your code, you have faceAttributes as a key that for value contains another dictionary with a key glasses leading to the last value that you want.
Your info object is a list with one element: a dictionary. So in order to get at the values in that dictionary, you'll need to tell the list where the dictionary is (at the head of the list, so info[0]).
So your reference syntax will be:
#If you want to store it in a variable, like glass_var
glass_var = info[0]["faceAttributes"]["glasses"]
#Or if you want to print it directly
print(info[0]["faceAttributes"]["glasses"])
What's going on here? info[0] is the dictionary containing several keys, including faceAttributes,faceId and faceRectangle. faceRectangle and faceAttributes are both dictionaries in themselves with more keys, which you can reference to get their values.
Your printed tree there is showing all the keys and values of your dictionary, so you can reference any part of your dictionary using the right keys:
print(info["faceId"]) #prints "0f0a985e-8998-4c01-93b6-8ef4bb565cf6"
print(info["faceRectangle"]["left"]) #prints 177
print(info["faceRectangle"]["width"]) #prints 162
If you have multiple entries in your info list, then you'll have multiple dictionaries, and you can get all the outputs as so:
for entry in info: #Note: "entry" is just a variable name,
# this can be any name you want. Every
# iteration of entry is one of the
# dictionaries in info.
print(entry["faceAttributes"]["glasses"])
Edit: I didn't see that info was a list of a dictionary, adapted for that fact.

Categories

Resources