How to update stock_quantity in python using woocommerce api - python

Trying to follow the api sample from http://woothemes.github.io/woocommerce-rest-api-docs/?python#update-a-product-attribute, but it's not updating the stock_quantity. I've confirmed that I have read/write access set for my api key.
I get the following error from the code below:
u'errors': [{u'message': u'No product data specified to edit product', u'code': u'woocommerce_api_missing_product_data'}]}
Any ideas?
import sys
import json
from woocommerce import API
wcapi = API(
url="http://(myurl)",
consumer_key="ck_<mykey>",
consumer_secret="cs_<mysecret>",
timeout=30
)
data = {
"stock_quantity": 5
}
print(wcapi.put("products/18", data).json())

Ok figured it out. I was using the wrong version of the api documentation. I should have been using v3. The correct code is:
import sys
import json
from woocommerce import API
wcapi = API(
url="http://(myurl)",
consumer_key="ck_<mykey>",
consumer_secret="cs_<mysecret>",
timeout=30
)
data = {
"product": {
"stock_quantity": 5
}
}
print(wcapi.put("products/18", data).json())

In the newest version of the API I found wrapping the product info in the "product" dictionary is not needed:
import sys
import json
from woocommerce import API
wcapi = API(
url="http://(myurl)",
consumer_key="ck_<mykey>",
consumer_secret="cs_<mysecret>",
timeout=30
)
data = {
"stock_quantity": 5
}
print(wcapi.put("products/18", data).json())

Related

Can't pass header in Python client generated by OpenAPI Generator

With the help of OpenAPI Generator I generated a Python client for the Amadeus Travel Restrictions API spec.
According to the README generated, I understand that I can pass headers with the header_params parameter but I receive the following error:
TypeError: g_et_covid_report() got an unexpected keyword argument 'header_params'
Below you can check my code:
import openapi_client
from openapi_client.apis.tags import covid19_area_report_api
from openapi_client.model.disease_area_report import DiseaseAreaReport
from openapi_client.model.error import Error
from openapi_client.model.meta import Meta
from openapi_client.model.warning import Warning
from pprint import pprint
configuration = openapi_client.Configuration(
host = "https://test.api.amadeus.com/v2"
)
with openapi_client.ApiClient(configuration) as api_client:
api_instance = covid19_area_report_api.Covid19AreaReportApi(api_client)
query_params = {
'countryCode': "US",
}
header_params = {
'Authorization': "Bearer MY_ACCESS_TOKEN",
}
try:
api_response = api_instance.g_et_covid_report(
query_params=query_params,
header_params=header_params
)
pprint(api_response)
except openapi_client.ApiException as e:
print("Exception when calling Covid19AreaReportApi->g_et_covid_report: %s\n" % e)
I've been checking the library and also OpenAPI Generator project on GitHub but I still can't find a way to pass header parameters which I need in order to authorise my API call.

When doing a Hubspot API call I get an unspecific error when replacing values with variables

I'm making an API call to Hubspot, and everything works fine until I try to replace the UNIX date with a variable.
First, I get the dates I'm looking for into UNIX format, which Hubspot expects. This works fine:
value = (begin_last_wk_raw - datetime(1970,1,1)).total_seconds()
highValue = (end_last_wk_raw - datetime(1970,1,1)).total_seconds()
print(value)
print(highValue)
To which I get the following response (which seems great):
1665930401.451494
1666535201.451494
I then run the following code:
url = 'https://api.hubapi.com/crm/v3/objects/contacts/search'
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + access_token
}
json_data = {
"filterGroups":[
{
"filters":[
{
"propertyName":"createdate",
"operator":"GTE",
"highValue": highValue,
"value": value
}
]
}
]
}
response = requests.post(url, headers=headers, data=json.dumps(json_data))
After which I get the following error:
'{"status":"error","message":"There was a problem with the request.","correlationId":"0a9e1fe0-0e80-4571-b610-e0ad05645baa"}'
My code is pretty bloated, but here are the necessary packages I've imported:
import logging
import requests
import pandas as pd
import json
from dotenv import load_dotenv
import datetime
from datetime import date
from datetime import datetime, timedelta
import gspread
from gspread_dataframe import set_with_dataframe
from hubspot import HubSpot
from hubspot.crm.contacts import ApiException
import os
load_dotenv()
I'm expecting to get data based on the new date range. I've verified that the date range contained in the variables does have data (by doing the query within Hubspot).
Again, when I enter the dates in UNIX format into the JSON section (i.e. "highValue" and "value"), I get error-free results. It's only when I try to replace the values with the variables "highValue" and "value" do I see a problem.
I tried searching Google for this error, but it didn't return much in the way of results, and I'm not sure if the error message is very specific anyway.

Use iot_v1 in a GCP Cloud Function

I'm attempting to write a GCP Cloud Function in Python that calls the API for creating an IoT device. The initial challenge seems to be getting the appropriate module (specifically iot_v1) loaded within Cloud Functions so that it can make the call.
Example Python code from Google is located at https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iot/api-client/manager/manager.py. The specific call desired is shown in "create_es_device". Trying to repurpose that into a Cloud Function (code below) errors out with "ImportError: cannot import name 'iot_v1' from 'google.cloud' (unknown location)"
Any thoughts?
import base64
import logging
import json
import datetime
from google.auth import compute_engine
from apiclient import discovery
from google.cloud import iot_v1
def handle_notification(event, context):
#Triggered from a message on a Cloud Pub/Sub topic.
#Args:
# event (dict): Event payload.
# context (google.cloud.functions.Context): Metadata for the event.
#
pubsub_message = base64.b64decode(event['data']).decode('utf-8')
logging.info('New device registration info: {}'.format(pubsub_message))
certData = json.loads(pubsub_message)['certs']
deviceID = certData['device-id']
certKey = certData['certificate']
projectID = certData['project-id']
cloudRegion = certData['cloud-region']
registryID = certData['registry-id']
newDevice = create_device(projectID, cloudRegion, registryID, deviceID, certKey)
logging.info('New device: {}'.format(newDevice))
def create_device(project_id, cloud_region, registry_id, device_id, public_key):
# from https://cloud.google.com/iot/docs/how-tos/devices#api_1
client = iot_v1.DeviceManagerClient()
parent = client.registry_path(project_id, cloud_region, registry_id)
# Note: You can have multiple credentials associated with a device.
device_template = {
#'id': device_id,
'id' : 'testing_device',
'credentials': [{
'public_key': {
'format': 'ES256_PEM',
'key': public_key
}
}]
}
return client.create_device(parent, device_template)
You need to have the google-cloud-iot project listed in your requirements.txt file.
See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/iot/api-client/manager/requirements.txt

Text not being added when using Slides API to change text

I am currently trying to automatically update a slide in a Google Slide presentation with the Slides API and when I run the code it does not seem to update.
My current code is:
from datetime import datetime
from datetime import timedelta
from oauth2client.client import GoogleCredentials
from google.oauth2 import service_account
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
from apiclient import discovery
import httplib2
import json
import requests
import string
credentials = service_account.Credentials.from_service_account_file("credentials.json")
service = build('slides', 'v1', credentials=credentials)
#Getting the lunch for the next day
tomorrow = datetime.now() + timedelta(days=1)
url = tomorrow.strftime("https://udas.nutrislice.com/menu/api/digest/school/upper-dauphin-high/menu-type/lunch/date/%Y/%m/%d/")
data = requests.get(url)
test = data.json()['menu_items']
#Converting the lunch to look nice and printing it
lunchtext = json.dumps(test, indent=4, sort_keys=True, separators=('\n', ':'))
newlunchtext = lunchtext.replace(r'"', ' ')
newlunchtext = newlunchtext.replace(r'[', r'"')
newlunchtext = newlunchtext.replace(r']', r'"')
print(newlunchtext)
#Preparing to make the request
PRESENTATION_ID = '1DE0NxsRH6nWxlZGsOP-IzZD-qodw_0YLcMKE0QaQ7vE'
OBJECT_ID = 'g6d3de38d16_0_115'
requests = [
{
'insertText': {
'text': newlunchtext
},
'objectId': OBJECT_ID,
'insertionIndex': 0,
},
]
body = {
'requests': requests
}
update = service.presentations().batchUpdate(presentationId = PRESENTATION_ID, body = body).execute
print(update)
When I run it I get a response that looks like this:
"
French Toast Sticks & Sausage
Pulled Pork BBQ on Bun
McCain Crispy Tater Tots
Garden Salad
"
<bound method HttpRequest.execute of <googleapiclient.http.HttpRequest object at 0x105519c70>>
I am not sure why it is not working as I have the correct objectId and presentationId.
Answer:
There are a couple of issues with your code: the request JSON and the execution of the batchUpdate
More Information:
Firstly, as per the request documentation of the Slides API, both objectId and insertionIndex are representations that should be included inside the insertText resource. This needs to be changed as such:
requests = [
{
'insertText': {
'text': newlunchtext,
'objectId': OBJECT_ID,
'insertionIndex': 0,
},
},
]
The other issue is that yo uare not executing the batchUpdate only referencing it. You need to add parentheses in order to call the execute() function:
update = service.presentations().batchUpdate(presentationId = PRESENTATION_ID, body = body).execute()
As a side note - do remember that your service account also needs to have edit access to the Slide for it to be able to make changes.
References:
Google Slides API - Method: presentations.batchUpdate
Google Slides API - batchUpdate: Requests
Google Slides API - Python Quickstart - Set up the sample

Azure module on webservice

I am trying to publish a machine learning model on Azure webservice using python. I am able to deploy the code successfully but when i try to call it through the URL, it's throwing me 'Azure' module doesn't exist. The code basically retrieves a TFIDF model from the container (blob) and use it to predict the new value. The error clearly says, Azure package is missing while trying to run on the webservice and I am not sure how to fix it. Here goes the code:
For deployment:
from azureml import services
from azure.storage.blob import BlobService
#services.publish('7c94eb2d9e4c01cbe7ce1063','f78QWNcOXHt9J+Qt1GMzgdEt+m3NXby9JL`npT7XX8ZAGdRZIX/NZ4lL2CkRkGQ==')
#services.types(res=unicode)
#services.returns(str)
def TechBot(res):
from azure.storage.blob import BlobService
from gensim.similarities import SparseMatrixSimilarity, MatrixSimilarity, Similarity
blob_service = BlobService(account_name='tfidf', account_key='RU4R/NIVPsPOoR0bgiJMtosHJMbK1+AVHG0sJCHT6jIdKPRz3cIMYTsrQ5BBD5SELKHUXgBHNmvsIlhEdqUCzw==')
blob_service.get_blob_to_path('techbot',"2014.csv","df")
df=pd.read_csv("df")
doct = res
To access the url I used the python code from
service.azureml.net
import urllib2
import json
import requests
data = {
"Inputs": {
"input1":
[
{
'res': "wifi wnable",
}
],
},
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
#proxies = {"http":"http://%s" % proxy}
url = 'http://ussouthcentral.services.azureml.net/workspaces/7c94eb2de26a45399e4c01cbe7ce1063/services/11943e537e0741beb466cd91f738d073/execute?api-version=2.0&format=swagger'
api_key = '8fH9kp67pEt3C6XK9sXDLbyYl5cBNEwYg9VY92xvkxNd+cd2w46sF1ckC3jqrL/m8joV7o3rsTRUydkzRGDYig==' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
#proxy_support = urllib2.ProxyHandler(proxies)
#opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
#urllib2.install_opener(opener)
req = urllib2.Request(url, body, headers)
try:
response = urllib2.urlopen(req, timeout=60)
result = response.read()
print(result)
except urllib2.HTTPError, error:
print("The request failed with status code: " + str(error.code))
# Print the headers - they include the requert ID and the timestamp, which are useful for debugging the failure
print(error.info())
print(json.loads(error.read()))
The string 'res' will be predicted at the end. As I said it runs perfectly fine if I run as it is in python by calling azure module, problem happens when I access the url.
Any help is appreciated, please let me know if you need more information (I only sohwcased half of my code)
I tried to reproduce the issue via POSTMAN, then I got the error information below as you said.
{
"error": {
"code": "ModuleExecutionError",
"message": "Module execution encountered an error.",
"details": [
{
"code": "85",
"target": "Execute Python Script RRS",
"message": "Error 0085: The following error occurred during script evaluation, please view the output log for more information:\r\n---------- Start of error message from Python interpreter ----------\r\nCaught exception while executing function: Traceback (most recent call last):\n File \"\\server\\InvokePy.py\", line 120, in executeScript\n outframe = mod.azureml_main(*inframes)\n File \"\\temp\\1280677032.py\", line 1094, in azureml_main\n File \"<ipython-input-15-bd03d199b8d9>\", line 6, in TechBot_2\nImportError: No module named azure\n\r\n\r\n---------- End of error message from Python interpreter ----------"
}
]
}
}
According to the error code 00085 & the information ImportError: No module named azure, I think the issue was caused by importing python moduleazure-storage. There was a similar SO thread Access Azure blog storage from within an Azure ML experiment which got the same issue, I think you can refer to its answer try to use HTTP protocol instead HTTPS in your code to resolve the issue as the code client = BlobService(STORAGE_ACCOUNT, STORAGE_KEY, protocol="http").
Hope it helps. Any concern & update, please feel free to let me know.
Update: Using HTTP protocol for BlobService
from azureml import services
from azure.storage.blob import BlobService
#services.publish('7c94eb2d9e4c01cbe7ce1063','f78QWNcOXHt9J+Qt1GMzgdEt+m3NXby9JL`npT7XX8ZAGdRZIX/NZ4lL2CkRkGQ==')
#services.types(res=unicode)
#services.returns(str)
def TechBot(res):
from azure.storage.blob import BlobService
from gensim.similarities import SparseMatrixSimilarity, MatrixSimilarity, Similarity
# Begin: Update code
# Using `HTTP` protocol for BlobService
blob_service = BlobService(account_name='tfidf',
account_key='RU4R/NIVPsPOoR0bgiJMtosHJMbK1+AVHG0sJCHT6jIdKPRz3cIMYTsrQ5BBD5SELKHUXgBHNmvsIlhEdqUCzw==',
protocol='http')
# End
blob_service.get_blob_to_path('techbot',"2014.csv","df")
df=pd.read_csv("df")
doct = res

Categories

Resources