I want my Echonest response to get song duration, which is supposed to be part of the audio_summary.
params = {
'type':'artist-radio',
'artist':artist,
'results': 3,
'bucket' : ['id:spotify-WW', 'tracks'],
'limit': True
}
response = en.get('playlist/static', **params)
songs = response['songs']
so, to get song duration, which key/value should I use in the example above?
NOTE: the wrapper being used is pyen
durationis an analysis found in song/profile, and not in playlist/static method, so we need a second response from the api.
this is one way of obtaining each song duration (as well as printing artist_name and song_title):
#get 'playlist response'
response_playlist = en.get('playlist/static', **params)
song_playlist = response_playlist['songs']
if len(song_playlist) > 0:
for i, song in enumerate(song_playlist):
#we need to track each song id
song_id = song_playlist[i]['id'] #ok
#in order to get song 'duration', we need to access 'song/profile response'
#and pass the id as an argument to 'audio_summary'
response_profile = en.get('song/profile', id=song_id, bucket="audio_summary")
song_profile = response_profile['songs']
dur = song_profile[0]['audio_summary']['duration']
print dur
#now we access each song 'foreign_id', which is playable by, say, Spotify
for track in song:
track = song['tracks'][i]
track_id = track['foreign_id'].replace('-WW', '')
print '{0} {2} {1}'.format(i, song['artist_name'], song['title'])
Related
I'm trying to set inventory quantity of a product in shopify using the Shopify Python Api.
As i understand it, i need to set the 'inventory_level' of the 'inventory_item' that belongs to the product, but after a few days of searching and testing i still have no luck.
Where i'm at
I have my products showing up in my store with all the data but the inventory quantity.
I'm not sure how to proceed as there's not a whole lot of documentation.
Here's my code for creating a product
def CreateShopifyProduct(data):
# CREATE PRODUCT
product = shopify.Product()
# Add stuff to product, variant and inventoryItem here
product.title = data['title']
#product.status = ""
#product.tags = data['tags']
product.body_html = data['description']
if 'catagory' in data:
product.product_type = data['category']
if 'vendor' in data:
product.vendor = data['vendor']
if 'image_url' in data:
image_path = data['image_url']
image = shopify.Image()
image.src = image_path
product.images = [image]
else:
try:
image = GetLocalImageFiles(data['id'])
product.images = [image]
except:
print("No local images found")
success = product.save() #returns false if the record is invalid
# CREATE VARIANT
variant = shopify.Variant()
if 'ean' in data:
variant.barcode = data['ean']
variant.price = data['gross_price']
variant.weight = data['weight']
#variant.count = data['inventory']
variant.inventory_management = 'shopify'
product.variants = [variant]
variant.product_id = product.id
s = variant.save()
success = product.save() #returns false if the record is invalid
# CREATE INVENTORYITEM
inventoryItem = shopify.InventoryItem()
#inventoryItem = variant.inventory_item
inventoryItem.tracked = True
inventoryItem.id = product.id
variant.inventory_quantity = data['inventory']
inventoryItem.inventory_quantity = data['inventory']
variant.inventory_item = inventoryItem
s = variant.save()
success = product.save()
#ii = inventoryItem.save() # this returns 406
#inv_level = shopify.InventoryLevel.find(inventory_item_ids=6792364982390, location_ids=61763518582)
#quantity = inv_level[0].__dict__['attributes']['available']
#shopify.InventoryLevel.set(location_id=61763518582, inventory_item_id=variant.inventory_item.id, available=data['inventory'])
#shopify.InventoryLevel.connect(61763518582, variant.inventory_item.id)
if product.errors:
#something went wrong, see new_product.errors.full_messages() for example
print("error")
print(product.errors.full_messages())
If i try to set the InventoryLevel with
shopify.InventoryLevel.set(61527654518, inventoryItem.id, 42)
# or
shopify.InventoryLevel.set(location_id=61527654518, inventory_item_id=inventoryItem.id, available=17)
I recieve a
pyactiveresource.connection.ResourceNotFound: Not Found: https://domain.myshopify.com/admin/api/2022-07/inventory_levels/set.json
You need three things to update an inventory level. One, you need a valid location ID. Two, you need the inventory item ID. Finally, you need the amount to adjust inventory to, that will adjust the inventory there to match your needs.
You should really play at the command-line and ensure you can quickly get the information you need, then try your updates. In other words, ensure you are getting a good location ID, inventory item ID and finally, that you know the amount of inventory already in Shopify. Since you have to calculate a delta change, these are the minimum steps most people take.
Note that once you get good at doing one item, you'll realize Shopify also accepts up to 100 at a time, making your updates a lot faster.
How to check item is exists and renew value only, if not exists and add new one?
For example:
I have an item 1 and value 1 already in my sheet, and then I get new value of item 1, I want to renew value 1 only, otherwise, if I get new item 2 and value 2, I want to add this in new columns.
I don't know how to write code, I search it long time but cannot found, could anyone help me? Many thanks!
The script below, the steps are:
first step, check my gmail get keyword 1
second, use keyword search datas in website (beautifulsoup module)
the last step, upload datas to google sheet (gspread module)
def Check_emailbox(box='Inbox', lab='SUBJECT', title='[PASS]'):
global email_content, report_info1, my_msg, report_info
dirpath = 'XXX'
with open(dirpath) as act:
content = act.read()
my_act = yaml.load(content, Loader=yaml.FullLoader)
user, password = my_act['user'], my_act['password']
imapUrl = 'imap.gmail.com'
my_mail = imaplib.IMAP4_SSL(imapUrl)
my_mail.login(user, password)
print('Login gmail account seccess.')
my_mail.select(box)
key = lab
value = title
_, data = my_mail.search(None, key, value)
mail_id_list = data[0].split()
msg_id = mail_id_list[-1]
res, data = my_mail.fetch(msg_id, '(RFC822)')
report_info = []
if res == 'OK':
raw_msg_txt = data[0][1]
try:
my_msg = email.message_from_bytes(raw_msg_txt)
print('Subject: ', my_msg['subject'])
print('From: ', my_msg['from'])
print('Time: ', my_msg['date'])
print('------------------------------------------------------------------------------------')
print('Content:')
for part in my_msg.walk():
email_content = part.get_payload()
report_info.append(email_content)
report_info1 = ''.join('%s' % id for id in report_info)
print(report_info1, type(report_info1))
# print('Hide info, if want to see detail, unmark previous code')
print('------------------------------------------------------------------------------------')
# my_mail.store(msg_id, '-FLAGS', '\SEEN')
except AttributeError:
my_msg = email.message_from_string(raw_msg_txt)
print('AttributeError: ', my_msg)
return email_content, my_msg, report_info, report_info1
Check_emailbox()
keyName = re.findall(r'Daily Report : (.*?)$', report_info1)
fwName = ''.join(keyName)
print(fwName)
# ↑ This data will be upload to sheet, and this is main item for check:
# if "feName" is exists, renew below datas only, if not exists, add new one in next row.
fwVersion = ''.join(re.findall(r'\d-(.*?)-', fwName)).rsplit('.',1)[0]
print(fwVersion)
# connect to the website and use beautifulsoup
ele = requests.get('XXXXXX')
felement = BeautifulSoup(ele.text, 'html.parser')
# print(felement.prettify())
fwinfo = felement.find(['a'], text = fwName)
fwhref = fwinfo.get('href')
print('Info: ', fwinfo)
print(fwhref)
rowid = ''.join(re.findall(r'data/(.*?)$', fwhref))
print('Download id is: ', rowid)
fwlink = 'XXXXXXXXX' + rowid
print('Download link: ', fwlink)
json_key = "XXXXXXX"
spread_url = ['https://spreadsheets.google.com/feeds']
connect_auth = SAC.from_json_keyfile_name(json_key, spread_url)
google_sheets = gspread.authorize(connect_auth)
sheet = google_sheets.open_by_key('XXXXXXXXX').worksheet('Pass Data')
Sheets = sheet
upload = []
upload.append(fwName)
upload.append(fwVersion)
upload.append(rowid)
upload.append(fwlink)
Sheets.append_row(upload)
print('==== Uplod to Google Sheet Done. ====')
In your situation, how about the following modification?
Modified script:
In this case, please use your google_sheets.
# Please set your values here.
fwName = "###"
fwVersion = "###"
rowid = "###"
fwlink = "###"
sheet = google_sheets.open_by_key('XXXXXXXXX').worksheet("Pass Data")
values = sheet.get_all_values()[2:]
obj = {}
for i, r in enumerate(values):
obj[r[0]] = i + 3
if obj.get(fwName):
sheet.update("B" + str(obj.get(fwName)), [[fwVersion, rowid, fwlink]], value_input_option="USER_ENTERED")
When this script is run, first, the values are retrieve from the sheet. And, by searching the value of column "A", new value is put to the searched row.
Note:
I prepared this modified script using your sample image. In your sample image, the 1st 2 rows are header rows. And, the search column is the column "A". I used them. So, when you change your Spreadsheet, this script might not be able to be used. Please be careful about this.
References:
update(range_name, values=None, **kwargs)
get_all_values(**kwargs)
I'm creating a customer in square and getting the results as follows. What I need is to get the id of customer.
My code :
from square.client import Client
client = Client(
access_token=settings.SQUARE_ACCESS_TOKEN,
environment=settings.SQUARE_ENVIRONMENT,
)
api_customers = client.customers
request_body = {'idempotency_key': idempotency_key, 'given_name': name, 'company_name': company,'phone_number':phone}
result = api_customers.create_customer(request_body)
And this is the output:
<ApiResponse [{"customer":
{"id": "F8M9KDHWPMYGK2108RMQVQ6FHC",
"created_at": "2020-10-22T09:14:50.159Z",
"updated_at": "2020-10-22T09:14:50Z",
"given_name": "mkv5",
"phone_number": "900000066666",
"company_name": "codesvera",
"preferences": {"email_unsubscribed": false},
"creation_source": "THIRD_PARTY"}
}
]>
Are you using this library ?
https://github.com/square/square-python-sdk/blob/master/square/http/api_response.py
if yes result is an array and APiResponse object.
so first you should do that : result = result.body
then to get the ID: result['customer']['id']
Ps : You have exemple in the github doc :
https://github.com/square/square-python-sdk
# Initialize the customer count
total_customers = 0
# Initialize the cursor with an empty string since we are
# calling list_customers for the first time
cursor = ""
# Count the total number of customers using the list_customers method
while True:
# Call list_customers method to get all customers in this Square account
result = api_customers.list_customers(cursor)
if result.is_success():
# If any customers are returned, the body property
# is a list with the name customers.
# If there are no customers, APIResponse returns
# an empty dictionary.
if result.body:
customers = result.body['customers']
total_customers += len(customers)
# Get the cursor if it exists in the result else set it to None
cursor = result.body.get('cursor', None)
print(f"cursor: {cursor}")
else:
print("No customers.")
break
# Call the error method to see if the call failed
elif result.is_error():
print(f"Errors: {result.errors}")
break
# If there is no cursor, we are at the end of the list.
if cursor == None:
break
print(f"Total customers: {total_customers}")
I'm doing a data analysis project using spotipy and numpy libraries. I've figured out how to achieve my expected result, but I don't know exactly why a slight change (using a for loop) to my code causes it to not work. here is my code:
def get_user_playlist(username, playlist_id, sp):
offset=0
playlist_songs = sp.user_playlist_tracks(username, playlist_id, limit=100, fields=None, offset=offset, market=None)['items']
return playlist_songs
def create_dataframe(playlist_songs):
playlist_df_columns = ['artist','track_name','id','explicit','duration','danceability','loudness','tempo']
#audio_analysis_columns = ['danceability','loudness','tempo']
playlist_df = pd.DataFrame(columns=df_columns)
# song = dict object containing song
playlist_df['artist'] = np.array([song['track']["album"]["artists"][0]["name"] for song in playlist_songs])
playlist_df['track_name'] = np.array([song['track']['name'] for song in playlist_songs])
playlist_df['id'] = np.array([song['track']['id'] for song in playlist_songs])
playlist_df['explicit'] = np.array([song['track']['explicit'] for song in playlist_songs])
for song in playlist_songs:
audio_analysis = sp.audio_features(song['track']['id'])
#returning audio_analysis for testing purposes.
return audio_analysis
#return playlist_df
the important part is the for loop, when I run this code, the length of the audio_analysis list = 1 :
for song in playlist_songs:
audio_analysis = sp.audio_features(song['track']['id'])
However, it works when I remove the for loop and do this instead, the length of the audio_analysis list = 94, as expected.:
audio_analysis = sp.audio_features(playlist_df['id'])
For reference, here is the code that prints the length:
playlist = get_user_playlist('username', 'playlist_name', sp)
audio_analysis = create_dataframe(playlist)
print(len(audio_analysis))
My question is: why does the for loop not work as I expect? Is my code not accessing the same information? Why isn't using a for loop to access information the same as using the playlist_df['id'] column directly?
I was trying to grab a list of prices. So far my code for such a thing is:
def steamlibrarypull(steamID, key):
#Pulls out a CSV of Steam appids.
steaminfo = {
'key': key,
'steamid': steamID,
'format':'JSON',
'include_appinfo':'1'
}
r = requests.get('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/', params=steaminfo)
d = json.loads(r.content)
I = d['response']['games']
B = {}
for games in I:
B[games['name'].encode('utf8')] = games['appid']
with open('games.csv', 'w') as f:
for key, value in B.items():
f.write("%s,%s\r\n" % (key, value))
return B
But I'd like to be able to do a request.get that'll take this dictionary and ouput out a list of prices. https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI Seems to require the need of a CSV list but is that really necessary?
this is a non formal steam api meaning steam modifies as they see fit. currently it does not support multiple appids as noted here.
to use it to get the price of a game you would go
http://store.steampowered.com/api/appdetails/?appids=237110&cc=us&filters=price_overview
working from the code you have above you will need to know how to iterate through the dictionary and update the store price once you get it back.
def steamlibrarypull(steamID, key):
#Pulls out a CSV of Steam appids.
steaminfo = {
'key': key,
'steamid': steamID,
'format':'JSON',
'include_appinfo':'1'
}
r = requests.get('http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/', params=steaminfo)
d = json.loads(r.content)
response = d['response']['games']
games = {}
for game in response:
getprice = requests.get('http://store.steampowered.com/api/appdetails/?appids=%d&filters=price_overview&cc=us' % game['appid'])
if getprice.status_code == 200:
rjson = json.loads(getprice.text)
# use the appid to fetch the value and convert to decimal
# appid is numeric, cast to string to lookup the price
try:
price = rjson[str(game['appid'])]['data']['price_overview']['initial'] * .01
except:
price = 0
games[game['name']] = {'price': price, 'appid': game['appid']}
this will return the following dictionary:
{u'Half-Life 2: Episode Two': {'price': 7.99, 'appid': 420}
it would be easier to navigate via appid instead of name but as per your request and original structure this is how it should be done. this then gives you the name, appid and price that you can work with further or write to a file.
note that this does not include a sleep timer, if your list of games is long you should sleep your api calls for 2 seconds before making another one or the api will block you and will not return data which will cause an error in python when you parse the price.