from future import print_function from prestapyt import PrestaShopWebService from xml.etree import ElementTree prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L') prestashop.debug = True prestashop.get('') print("GET") print((ElementTree.tostring(prestashop.get('addresses')))) print((ElementTree.tostring(prestashop.get('addresses', resource_id=1)))) print((ElementTree.tostring(prestashop.get('addresses/1')))) print((ElementTree.tostring(prestashop.get('addresses', options={'limit': 1})))) print((ElementTree.tostring(prestashop.get('stock_movement_reasons')))) print("HEAD") print((prestashop.head('addresses'))) print("EDIT") prestashop.edit( "addresses", 1, """<prestashop xmlns:ns0="http://www.w3.org/1999/xlink"> <address> <id>1</id> <id_customer /> <id_manufacturer ns0:href="http://localhost:8080/api/manufacturers/1">1</id_manufacturer> <id_supplier /> <id_country ns0:href="http://localhost:8080/api/countries/21">21</id_country> <id_state ns0:href="http://localhost:8080/api/states/5">5</id_state>
}, }, 'value': 'test description english' }, { 'attrs': { 'id': '2', 'href': { 'value': 'http://localhost:8080/api/languages/1', 'xmlns': 'http://www.w3.org/1999/xlink' }, }, 'value': 'test description french' }], }, } } } print dict2xml(x) import xml2dict from prestapyt import PrestaShopWebService prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L') products_xml = prestashop.get('products', 1) products_dict = xml2dict.ET2dict(products_xml) pprint(dict2xml(products_dict))
'id_supplier': None, 'lastname': 'JOBS', 'other': None, 'phone': '(800) 275-2273', 'phone_mobile': None, 'postcode': '95014', 'vat_number': 'XXX', 'description': {'language': [{'attrs': {'id': '1', 'href': {'value': 'http://localhost:8080/api/languages/1', 'xmlns': 'http://www.w3.org/1999/xlink'},}, 'value': 'test description english'}, {'attrs': {'id': '2', 'href': {'value': 'http://localhost:8080/api/languages/1', 'xmlns': 'http://www.w3.org/1999/xlink'},}, 'value': 'test description french'}], }, }}} print dict2xml(x) import xml2dict from prestapyt import PrestaShopWebService prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L') products_xml = prestashop.get('products', 1) products_dict = xml2dict.ET2dict(products_xml) pprint(dict2xml(products_dict))
class PrestaHelper(object): """Helper class to obtain structured information from prestashop API""" __prestashop = None __prestashop_api_access = {'url' : None, 'key' : None } def __init__( self, presta_api_url, presta_api_key, debug = __debug__ ): """ constructor with connection parameter to PrestaShop API. """ # Keep track of parameters self.__prestashop_api_access['url'] = presta_api_url self.__prestashop_api_access['key'] = presta_api_key logging.info( 'connecting Presta API @ %s...', (presta_api_url) ) self.__prestashop = PrestaShopWebService( presta_api_url, presta_api_key ) self.__prestashop.debug = debug def search( self, pattern, options ): """ Giving access to search capability of underlaying PrestaShop WebService """ # Search are organised as follow # (Store URL)/api/customers/?display=[firstname,lastname]&filter[id]=[1|5] # (store URL)/api/orders/?display=[id,current_state]&limit=25&sort=id_DESC # See source: # http://doc.prestashop.com/display/PS14/Chapter+8+-+Advanced+Use # return self.__prestashop.search( pattern, options = options ) def get_accessrights( self ): """ Return the access rights on API as dictionnary Really convenient to check the prestashop connexion.""" el = self.__prestashop.get( '' ) item = etree_to_dict( el ) item = item['prestashop']['api'] # skip nodes prestashop & api # remove attribute nodes _result = {} for k,v in item.items(): if not k.startswith('@'): _result[k] = v return _result def get_lastcustomermessage_id( self ): """ Retreive the last customer message ID Stored into PrestaShop""" el = self.__prestashop.search( 'customer_messages', options={'limit':1, 'sort' : 'id_DESC'} ) item = etree_to_dict( el ) return int( item['prestashop']['customer_messages']['customer_message']['@id'] ) def get_lastcustomermessages( self, fromId, count=1 ): """ Retreive the last customer messages stored in PrestaShop fromId - ID from the message message to start from (see get_lastcustomermessage_id) count - (default=1) the number of messages to retreive fromId (counting down) Returns: A list of CustomerMessageData objects """ _result = [] for i in range( count ): # range(1)=0 range(2)=0,1 el = self.__prestashop.get( 'customer_messages', fromId-i ) customermessage = CustomerMessageData( self ) customermessage.load_from_xml( el ) _result.append( customermessage ) return _result def get_customerthread( self, id ): """ Retreive the custom thread data from thread id id(int) - id_customer_thread which is mentionned into a customer message. Returns: A CustomerThreadData object """ if not(isinstance( id, int )): raise EValueError( 'id must be integer' ) logging.debug( 'read id_customer_thread: %s ' % id ) el = self.__prestashop.get( 'customer_threads', id ) customerthread = CustomerThreadData( self ) customerthread.load_from_xml( el ) return customerthread def get_carriers( self ): """ Retreive a list of Carriers (CarrierData) from prestashop """ logging.debug( 'read carriers' ) el = self.__prestashop.search( 'carriers', options = {'display':'[id,deleted,active,name]'} ) _result = CarrierList( self ) _result.load_from_xml( el ) return _result def get_products( self ): """ retreive a list of products from PrestaShop """ logging.debug( 'read products' ) #el = self.__prestashop.search( 'products' ) #print( ElementTree.tostring( el ) ) el = self.__prestashop.search( 'products', options = {'display': '[id,reference,active,name,price,wholesale_price,id_supplier,id_category_default,advanced_stock_management,available_for_order,ean13]'} ) _result = BaseProductList( self ) _result.load_from_xml( el ) return _result def get_suppliers( self ): """ retreive the list of suppliers """ logging.debug('read suppliers') el = self.__prestashop.search( 'suppliers', options = {'display': '[id,active,name]'} ) _result = SupplierList( self ) _result.load_from_xml( el ) return _result def get_product_suppliers( self ): """ retreive the list of all the supplier for all the products """ logging.debug('read product suppliers') el = self.__prestashop.search( 'product_suppliers', options = {'display': '[id,id_product,id_supplier,product_supplier_reference]'} ) _result = ProductSupplierList( self ) _result.load_from_xml( el ) return _result def get_order_states( self ): """ Retreive the list of Order States (OrderStateDate) from prestashop """ logging.debug( 'read order states' ) el = self.__prestashop.search( 'order_states', options = {'display':'[id,unremovable,send_email,invoice,shipped,paid,deleted,name]'} ) #print( ElementTree.tostring( el ) ) _result = OrderStateList( self ) _result.load_from_xml( el ) return _result def get_lastorder_id( self ): """ retreive the last order ID stored in PrestaShop """ el = self.__prestashop.search( 'orders', options={'limit':1, 'sort' : 'id_DESC'} ) item = etree_to_dict( el ) return int( item['prestashop']['orders']['order']['@id'] ) def get_order_ids( self, order_state_filter, limit = 25 ): """ Retreive a list of Order ID stored in prestashop for a given status. Start from the highest ID in the database with a max of limit rows loaded via the API""" # Since PrestaShop 1.6, current_state is no more filterable (returns an Error 400 bad request) # So filter must be applied by code! # # el = self.__prestashop.search( 'orders', options={'limit':limit, 'sort' : 'id_DESC', 'display':'[id,current_state]', 'filter[current_state]': '[%i]' % order_state_filter } ) el = self.__prestashop.search( 'orders', options={'limit':limit, 'sort' : 'id_DESC', 'display':'[id,current_state]' } ) items = etree_to_dict( el ) # print( items ) # Si aucune entrée due au filtrage (oui cela arrive) if isinstance( items['prestashop']['orders'], str ): return [] # Si une seule entrée --> transformer l'unique dictionnaire en liste order_list = items['prestashop']['orders']['order'] if isinstance( order_list, dict ): order_list = [ order_list ] # print( order_list ) _result = [] for order in order_list: if (order_state_filter == None) or (int(order['current_state']['#text']) == order_state_filter): _result.append( int(order['id']) ) return _result def get_last_orders( self, fromId, count=1 ): """ Retreive the last orders stored in PrestaShop Args: fromId - ID from the last order (see get_lastorder_id) count - (default=1) the number of orders to retreive fromId (counting down) Returns: A list of OrderData objects """ _result = [] for i in range( count ): # range(1)=0 range(2)=0,1 el = self.__prestashop.get( 'orders', fromId-i ) order = OrderData( self ) order.load_from_xml( el ) _result.append( order ) return _result def get_outofstock_orderable_ids( self ): """ Locate the product IDs where advanced stock management is improperly defined. Accepting OutOfStock ordering """ # out_of_stock = 1 -> Accept "out of stock" order el = self.__prestashop.search( 'stock_availables' , options={ 'display':'[id, id_product]', 'filter[out_of_stock]': '[1]' } ) items = etree_to_dict( el ) # print( items ) # Si aucune entrée due au filtrage (oui cela arrive) if isinstance( items['prestashop']['stock_availables'], str ): return [] # Si une seule entrée --> transformer l'unique dictionnaire en liste stock_list = items['prestashop']['stock_availables']['stock_available'] if isinstance( stock_list, dict ): stock_list = [ stock_list ] # print( stock_list ) _result = [] for stock in stock_list: _result.append( int(stock['id_product']['#text']) ) return _result def get_unsynch_stock_qty_ids( self ): """ Locate the product IDs where advanced stock management is improperly defined. Having theyr qty not in synch with the Advanced Stock Management """ # depends_on_stock = 0 -> gestion manuelle des quantités el = self.__prestashop.search( 'stock_availables' , options={ 'display':'[id, id_product]', 'filter[depends_on_stock]': '[0]' } ) items = etree_to_dict( el ) # print( items ) # Si aucune entrée due au filtrage (oui cela arrive) if isinstance( items['prestashop']['stock_availables'], str ): return [] # Si une seule entrée --> transformer l'unique dictionnaire en liste stock_list = items['prestashop']['stock_availables']['stock_available'] if isinstance( stock_list, dict ): stock_list = [ stock_list ] # print( stock_list ) _result = [] for stock in stock_list: _result.append( int(stock['id_product']['#text']) ) return _result def get_stockavailables( self ): """ retreive the list of stock availables from PrestaShop """ el = self.__prestashop.search( 'stock_availables' , options={ 'display':'[id, id_product,quantity,depends_on_stock,out_of_stock]' } ) _result = StockAvailableList( self ) _result.load_from_xml( el ) return _result def get_categories( self ): """ Load the product categories """ el = self.__prestashop.search( 'categories', options={ 'display':'[id,name,active,level_depth,is_root_category]' } ) _result = CategoryList( self ) _result.load_from_xml( el ) return _result
from prestapyt import PrestaShopWebService from xml.etree import ElementTree prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L') prestashop.debug = True prestashop.get('') print "GET" print ElementTree.tostring(prestashop.get('addresses')) print ElementTree.tostring(prestashop.get('addresses', resource_id=1)) print ElementTree.tostring(prestashop.get('addresses/1')) print ElementTree.tostring(prestashop.get('addresses', options={'limit': 1})) print ElementTree.tostring(prestashop.get('stock_movement_reasons')) print "HEAD" print prestashop.head('addresses') print "EDIT" prestashop.edit("addresses", 1, """<prestashop xmlns:ns0="http://www.w3.org/1999/xlink"> <address> <id>1</id> <id_customer /> <id_manufacturer ns0:href="http://localhost:8080/api/manufacturers/1">1</id_manufacturer> <id_supplier /> <id_country ns0:href="http://localhost:8080/api/countries/21">21</id_country> <id_state ns0:href="http://localhost:8080/api/states/5">5</id_state> <alias>manufacturer</alias> <company />
from prestapyt import PrestaShopWebService from xml.etree import ElementTree prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L', parse_type='dict') #prestashop.debug = True from pprint import pprint pprint(prestashop.get('')) pprint(prestashop.head('')) pprint(prestashop.get('addresses', 1)) pprint(prestashop.get('products', 1)) address_data = prestashop.get('addresses', 1) address_data['address']['firstname'] = 'Robert' prestashop.edit('addresses', 1, address_data) address_data = prestashop.get('addresses', options={'schema': 'blank'}) address_data['address'].update({'address1': '1 Infinite Loop', 'address2': '', 'alias': 'manufacturer', 'city': 'Cupertino', 'company': '', 'deleted': '0', 'dni': '', 'firstname': 'STEVE', 'id_country': '21', 'id_customer': '', 'id_manufacturer': '1', 'id_state': '5',
from prestapyt import PrestaShopWebService from xml.etree import ElementTree prestashop = PrestaShopWebService('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L', parse_type='dict') #prestashop.debug = True from pprint import pprint pprint(prestashop.get('')) pprint(prestashop.head('')) pprint(prestashop.get('addresses', 1)) pprint(prestashop.get('products', 1)) address_data = prestashop.get('addresses', 1) address_data['address']['firstname'] = 'Robert' prestashop.edit('addresses', 1, address_data) address_data = prestashop.get('addresses', options={'schema': 'blank'}) address_data['address'].update({ 'address1': '1 Infinite Loop', 'address2': '', 'alias': 'manufacturer', 'city': 'Cupertino', 'company': '', 'deleted': '0', 'dni': '', 'firstname': 'STEVE', 'id_country': '21', 'id_customer': '', 'id_manufacturer': '1', 'id_state': '5',