GithubHelp home page GithubHelp logo

prestapyt / prestapyt Goto Github PK

View Code? Open in Web Editor NEW
86.0 86.0 101.0 114 KB

Prestapyt is a library for Python to interact with the PrestaShop's Web Service API.

License: GNU Affero General Public License v3.0

Python 99.51% Shell 0.49%

prestapyt's Introduction

Prestapyt

prestapyt is a library for Python to interact with the PrestaShop's Web Service API.

Learn more about the PrestaShop Web Service from the Official Prestashop Documentation.

prestapyt is a direct port of the PrestaShop PHP API Client, PSWebServiceLibrary.php

Similar to PSWebServiceLibrary.php, prestapyt is a thin wrapper around the PrestaShop Web Service: it takes care of making the call to your PrestaShop instance's Web Service, supports the Web Service's HTTP-based CRUD operations (handling any errors) and then returns the XML ready for you to work with in Python (as well as prestasac if you work with scala).

Installation

The easiest way to install prestapyt (needs setuptools):

easy_install prestapyt

Or, better, using pip:

pip install prestapyt

If you do not have setuptools, download prestapyt as a .tar.gz or .zip from Prestapyt Source Archives, untar it and run:

python setup.py install

In order to always be uptodate, the best way is to use pip from this repo with the following command :

pip install --ignore-installed git+https://github.com/prestapyt/prestapyt.git@master

Usage

Message as xml

from prestapyt import PrestaShopWebService
prestashop = PrestaShopWebService('http://localhost:8080/api', WEBSERVICE_KEY)

Message as dictionary

from prestapyt import PrestaShopWebServiceDict
prestashop = PrestaShopWebServiceDict('http://localhost:8080/api', WEBSERVICE_KEY)

Search

Get all addresses

prestashop.get('addresses') # will return the same xml message than
prestashop.search('addresses')

Note: when using PrestaShopWebServiceDict prestashop.search('addresses') will return a list of ids.

Search with filters

prestashop.search('addresses', options={'limit': 10})
prestashop.search('addresses', options={'display': '[firstname,lastname]', 'filter[id]': '[1|5]'})

For additional info check reference for the options.

Get single address

prestashop.get('addresses', resource_id=1) or prestashop.get('addresses/1')

returns ElementTree (PrestaShopWebService) or dict (PrestaShopWebServiceDict).

You can use the full api URL

prestashop.get('http://localhost:8080/api/addresses/1')

Head request

prestashop.head('addresses')

Manipulate records

Delete

prestashop.delete('addresses', resource_ids=4)

Delete many records at once

prestashop.delete('addresses', resource_ids=[5,6])

Add record

prestashop.add('addresses', xml)

Edit record

prestashop.edit('addresses', xml)

Get model blank xml schema

prestashop.get('addresses', options={'schema': 'blank'})

Add product image

file_name = 'sample.jpg'
fd = io.open(file_name, "rb")
content = fd.read()
fd.close()

prestashop.add('/images/products/123', files=[('image', file_name, content)])

API Documentation

Documentation for the PrestaShop Web Service can be found on the PrestaShop wiki: Using the REST webservice

Credits:

Thanks to Prestashop SA for their PHP API Client PSWebServiceLibrary.php

Thanks to Alex Dean for his port of PSWebServiceLibrary.php to the Scala language, prestasac from which I also inspired my library.

Copyright and License

prestapyt is copyright (c) 2012 Guewen Baconnier

prestapyt is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

prestapyt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License along with prestapyt. If not, see GNU licenses.

prestapyt's People

Contributors

axel584 avatar dymirt avatar ffernandez-planetatic avatar flotho avatar guewen avatar gustawdaniel avatar omalbastin avatar pedrobaeza avatar qtheuret avatar sergio-teruel avatar simahawk avatar wantellets avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

prestapyt's Issues

Suggest Improvment to error reporting

I suggest a small change to prestapyt.py

line 171:  self._check_status_code(status_code)

Since this raises an exception on error, the code in line 175 does not execute.

174        if self.debug: # TODO better debug logs
175            print ("Response code: %s\nResponse headers:\n%s\nResponse body:\n%s"
176                   % (status_code, header, content))

If you move line 171 to a point below 176, any error messages sent by Prestashop will display.
Below is an example of what comes back:

Execute url: http://altajewelers.com/api/products / method: POST
Response code: 500
Response headers:
{'status': '500', 'content-length': '250', 'psws-version': '1.4.9.1', 'x-powered-by': 'PrestaShop Webservice', 'vary': 'Accept-Encoding', 'access-time': '1347167024', 'connection': 'close', '-content-encoding': 'gzip', 'execution-time': '0.558', 'date': 'Sun, 09 Sep 2012 05:03:44 GMT', 'server': 'Apache/2.2.14 (Ubuntu)', 'content-type': 'text/xml;charset=utf-8'}
Response body:
<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<errors>
<error>
<code><![CDATA[85]]></code>
<message><![CDATA[Error occurred while setting the images value]]></message>
</error>
</errors>
</prestashop>

ERROR: psapi_product.py: add_product: 'This call to PrestaShop Web Services failed and returned an HTTP status of 500. That means: Internal Server Error.'

You could parse out the error and display only that; but, why bother; it's useful to see all of the returned data.

Because of a bug in Prestashop, this error data was not being sent back to the client. I've sent a bug report to the Prestashop developers.

Mark

setup.py has non-trivial dependencies

Hi, thanks for the useful work

Unfortunately, prestapyt's setup.py breaks the contract of setup.py here:

import prestapyt

def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    # Basic package information.
    name = 'prestapyt',
    version = prestapyt.prestapyt.__version__,

The intent is rather clear (try and avoid duplication of version number), but importing prestapyt from the setup.py means than any dependency has to be fulfilled prior to installation.

It is therefore impossible to install prestapyt in a fresh virtualenv without manually installing httplib2 first

ImportError: No module named httplib2

(it works in buldout only with the released version, because we can explicitely add the httplib2 depenency in the config file and hope it'll be installed in the right order).

Avoiding version number duplication while providing it as an attribute on the module is a matter of policy, it's not easy for me to guess what'd suit you, but a lot of projects have encountered and solved similar problems.

Partial edit / add

The REST API of Prestashop does not support the PATCH method. It use PUT for modifications, so it means a "full replacement" which implies to pass all the values even if you modify only one field.

To edit a resource, you must post the entire XML with all the values of the resource, modifying the values you want.

If you try to post a XML with only the few fields to modify, you will get a bad request error.

This can be addressed at the prestapyt level but with a performance penalty.

Implementation has to (only on PrestaShopWebServiceDict) :
On a call to edit on prestapyt with a dict of values:

  • call the get method on prestashop
  • modify the full XML received with the values of the dict
  • call edit on prestashop with the modified xml

on a call to add on prestapyt with a dict of values:

  • same as upper but get method on prestashop must not be on a resource and must have the options {'schema': 'blank'}

'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Hello,

I have a probleme when I try associate an image to a product.

fd       = io.open(image_fr.filename, "rb")
content  = fd.read()
fd.close()
connetion.add('/images/products/'+str(id_product), files=[('image', name, content)])

I have this error: ''utf8' codec can't decode byte 0xff in position 0: invalid start byte' on "/prestapyt.py", line 420, in encode_multipart_formdata

AttributeError: 'tuple' object has no attribute 'content'

This is an error the connector is giving me when i try to import products:

Import a record from Prestashop
UUID
b6bc9a6c-733e-4417-8fa5-64a675f9a5c5
Task
openerp.addons.prestashoperpconnect.unit.import_synchronizer.import_record('prestashop.product.product', 1, 1)
Priority
10
Execute only after
User ID
Administrator
Created Date
29/11/2013 12:53:36
Enqueue Time
29/11/2013 12:54:28
Start Date
29/11/2013 12:54:43
Date Done
Worker
Current try / max. retries 1 / 5 If the max. retries is 0, the number of retries is infinite.
Exception Information
Traceback (most recent call last):
File "/usr/prestaconnect/openerp-connector/connector/queue/worker.py", line 122, in run_job
job.perform(session)
File "/usr/prestaconnect/openerp-connector/connector/queue/job.py", line 460, in perform
self.result = self.func(session, _self.args, *_self.kwargs)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 671, in import_record
importer.run(prestashop_id)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 553, in run
super(ProductRecordImport, self).run(prestashop_id)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 481, in run
erp_id
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 489, in _run_record
self.mapper.convert(prestashop_record)
File "/usr/prestaconnect/openerp-connector/connector/unit/mapper.py", line 216, in convert
self._convert(record, fields=fields)
File "/usr/prestaconnect/openerp-connector/connector/unit/mapper.py", line 172, in _convert
values = meth(record)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/product.py", line 218, in image
record['id_default_image']['value'])
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/backend_adapter.py", line 232, in read
options=options
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/backend_adapter.py", line 50, in get_image
image_content = base64.b64encode(response.content)
AttributeError: 'tuple' object has no attribute 'content'

I can't even debug it on pdb because of all the imports the module needs, so obviously throws more errors if i comment the openerp imports when debugging, so, any clue about this?

Problem with serialization dict -> XML

Hello,

Your library is really nice (I can read, update,delete and create something) but i have a problem for create a product in PrestaShop;

# ....

print "ADD PRODUCTS"
print "================"
product_data = prestashop.get('products', options={'schema': 'blank'})
print product_data
print ""
product_data['product'].update({
'ean13': '10399940700',
'name': 'Macbook',
'id_category_default': '1',
'out_of_stock': '2',
'indexed': '1',
'price': '50',
'active': '1',
'quantity': '3'
})
prestashop.add('products', product_data)

Error : prestapyt.prestapyt.PrestaShopWebServiceError: 'This call to PrestaShop Wices failed and returned an HTTP status of 400. That means: Bad Request.'

print "DONE"

With PSWebServiceLibrary.php the resultat is Successfully added.

1 2 10399940700 50 1 1 3 Macbook

And i had compare with the xml of PrestaPyt :

1 2 10399940700 50 1 1 3 1

Is it me that does not use the library well or is it a bug ?

Best regards.

Prestashop 1.5.1 support

How can I use this module with the 1.5.1 version of Prestashop?
In this update the Prestashop API doesn't change.

error on arguments edit()

prestashop = PrestaShopWebServiceDict('http://localhost:8080/api', 'BVWPFFYBT97WKM959D7AVVD0M4815Y1L')

attributes = prestashop.get('stock_availables', 1)
prestashop.edit('stock_availables', 1, attributes)

return error: TypeError: edit() takes exactly 3 arguments (4 given)

how to edit the quantity?

I cant find anything on google explaining how to edit/add quantity. when i try to add it to my product's xml it just gives me an error message:
prestapyt.prestapyt.PrestaShopWebServiceError: 'parameter "quantity" not writable. Please remove this attribute of this XML'
could anyone please comment me your solution? this is really urgent

Please help me, "No module named prestapyt" error

Hi, i'm not computer user expert, i have a problem for use connector-prestashop (https://github.com/OCA/connector-prestashop)

I use local prestashop 1.6 and local odoo 8. (use windows 8.1)
I have installed pyton 2.7
i have installed easy install
i have installed pip install
i have copied folder prestapyt (unzipped from prestapty-master) inside C:\Python27\Scripts
i have installed prestapyt with comand C:\Python27\Scripts\pip.exe install Prestapyt
i have installed requirements.txt with comand C:\Python27\Scripts\pip.exe install requirements.txt -r
i have copied the 3 modules folders of prestashop-connector inside odoo addons

When i upgrade the modules in odoo setting - upgrade modules,
i have this error:
Traceback (most recent call last):
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 530, in handle_exception
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 567, in dispatch
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 303, in call_function
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\service\model.py", line 113, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 300, in checked_call
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 796, in call
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 396, in response_wrap
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\web\controllers\main.py", line 940, in call_button
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\web\controllers\main.py", line 928, in call_kw
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\api.py", line 241, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\api.py", line 393, in old_api
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\api.py", line 397, in new_api
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\base\module\wizard\base_module_update.py", line 15, in update_module
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\api.py", line 239, in wrapper
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\api.py", line 462, in new_api
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\base\module\module.py", line 654, in update_list
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\http.py", line 1298, in load_addons
File "C:\Program Files (x86)\Odoo 8.0-20150424\server.\openerp\modules\module.py", line 80, in load_module
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\prestashoperpconnect__init
.py", line 27, in
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\prestashoperpconnect\product.py", line 34, in
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\prestashoperpconnect\unit__init
_.py", line 26, in
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\prestashoperpconnect\unit\mapper.py", line 35, in
File "C:\Program Files (x86)\Odoo 8.0-20150424\server\openerp\addons\prestashoperpconnect\unit\backend_adapter.py", line 29, in

ImportError: No module named prestapyt

I don't know what's happen, PLEASE ANYONE CAN HELP ME???
THANKS

cannot import name 'PrestaShopWebService'

Hi, I'm following the instructions to install and run prestapyt but getting the following error

from prestapyt import PrestaShopWebService
Traceback (most recent call last):
File "<pyshell#7>", line 1, in
from prestapyt import PrestaShopWebService
File "C:\Python34\lib\site-packages\prestapyt__init__.py", line 1, in
from prestapyt import PrestaShopWebService
ImportError: cannot import name 'PrestaShopWebService'

I'm running Python 3.4 in Windows 10 and the version of my Prestashop is 1.6

Any hint on what I am doing wrong?

thanks in advance

HTTP response is empty

hi

i got this error when i wanted to add a product to the shop. my script works before. i did not change my script, but my shop update from 1.5 to 1.6.

can anyone help? thanks

Advanced Options

Hi,
How to use prestapyt to change name id product or change url img ?
Thanks for reply.
Please update examples files

Release 0.9.1 on pypi

Following #25

Could you please push >=9.0 to pypi ? Current pypi version does not support Python 3

Httplib2 connection close

To check:
httplib2 doesn't close the connections
add connection: close in the headers to force the server to close it.

TypeError: string indices must be integers, not str

And this is another 'bug?' or 'error' the connector is giving me:

File "/usr/prestaconnect/openerp-connector/connector/queue/worker.py", line 122, in run_job
job.perform(session)
File "/usr/prestaconnect/openerp-connector/connector/queue/job.py", line 460, in perform
self.result = self.func(session, _self.args, *_self.kwargs)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 663, in import_batch
importer.run(filters=filters, *_kwargs)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 202, in run
return super(PaymentMethodsImportSynchronizer, self).run(filters, *_kwargs)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 176, in run
record_ids = self._run_page(filters)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 186, in _run_page
self._import_record(record_id, **kwargs)
File "/usr/prestaconnect/prestashoperpconnect/prestashoperpconnect/unit/import_synchronizer.py", line 206, in _import_record
('name', '=', record['payment']),
TypeError: string indices must be integers, not str

In the module code i see this:

class PaymentMethodsImportSynchronizer(BatchImportSynchronizer):
_model_name = 'payment.method'

def run(self, filters=None, *_kwargs):
if filters is None:
filters = {}
filters['display'] = '[id,payment]'
return super(PaymentMethodsImportSynchronizer, self).run(filters, *_kwargs)

def _import_record(self, record):
ids = self.session.search('payment.method', [
('name', '=', record['payment']),
('company_id', '=', self.backend_record.company_id.id),
])
if ids:
return
self.session.create('payment.method', {
'name': record['payment'],
'company_id': self.backend_record.company_id.id,
})

I managed to install everything and it does import metadata and base data as well.

But any 'background' import throws the 'tuple' from my previous issue, and this 'integers' one, any chance to test it? :(

Thanks in advance!

SSL

Guewen,

Have you given any thought to adding SSL capability to prestapyt? This is an option in Prestashop for webservice. Prestashop webservice has the capability to transfer private user information and this should be protected. I have not done any work to implement this but may if I have time. I don't have experience with SSL other than installing it on servers so I'm sure I have a lot to learn. It occurs to me that if linking to the local browser's certificates is possible using these for prestapyt SSL would be useful. If you have SSL experience and not the time to implement it I would appreciate pointers from your experience.

Mark

Reporting of errors

The webservices api does not return useful errors.
Prestapyt cannot show errors which it does not receive.

in WebserviceRequest.php I see code such as:
$this->setError(400, 'id is duplicate in request', 89);

I do not see these errors reported in the apache log file.
Do I have a configuration problem which prevents me from seeing these errors?

I would appreciate it ever so much if you could educate me as to how I should set my configuration to see these errors.

I see many other errors in the log file, why not these.

I had prestapyt working well with Prestashop version 1.4.7.3.
I installed Prestashop version 1.4.9.0 and am now having problems.

An add which had worked now reports 500, internal server error.

It is my guess that I am sending field data in the request which is now no longer allowed.
I can figure this out by trial and error; but, certainly there is a better way.

Guewen, thank you for your library. I like it very much.

Mark

Example in README / KeyError: 'attrs'

When I try :
prestashop.search('addresses', options={'display': '[firstname,lastname]', 'filter[id]': '[1|5]'})

Here what I get :

KeyError Traceback (most recent call last)
in ()
----> 1 prestashop.search('addresses', options={'display': '[firstname,lastname]', 'filter[id]': '[1|5]'})

/usr/local/lib/python2.7/dist-packages/prestapyt-0.6.1-py2.7.egg/prestapyt/prestapyt.pyc in search(self, resource, options)
475 return []
476 elif isinstance(elems, list):
--> 477 ids = [int(elem['attrs']['id']) for elem in elems]
478 else:
479 ids = [int(elems['attrs']['id'])]

KeyError: 'attrs'

Error adding products with 1.4.9.0 using dict

Response body:

I don't understand how to set the value of an association using the dictionary returned from the schema call.

p = prestashop.get('products', options={'schema':'blank'})
p['product']["name"] = "New Product"
p['product']["price"] = "30.00"
p['product']['link_rewrite'] = "new-product"
p['product']['available_for_order'] = '1'
p['product']['active'] = '1'
p['product']['quantity'] = 10

What to put here to avaoid the issue?

p['product']['associations']['images']['id'] = 47

prestashop.add('products', p)

Thank you.

1.4 Updating address and products (501 error)

I've run both examples (xml and dict) and I cannot update addresses or products. I keep getting a 501 error (Not Implemented). My key has the correct permissions and I can list products and addresses just fine. I am curious if it's a configuration of my host or cart? I am using a hosted solution from Arvixe. Do you have a working demo of this functionality I could see?

ModuleNotFoundError: No module named 'importlib.metadata'

Hi
I just trying to working with this library for the first time and after installing the module in a virtual environment the above error raised and I do not know what to do for solving this problem

(env) C:\Users\Arian-pc\Dropbox\Projects\update-price-rule-prestashop\app>python main.py Traceback (most recent call last): File "main.py", line 1, in <module> from prestapyt import PrestaShopWebService File "C:\Users\Arian-pc\Dropbox\Projects\update-price-rule-prestashop\env\lib\site-packages\prestapyt\__init__.py", line 1, in <module> from .prestapyt import PrestaShopWebService File "C:\Users\Arian-pc\Dropbox\Projects\update-price-rule-prestashop\env\lib\site-packages\prestapyt\prestapyt.py", line 52, in <module> from .version import __author__ File "C:\Users\Arian-pc\Dropbox\Projects\update-price-rule-prestashop\env\lib\site-packages\prestapyt\version.py", line 1, in <module> from importlib.metadata import version, PackageNotFoundError ModuleNotFoundError: No module named 'importlib.metadata'

I'm also read the famous topics in GitHub and StackOverflow but that doesn't help
can you just tell me how can I solve this problem?
is it related to the python version ?

my python version is -> Python 3.7.4

I'm also installed "importlib-metadata" but it doesn't help

thank you

Cant make requests after upgrading prestapyt version

Before the upgrade, things were working fine. Yesterday I noticed that although I was able to edit products, I was getting an error when creating new ones: "XML error : String could not be parsed as XML".

I decided to then upgrade prestapyt, but now I cant make any request (line 232 prestapyt.py, latest version):

<title>403 Forbidden</title>

Forbidden

You don't have permission to access /api/products on this server.

Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Any idea why things stopped working? Thanks

socket.error: [Errno 9] Bad file descriptor

Hi, I'm using PS 1.6 and Python 2.7. I was able to establish connection but whenever I try to get data from the database I get a socket error. Any idea of what it is going on? thanks in advance

this is the out put I'm getting

prestashop.search('orders')
Traceback (most recent call last):
File "", line 1, in
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/prestapyt/prestapyt.py", line 298, in search
return self.get(resource, options=options)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/prestapyt/prestapyt.py", line 316, in get
return self.get_with_url(full_url)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/prestapyt/prestapyt.py", line 325, in get_with_url
return self._parse(self._execute(url, 'GET')[2])
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/prestapyt/prestapyt.py", line 189, in _execute
header, content = self.http_client.request(url, method, body=body, headers=request_headers)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/httplib2/init.py", line 1609, in request
(response, content) = self._request(conn, authority, uri, request_uri, method, body, headers, redirections, cachekey)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/httplib2/init.py", line 1351, in _request
(response, content) = self._conn_request(conn, request_uri, method, body, headers)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/httplib2/init.py", line 1273, in _conn_request
conn.request(method, request_uri, body, headers)
File "/usr/lib/python2.7/httplib.py", line 979, in request
self._send_request(method, url, body, headers)
File "/usr/lib/python2.7/httplib.py", line 1013, in _send_request
self.endheaders(body)
File "/usr/lib/python2.7/httplib.py", line 975, in endheaders
self._send_output(message_body)
File "/usr/lib/python2.7/httplib.py", line 835, in _send_output
self.send(msg)
File "/usr/lib/python2.7/httplib.py", line 811, in send
self.sock.sendall(data)
File "/home/joluu/.virtualenvs/my-virtualenv/local/lib/python2.7/site-packages/httplib2/socks.py", line 151, in sendall
return super(socksocket, self).sendall(content, _args)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(_args)
File "/usr/lib/python2.7/socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor

Product Option Values & Accessories

When creating a product for the first time, I include the product_features and accessories in the schema but for some reason, they do not show up when the product is added on Prestashop. I believe I am inserting the correct JSON data for both.

Thanks

delete an image

What is the method for deleting an image?

I've tried:

prestashop_id = 3
image_ids = ["123", "456"]
ws.delete(f"images/products/{prestashop_id}", image_ids)

and

prestashop_id = 3
image_ids = "123"
ws.delete(f"images/products/{prestashop_id}", image_ids)

But is not working
Thank you

Installer errror missing README.md

Doing a pip install -U prestapyt

Fails cannot find README.md

Manually copying README.md into build directory and running again install completes.

Authentication error

prestapyt.prestapyt.PrestaShopAuthenticationError: 'Unauthorized'

I have tried to connect to the API through through standards requests and works fine. When i tried using the library i get and Unauthorized Error. I used the example and C+P'ed my details in.

cannot import name 'PrestaShopWebService'

cannot import name 'PrestaShopWebService' from partially initialized module 'prestapyt' (most likely due to a circular import) (/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/prestapyt/init.py)

Anyone can help me?

Tested with Prestashop 1.5 SVN 17569

Prestapyt works with Prestashop 1.5 SVN 17569.

The webservice layer still has bugs; and, some of the data formats have changed; but, there are no problems with Prestapyt.

Mark

prestashop 1.7.6.8 support

I have used this library on a Prestashop site with this version.
I know, this library is not fully compatible, and in fact it not work ๐Ÿ˜‚

What is the problem with this version?
I receive this error every time:

'HTTP XML response is not parsable : XML or text declaration not at start of entity: line 1, column 1. b\'\\t<?xml version="1.0" encoding="UTF-8"?>\\n<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">\\n<product>

Examples don't work

The example prestapyt_dict.py located in the "examples" subdirectory don't work :

Traceback (most recent call last):
File "./product_images.py", line 9, in
parse_type='dict')
TypeError: init() got an unexpected keyword argument 'parse_type'
zsh: exit 1 ./product_images.py

They are probably outdated.

Error on Edit: 'NoneType' object has no attribute 'nodeType'

Greetings Guewen,

I am have the next error when try to edit a record on prestashop:

2014-10-20 04:14:22,393 12224 ERROR salling openerp.addons.connector.queue.worker: Traceback (most recent call last):
  File "/opt/openerp/addons-connector/connector/queue/worker.py", line 123, in run_job
    job.perform(session)
  File "/opt/openerp/addons-connector/connector/queue/job.py", line 490, in perform
    self.result = self.func(session, *self.args, **self.kwargs)
  File "/opt/openerp/addons-connector/prestashoperpconnect/unit/export_synchronizer.py", line 243, in export_product
    return product_exporter.run(record_id, fields)
  File "/opt/openerp/addons-connector/prestashoperpconnect/unit/export_synchronizer.py", line 81, in run
    result = self._run(*args, **kwargs)
  File "/opt/openerp/addons-connector/prestashoperpconnect/unit/export_synchronizer.py", line 155, in _run
    self._update(record)
  File "/opt/openerp/addons-connector/prestashoperpconnect/unit/export_synchronizer.py", line 131, in _update
    self.backend_adapter.write(self.prestashop_id, data)
  File "/opt/openerp/addons-connector/prestashoperpconnect/unit/backend_adapter.py", line 156, in write
    return api.edit(self._prestashop_model, id, content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/prestapyt.py", line 364, in edit
    return self.edit_with_url(full_url, content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/prestapyt.py", line 516, in edit_with_url
    xml_content = dict2xml.dict2xml({'prestashop': content})
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/dict2xml.py", line 119, in dict2xml
    root, _ = _process_complex(doc, data.items())
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/dict2xml.py", line 71, in _process_complex
    nodes = _process(doc, tag, value)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/dict2xml.py", line 49, in _process
    nodelist, attrs = _process_complex(doc, tag_value.items())
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/dict2xml.py", line 71, in _process_complex
    nodes = _process(doc, tag, value)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt/dict2xml.py", line 51, in _process
    node.appendChild(child)
  File "/usr/lib/python2.7/xml/dom/minidom.py", line 112, in appendChild
    if node.nodeType == self.DOCUMENT_FRAGMENT_NODE:
AttributeError: 'NoneType' object has no attribute 'nodeType'

I am doing this for edit a record on prestashoperpconnect.unit.backend_adapter:

    def write(self, id, attributes=None):                                                                                                                                                        
        """ Update records on the external system """                                                                                                                                            
        api = self.connect()                                                                                                                                                                     
        attributes['id'] = id                                                                                                                                                                    
        content = api.get(self._prestashop_model, resource_id=id)                                                                                                                                
        key = content.items()[0][0]                                                                                                                                                              
        content.get(key).update(attributes)                                                                                                                                                      
        return api.edit(self._prestashop_model, id, content) 

Please help when you have time, I will try to fix it tomorrow, some advice ?

Thanks.
Best Regards.

Unicode decode error with debug is active

I am getting such errors when using prestapyt with debug activated :

File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 325, in add_with_url
print "Execute url: %s / method: POST\nbody: %s" % (url, pretty_body)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 807: ordinal not in range(128)

The same kind of problem appears here :

print "Response body:\n%s\n" % r.content

In both cases, we print characters without taking care of encoding, which leads this issue !

Shouldn't we handle "print" in a better way ?

CRLF.join(L) expected str instance, bytes found when uploading image

I am trying to upload images inside a product of prestashop 1.7.4 (I know it's not fully supported yet, but the rest of the methods worked like charm, adding or editing other structures even with dict)
prestashop.add('/images/products/{}'.format(new_product_id), files=[('image', 'image.jpg', content)])

but I get the following error:

  File "/site-packages/prestapyt/prestapyt.py", line 499, in encode_multipart_formdata
    body = CRLF.join(L)
TypeError: sequence item 4: expected str instance, bytes found

which is due to the fact that L.append(value) is a binary data and during that join it gets mixed with string data and fails.

I was able to solve the image upload directly with the requests module(which I belive it's used within prestapyt in the following way:

ps_token = 'XXXXXXXXXXXXXXXXXXx'
ps_image_url = 'http://xxxxxxx/images/products/{}'.format(new_product_id)
filename = '/tmp/filename.jpg'
files = {'image': ("filename.jpg", open(file_name, 'rb'), 'image/jpg')}

client = requests.Session()
client.auth = (ps_token, '')
r = client.post(ps_image_url, files=files)
print(r)
print(r.text)

I am not sure if it is a python3 issue(I am using the port version recenlty made) only. But I'm writting this because I think this python library is awesome and makes the API so easy to use with dictionaries. Thanks for your comments or some possible pull request.

Support for Prestashop 1.6

Hello,

I've read in the source code, which is not supported the version 1.6 of prestashop.

How I can help?

I have the next problem trying to sync OpenERP 7 with prestashop 1.6:

OpenERP Server Error

Client Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/http.py", line 204, in dispatch
    response["result"] = method(self, **self.params)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/controllers/main.py", line 1132, in call_button
    action = self._call_kw(req, model, method, args, {})
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/controllers/main.py", line 1120, in _call_kw
    return getattr(req.session.model(model), method)(*args, **kwargs)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/session.py", line 42, in proxy
    result = self.proxy.execute_kw(self.session._db, self.session._uid, self.session._password, self.model, method, args, kw)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/session.py", line 30, in proxy_method
    result = self.session.send(self.service_name, method, *args)
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/session.py", line 103, in send
    raise xmlrpclib.Fault(openerp.tools.ustr(e), formatted_info)


Server Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/openerp/addons/web/session.py", line 89, in send
    return openerp.netsvc.dispatch_rpc(service_name, method, args)
  File "/usr/lib/pymodules/python2.7/openerp/netsvc.py", line 296, in dispatch_rpc
    result = ExportService.getService(service_name).dispatch(method, params)
  File "/usr/lib/pymodules/python2.7/openerp/service/web_services.py", line 626, in dispatch
    res = fn(db, uid, *params)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 190, in execute_kw
    return self.execute(db, uid, obj, method, *args, **kw or {})
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 132, in wrapper
    return f(self, dbname, *args, **kwargs)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 199, in execute
    res = self.execute_cr(cr, uid, obj, method, *args, **kw)
  File "/usr/lib/pymodules/python2.7/openerp/osv/osv.py", line 187, in execute_cr
    return getattr(object, method)(cr, uid, *args, **kw)
  File "/home/vagrant/addons/prestashoperpconnect/models/prestashop_model.py", line 116, in synchronize_metadata
    import_batch(session, model, backend_id)
  File "/home/vagrant/addons/prestashoperpconnect/unit/import_synchronizer.py", line 1014, in import_batch
    importer.run(filters=filters, **kwargs)
  File "/home/vagrant/addons/prestashoperpconnect/unit/import_synchronizer.py", line 183, in run
    record_ids = self._run_page(filters, **kwargs)
  File "/home/vagrant/addons/prestashoperpconnect/unit/import_synchronizer.py", line 191, in _run_page
    record_ids = self.backend_adapter.search(filters)
  File "/home/vagrant/addons/prestashoperpconnect/unit/backend_adapter.py", line 126, in search
    return api.search(self._prestashop_model, filters)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 494, in search
    search(resource, options=options)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 348, in search
    return self.get(resource, options=options)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 516, in get
    response = super(PrestaShopWebServiceDict, self).get(resource, resource_id=resource_id, options=options)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 366, in get
    return self.get_with_url(full_url)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 536, in get_with_url
    response = super(PrestaShopWebServiceDict, self).get_with_url(url)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 375, in get_with_url
    r = self._execute(url, 'GET')
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 206, in _execute
    self._check_status_code(r.status_code, r.content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 144, in _check_status_code
    ps_error_code, ps_error_msg = self._parse_error(content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 116, in _parse_error
    error_answer = self._parse(xml_content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 619, in _parse
    parsed_content = super(PrestaShopWebServiceDict, self)._parse(content)
  File "/usr/local/lib/python2.7/dist-packages/prestapyt-0.4.0-py2.7.egg/prestapyt/prestapyt.py", line 227, in _parse
    parsed_content = ElementTree.fromstring(unicode_encode.unicode2encoding(content))
  File "<string>", line 124, in XML
ParseError: syntax error: line 1, column 49

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.