Creating an un-stockable bundle item pointing to multiple variations/items - python

I need to create a "bundled" item that points to items I reference by item_id. In other terms, this is an 'un-stockable' item that is not tracked by inventory rather when it is sold it deducts the inventory of only the linked item/variations. I cannot figure this out using Square's Endpoint API. So far I have:
result = client.catalog.upsert_catalog_object(
body={
"idempotency_key": str(idempotency_key),
"object": {
"type": "ITEM",
"id": "#Cocoa_bundle",
"item_data": {
"name": "Cocoa Bundle",
"description": "Hot Chocolate Bundle of Small and Large sizes",
"abbreviation": "CB",
"item_variation_ids": ["H6EK5FZ4MMJB56FFASFNYZXC", "NZGVV7TXJHVUMNQAY743FRQX"],
"track_inventory": False,
}
}
}
)
And I recieve:
"category": "INVALID_REQUEST_ERROR",
"code": "BAD_REQUEST",
"detail": "Item with name Cocoa Bundle and token #Cocoa_bundle must have at least one variation."
However, this will create a new "variation" of an item rather than creating a bundle. It needs to be an item linked to the variations: 'item_variation_ids'. Is it possible to create a bundle as such?

Related

Uniswap Graph QL Wrong Price

I'm working on a DeFi price bot for python practice. I thought my code had been bugged, when it calculated the price of WETH to ADS.
After auditing my code and realizing it was calculating the correct way, I went further up in the chain and got that the data coming from Uniswap's Graph QL is actually where the error is. Here is the info being given to me by GraphQL, relating to the price of ADS/WETH
{
"id": "0xb9044f46dcdea7ecebbd918a9659ba8239bd9f37",
"totalValueLockedETH": "9904.271380202576136314291146113488",
"token0Price": "0.001320257312519524061776624436378727",
"token1Price": "757.4281092915453379114232503540107",
"feeTier": "10000",
"token0": {
"id": "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2",
"symbol": "WETH",
"name": "Wrapped Ether",
"decimals": "18"
},
"token1": {
"id": "0xcfcecfe2bd2fed07a9145222e8a7ad9cf1ccd22a",
"symbol": "ADS",
"name": "Adshares",
"decimals": "11"
}
},
As you can see in token0Price, we are being given "0.0013..." for the price.
However, manually selecting ADS -> WETH in Uniswap's dapp, gives the price: "0.00078".
Am I using GraphQL wrong? Or is this an issue on the Uniswap side?

Retrieving data from a Python Tuple

I am trying to retrieve and reuse data from a JSON object in a for loop in Python. An example of a single JSON object below:
{
"id": "123456789",
"envs": [
"env:remote1",
"env:remote2",
"env:remote3"
],
"moves": {
"sequence1": "half glass full",
"sequence2": "half glass empty"
}
}
For loop example
for i in ids:
print(i["envs"])
print(i["moves"])
envs will be successfully printed since it is a list. However, since moves is a tuple I receive a KeyError as it is looking for a key in a dictionary. What is the Python recommended way of pulling data from a tuple in this instance. For example, I want to print sequence1 or sequence2.
Thanks
It appears you made a typographic error.
From this code
ids = [
{
"id": "123456789",
"envs": [
"env:remote1",
"env:remote2",
"env:remote3",
],
"moves": {
"sequence1": "half glass full",
"sequence2": "half glass empty",
},
}
]
for i in ids:
print(i["envs"])
print(i["moves"])
I obtain these results
['env:remote1', 'env:remote2', 'env:remote3']
{'sequence1': 'half glass full', 'sequence2': 'half glass empty'}

Importing JSON data from a file as class instances

class Company:
def __init__(self, company_id, name):
self.company_id = company_id
self.name = name
I have a class named Company (class shown above), and I am trying to add companies into this program using this JSON file:
[
{
"id": "companyA",
"name": "Apple Farm"
},
{
"id": "companyB",
"name": "Buzzing Bees"
},
{
"id": "companyC",
"name": "Cat Corporate"
},
{
"id": "companyD",
"name": "Dog Dentists Limited"
}
]
Right now I, know how to add each company individually like this:
c = Company(company[0]['id'], company[0]['name'])
However, I want to create all of them with a for loop which creates these companies, and so that I can access them by their company_id.
How can I do this?
I dint understand the last part of the question where you say you want to "call them by company IDs"..
If you dont want to handle each objects independently and reference it by their name then storing them in a dict is a useful way. A dictionary comprehension will be the easiest way to do it.
company_objects = {company['id']: Company(company['id'], company['name']) for company in companies}
Now you should be able to access them as company_objects['companyA']
If you change the JSON definition slightly as below:
{
"company_id": "companyA",
"name": "Apple Farm"
}
You will be able to even optimize the dictionary comprehension as below:
{company['company_id']: Company(**company) for company in companies}
You can first retrieve the JSON code with the json library:
import json
with open("path/to/file.json") as jsonFile: # Replace "path/to/file.json" with the path to your JSON file
companies = json.load(jsonFile)
Then, you can create a dictionary to store the companies:
companyDict = {}
You then iterate through all the companies in the JSON file. Then, for every dictionary inside the JSON file, create a Company:
for company in companies:
companyDict[company["id"]] = Company(company["id"], company["name"])
You can then access your company like this:
companyA = companyDict["companyA"] # You can replace the key with the company ID
From the looks of your class, it looks as though it is not meant to contain information pertaining to multiple companies. Rather, you should create a separate class instance for each company.
Using the object you provided as such:
companies = [
{
"id": "companyA",
"name": "Apple Farm"
},
{
"id": "companyB",
"name": "Buzzing Bees"
},
{
"id": "companyC",
"name": "Cat Corporate"
},
{
"id": "companyD",
"name": "Dog Dentists Limited"
}
]
you can create a class for each company as such:
company_classes = [Company(company.id, company.name) for company in companies]
this will create a list of company objects.

Python: Iterate JSON and remove items with specific criteria

I am trying to filter out data from API JSON response with Python and I get weird results. I would be glad if somebody can guide me how to deal with the situation.
The main idea is to remove irrelevant data in the JSON and keep only the data that is associated with particular people which I hold in a list.
Here is a snip of the JSON file:
{
"result": [
{
"number": "Number1",
"short_description": "Some Description",
"assignment_group": {
"display_value": "Some value",
"link": "https://some_link.com"
},
"incident_state": "Closed",
"sys_created_on": "2020-03-30 11:51:24",
"priority": "4 - Low",
"assigned_to": {
"display_value": "John Doe",
"link": "https://some_link.com"
}
},
{
"number": "Number2",
"short_description": "Some Description",
"assignment_group": {
"display_value": "Some value",
"link": "https://some_link.com"
},
"incident_state": "Closed",
"sys_created_on": "2020-03-10 11:07:13",
"priority": "4 - Low",
"assigned_to": {
"display_value": "Tyrell Greenley",
"link": "https://some_link.com"
}
},
{
"number": "Number3",
"short_description": "Some Description",
"assignment_group": {
"display_value": "Some value",
"link": "https://some_link.com"
},
"incident_state": "Closed",
"sys_created_on": "2020-03-20 10:23:35",
"priority": "4 - Low",
"assigned_to": {
"display_value": "Delmar Vachon",
"link": "https://some_link.com"
}
},
{
"number": "Number4",
"short_description": "Some Description",
"assignment_group": {
"display_value": "Some value",
"link": "https://some_link.com"
},
"incident_state": "Closed",
"sys_created_on": "2020-03-30 11:51:24",
"priority": "4 - Low",
"assigned_to": {
"display_value": "Samual Isham",
"link": "https://some_link.com"
}
}
]
}
Here is the Python code:
users_test = ['Ahmad Wickert', 'Dick Weston', 'Gerardo Salido', 'Rosendo Dewey', 'Samual Isham']
# Load JSON file
with open('extract.json', 'r') as input_file:
input_data = json.load(input_file)
# Create a function to clear the data
def clear_data(data, users):
"""Filter out the data and leave only records for the names in the users_test list"""
for elem in data:
print(elem['assigned_to']['display_value'] not in users)
if elem['assigned_to']['display_value'] not in users:
print('Removing {} from JSON as not present in list of names.'.format(elem['assigned_to']['display_value']))
data.remove(elem)
else:
print('Keeping the record for {} in JSON.'.format(elem['assigned_to']['display_value']))
return data
cd = clear_data(input_data['result'], users_test)
And here is the output, which seems to iterate through only 2 of the items in the file:
True
Removing John Doe from JSON as not present in list of names.
True
Removing Delmar Vachon from JSON as not present in list of names.
Process finished with exit code 0
It seems that the problem is more or less related to the .remove() method however I don't find any other suitable solution to delete these particular items that I do not need.
Here is the output of the iteration without applying the remove() method:
True
Removing John Doe from JSON as not present in list of names.
True
Removing Tyrell Greenley from JSON as not present in list of names.
True
Removing Delmar Vachon from JSON as not present in list of names.
False
Keeping the record for Samual Isham in JSON.
Process finished with exit code 0
Note: I have left the check for the name visible on purpose.
I would appreciate any ideas to sort out the situation.
If you don't need to log info about people you are removing you could simply try
filtered = [i for i in data['result'] if i['assigned_to']['display_value'] in users_test]
users_test = ['Ahmad Wickert', 'Dick Weston', 'Gerardo Salido', 'Rosendo Dewey', 'Samual Isham']
solution = []
for user in users_test:
print(user)
for value in data['result']:
if user == value['assigned_to']['display_value']:
solution.append(value)
print(solution)
for more efficient code, as asked by #NomadMonad
solution = list(filter(lambda x: x['assigned_to']['display_value'] in users_test, data['result']))
You are modifying a dictionary while at the same time iterating through it. Check out this blog post which describes this behavior.
A safer way to do this is to make a copy of your dictionary to iterate over, and to delete from your original dictionary:
import copy
def clear_data(data, users):
"""Filter out the data and leave only records for the names in the users_test list"""
for elem in copy.deepcopy(data): # deepcopy handles nested dicts
# Still call data.remove() in here

Accessing nested objects with python

I have a response that I receive from foursquare in the form of json. I have tried to access the certain parts of the object but have had no success. How would I access say the address of the object? Here is my code that I have tried.
url = 'https://api.foursquare.com/v2/venues/explore'
params = dict(client_id=foursquare_client_id,
client_secret=foursquare_client_secret,
v='20170801', ll=''+lat+','+long+'',
query=mealType, limit=100)
resp = requests.get(url=url, params=params)
data = json.loads(resp.text)
msg = '{} {}'.format("Restaurant Address: ",
data['response']['groups'][0]['items'][0]['venue']['location']['address'])
print(msg)
Here is an example of json response:
"items": [
{
"reasons": {
"count": 0,
"items": [
{
"summary": "This spot is popular",
"type": "general",
"reasonName": "globalInteractionReason"
}
]
},
"venue": {
"id": "412d2800f964a520df0c1fe3",
"name": "Central Park",
"contact": {
"phone": "2123106600",
"formattedPhone": "(212) 310-6600",
"twitter": "centralparknyc",
"instagram": "centralparknyc",
"facebook": "37965424481",
"facebookUsername": "centralparknyc",
"facebookName": "Central Park"
},
"location": {
"address": "59th St to 110th St",
"crossStreet": "5th Ave to Central Park West",
"lat": 40.78408342593807,
"lng": -73.96485328674316,
"labeledLatLngs": [
{
"label": "display",
"lat": 40.78408342593807,
"lng": -73.96485328674316
}
],
the full response can be found here
Like so
addrs=data['items'][2]['location']['address']
Your code (at least as far as loading and accessing the object) looks correct to me. I loaded the json from a file (since I don't have your foursquare id) and it worked fine. You are correctly using object/dictionary keys and array positions to navigate to what you want. However, you mispelled "address" in the line where you drill down to the data. Adding the missing 'a' made it work. I'm also correcting the typo in the URL you posted.
I answered this assuming that the example JSON you linked to is what is stored in data. If that isn't the case, a relatively easy way to see exact what python has stored in data is to import pprint and use it like so: pprint.pprint(data).
You could also start an interactive python shell by running the program with the -i switch and examine the variable yourself.
data["items"][2]["location"]["address"]
This will access the address for you.
You can go to any level of nesting by using integer index in case of an array and string index in case of a dict.
Like in your case items is an array
#items[int index]
items[0]
Now items[0] is a dictionary so we access by string indexes
item[0]['location']
Now again its an object s we use string index
item[0]['location']['address]

Categories