I’m implementing a service in Python that interacts with Magento through SOAP v2. So far, I’m able to get the product list doing something like this:
import suds
from suds.client import Client
wsdl_file = 'http://server/api/v2_soap?wsdl=1'
user = 'user'
password = 'password'
client = Client(wsdl_file) # load the wsdl file
session = client.service.login(user, password) # login and create a session
client.service.catalogProductList(session)
However, I’m not able to create a product, as I don’t really know what data I should send and how to send it. I know the method I have to use is catalogProductCreate, but the PHP examples shown here don’t really help me.
Any input would be appreciated.
Thank you in advance.
You are there already. I think your issue is not able to translate the PHP array of arguments to be passed into Python Key Value pairs. If thats the case this will help you a bit. As well as need to set the attribute set using catalogProductAttributeSetList before you create the product
attributeSets = client.service.catalogProductAttributeSetList(session)
#print attributeSets
# Not very sure how to get the current element from the attributeSets array. hope the below code will work
attributeSet = attributeSets[0]
product_details = [{'name':'Your Product Name'},{'description':'Product description'},{'short_description':'Product short description'},{'weight':'10'},{ 'status':'1'},{'url_key':'product-url-key'},{'url_path':'product-url-path'},{'visibility' :4},{'price':100},{'tax_class_id':1},{'categories': [2]},{'websites': [1]}]
client.service.catalogProductCreate(session , 'simple', attributeSet.set_id, 'your_product_sku',product_details)
suds.TypeNotFound: Type not found: 'productData'
Because the productData format is not right. You may want to change from
product_details = [{'name':'Your Product Name'},{'description':'Product description'}, {'short_description':'Product short description'},{'weight':'10'},{ 'status':'1'},{'url_key':'product-url-key'},{'url_path':'product-url-path'},{'visibility' :4},{'price':100},{'tax_class_id':1},{'categories': [2]},{'websites': [1]}]
to
product_details = {'name':'Your Product Name','description':'Product description', 'short_description':'Product short description','weight':'10', 'status':'1','url_key':'product-url-key','url_path':'product-url-path','visibility' :4,'price':100,'tax_class_id':1,'categories': [2],'websites': [1]}
It works for me.
Related
I am playing around with the Zillow API, but I am having trouble retrieving the rent data. Currently I am using a Python Zillow wrapper, but I am not sure if it works for pulling the rent data.
This is the help page I am using for the Zillow API:
https://www.zillow.com/howto/api/GetSearchResults.htm
import pyzillow
from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults
import pandas as pd
house = pd.read_excel('Housing_Output.xlsx')
### Login to Zillow API
address = ['123 Test Street City, State Abbreviation'] # Fill this in with an address
zip_code = ['zip code'] # fill this in with a zip code
zillow_data = ZillowWrapper(API KEY)
deep_search_response = zillow_data.get_deep_search_results(address, zip_code)
result = GetDeepSearchResults(deep_search_response)
# These API calls work, but I am not sure how to retrieve the rent data
print(result.zestimate_amount)
print(result.tax_value)
ADDING ADDITIONAL INFO:
Chapter 2 talks how to pull rent data by creating a XML function called zillowProperty. My skills going into XML aren't great, but I think I need to either:
a) import some xml package to help read it
b) save the code as an XML file and use the open function to read the file
https://www.amherst.edu/system/files/media/Comprehensive_Evaluation_-_Ningyue_Christina_Wang.pdf
I am trying to provide the code in here, but it won't let me break to the next line for some reason.
We can see that rent is not a field one can get using the pyzillow package, by looking into the attributes of your result by running dir(result), as well as the code here: Pyzillow source code.
However, thanks to the beauty of open source, you can edit the source code of this package and get the functionality you are looking for. Here is how:
First, locate where the code sits in your hard drive. Import pyzillow, and run:
pyzillow?
The File field shows this for me:
c:\programdata\anaconda3\lib\site-packages\pyzillow\__init__.py
Hence go to c:\programdata\anaconda3\lib\site-packages\pyzillow (or whatever it shows for you) and open the pyzillow.py file with a text editor.
Now we need to do two changes.
One: Inside the get_deep_search_results function, you'll see params. We need to edit that to turn the rentzestimate feature on. So change that function to:
def get_deep_search_results(self, address, zipcode):
"""
GetDeepSearchResults API
"""
url = 'http://www.zillow.com/webservice/GetDeepSearchResults.htm'
params = {
'address': address,
'citystatezip': zipcode,
'zws-id': self.api_key,
'rentzestimate': True # This is the only line we add
}
return self.get_data(url, params)
Two: Go to class GetDeepSearchResults(ZillowResults), and add the following into the attribute_mapping dictionary:
'rentzestimate_amount': 'result/rentzestimate/amount'
Voila! The customized&updated Python package now returns the Rent Zestimate! Let's try:
from pyzillow.pyzillow import ZillowWrapper, GetDeepSearchResults
address = ['11 Avenue B, Johnson City, NY']
zip_code = ['13790']
zillow_data = ZillowWrapper('X1-ZWz1835knufc3v_38l6u')
deep_search_response = zillow_data.get_deep_search_results(address, zip_code)
result = GetDeepSearchResults(deep_search_response)
print(result.rentzestimate_amount)
Which correctly returns the Rent Zestimate of $1200, which can be validated at the Zillow page of that address.
Using a rest/soap API like python-otrs or pyotrs is possible to close a ticket?
using python-otrs i try and receive a error:
otrs.client.SOAPError: TicketUpdate: Ticket->StateID or Ticket->State parameter is invalid! (TicketUpdate.InvalidParameter)
The code i try is:
from otrs.ticket.template import GenericTicketConnectorSOAP
from otrs.client import GenericInterfaceClient
from otrs.ticket.objects import Ticket, Article, DynamicField, Attachment
server_uri = r'https://www.example.com'
webservice_name = 'GenericTicketConnectorSOAP'
client = GenericInterfaceClient(server_uri, tc=GenericTicketConnectorSOAP(webservice_name))
# user session
client.tc.SessionCreate(user_login='user', password='pass')
t_upd = Ticket(State='closed',StateID='3')
client.tc.TicketUpdate(3657,ticket=t_upd)
where 3657 is the id of the ticket.
Thanks,
jp
I think the correct state name is closed successful but you don't need to ad both the name and the ID, just one of them should be enough.
Refer the key exactly used in the backend. You sould able check/match in the admin state aswell. The value of parameter should always match to the unique key used in the status table.
I'm super new in development in general. I'm currently building a webapp that get data from Rally/CA Agile Central and put them in a neat table.
My code:
response = rally.get('UserStory', fetch = True, query=query_criteria)
response_defect = rally.get('Defect', fetch = True, query=query_criteria)
story_list = []
if not response.errors:
for story in response:
#print (story.details())
a_story={}
#a_story['State'] = story.State.Name #if story.State else "Backlog"
a_story['State']=story.BusOpsKanban if story.BusOpsKanban else "unassigned"
#a_story['Status']=Story.Status if story.Status else "unassigned"
a_story['id'] = story.FormattedID
a_story['name'] = story.Name
a_story['Opened']=(datetime.strptime(story.CreationDate, '%Y-%m-%dT%H:%M:%S.%fZ').strftime('%Y-%d-%b'))
a_story['Requester']= story.Owner.Name if story.Owner else "unassigned"
a_story['Blocked']= story.Blocked
a_story['Service']=story.c_ServiceNowID
My issue is to get access to the value of the linkid of my customfield (c_ServiceNowID).
When I run a Dict = I see that I have LinkID attributes but when I type
story.c_ServiceNowID.LinkID, I receive an error message telling me there is no such attributes.... How do I access this value using python ?
Thank you
According to the documentation at http://pyral.readthedocs.io/en/latest/overview.html#custom-fields, pyral allows you to reference the field without the c_ prefix
Most Artifact types in Rally can be augmented with custom fields. As of Rally WSAPI v2.0, the ElementName for a custom field is prefixed with ‘c_’. The pyral toolkit allows you to reference these fields without having to use the ‘c_’ prefix. For example, if your custom field has a DisplayName of ‘Burnt Offerings Index’ you can use the String of ‘BurntOfferingsIndex’ in a fetch clause or a query clause or refer to the field directly on an artifact as artifact.BurntOfferingsIndex.
I think what you have should work, unless the ServiceNowID is empty. In that case there will not be a LinkID or DisplayString available on the ServiceNowID object.
If you update your code to check to make sure the Attribute is there, does it work?
if hasattr(story.c_ServiceNowID, 'LinkID'):
a_story['Service']=story.c_ServiceNowID.DisplayString
a_story['Link']=story.c_ServiceNowID.LinkID
Ok, so I need to build this application where I'll read images from a www.flickr.com account and use the images in my Python app. How will I do that? Any ideas? Thanks.
You could use one of the various flickr python libraries :
http://code.google.com/p/flickrpy/
http://pypi.python.org/pypi/Flickr.API/
http://stuvel.eu/projects/flickrapi
And for a good overview of flickr API, always look at the docs: http://www.flickr.com/services/api/
An example:
import flickrapi
api_key = 'API KEY YYYYYYYYYY' # you will need a key
api_password = 'your secret'
flickrClient = flickrapi.FlickrAPI(api_key, api_password)
# now you could use the methods on this client
# flickrClient.methodname(param)
favourites = flickrClient.favorites_getPublicList(user_id='userid')
# Get the title of the photos
for photo in favourites.photos[0].photo:
print photo['title']
[Edit:]
For authentication look at : http://stuvel.eu/flickrapi/documentation/#authentication
I'm brand new at Python and I'm trying to write an extension to an app that imports GA information and parses it into MySQL. There is a shamfully sparse amount of infomation on the topic. The Google Docs only seem to have examples in JS and Java...
...I have gotten to the point where my user can authenticate into GA using SubAuth. That code is here:
import gdata.service
import gdata.analytics
from django import http
from django import shortcuts
from django.shortcuts import render_to_response
def authorize(request):
next = 'http://localhost:8000/authconfirm'
scope = 'https://www.google.com/analytics/feeds'
secure = False # set secure=True to request secure AuthSub tokens
session = False
auth_sub_url = gdata.service.GenerateAuthSubRequestUrl(next, scope, secure=secure, session=session)
return http.HttpResponseRedirect(auth_sub_url)
So, step next is getting at the data. I have found this library: (beware, UI is offensive) http://gdata-python-client.googlecode.com/svn/trunk/pydocs/gdata.analytics.html
However, I have found it difficult to navigate. It seems like I should be gdata.analytics.AnalyticsDataEntry.getDataEntry(), but I'm not sure what it is asking me to pass it.
I would love a push in the right direction. I feel I've exhausted google looking for a working example.
Thank you!!
EDIT: I have gotten farther, but my problem still isn't solved. The below method returns data (I believe).... the error I get is: "'str' object has no attribute '_BecomeChildElement'" I believe I am returning a feed? However, I don't know how to drill into it. Is there a way for me to inspect this object?
def auth_confirm(request):
gdata_service = gdata.service.GDataService('iSample_acctSample_v1.0')
feedUri='https://www.google.com/analytics/feeds/accounts/default?max-results=50'
# request feed
feed = gdata.analytics.AnalyticsDataFeed(feedUri)
print str(feed)
Maybe this post can help out. Seems like there are not Analytics specific bindings yet, so you are working with the generic gdata.
I've been using GA for a little over a year now and since about April 2009, i have used python bindings supplied in a package called python-googleanalytics by Clint Ecker et al. So far, it works quite well.
Here's where to get it: http://github.com/clintecker/python-googleanalytics.
Install it the usual way.
To use it: First, so that you don't have to manually pass in your login credentials each time you access the API, put them in a config file like so:
[Credentials]
google_account_email = youraccount#gmail.com
google_account_password = yourpassword
Name this file '.pythongoogleanalytics' and put it in your home directory.
And from an interactive prompt type:
from googleanalytics import Connection
import datetime
connection = Connection() # pass in id & pw as strings **if** not in config file
account = connection.get_account(<*your GA profile ID goes here*>)
start_date = datetime.date(2009, 12, 01)
end_data = datetime.date(2009, 12, 13)
# account object does the work, specify what data you want w/
# 'metrics' & 'dimensions'; see 'USAGE.md' file for examples
account.get_data(start_date=start_date, end_date=end_date, metrics=['visits'])
The 'get_account' method will return a python list (in above instance, bound to the variable 'account'), which contains your data.
You need 3 files within the app. client_secrets.json, analytics.dat and google_auth.py.
Create a module Query.py within the app:
class Query(object):
def __init__(self, startdate, enddate, filter, metrics):
self.startdate = startdate.strftime('%Y-%m-%d')
self.enddate = enddate.strftime('%Y-%m-%d')
self.filter = "ga:medium=" + filter
self.metrics = metrics
Example models.py: #has the following function
import google_auth
service = googleauth.initialize_service()
def total_visit(self):
object = AnalyticsData.objects.get(utm_source=self.utm_source)
trial = Query(object.date.startdate, object.date.enddate, object.utm_source, ga:sessions")
result = service.data().ga().get(ids = 'ga:<your-profile-id>', start_date = trial.startdate, end_date = trial.enddate, filters= trial.filter, metrics = trial.metrics).execute()
total_visit = result.get('rows')
<yr save command, ColumnName.object.create(data=total_visit) goes here>