使用Python向API Prestashop发出POST请求

Pei*_*sou 6 python web-services request prestashop-1.7

我可以通过列出和创建产品Prestashop API。我想在我的网站上自动化一点产品更新过程。

但是我在尝试使用图像创建新产品以及将图像上传到我通过Web服务创建的产品中尝试上传图像时遇到问题。

我的代码中没有看到任何错误,因此我想知道是否使用Prestashop API出错了。

我的代码:

def addNewImage(product_id):
   file = 'foto.png'
   fd = io.open(file, "rb")
   data = fd.read()
   r = requests.post(urlimg + product_id, data=data,auth=(key,""), headers={'Content-Type': 'multipart/form-data'})
   print(r.status_code)
   print(r.headers)
   print(r.content)

Prints:

500
{'Server': 'nginx', 'Date': 'Fri, 31 May 2019 09:18:27 GMT', 'Content-Type': 'text/xml;charset=utf-8', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive', 'Access-Time': '1559294307', 'X-Powered-By': 'PrestaShop Webservice', 'PSWS-Version': '1.7.5.2', 'Execution-Time': '0.003', 'Set-Cookie': 'PrestaShop-30ff13c7718a401c862ad41ea4c0505f=def50200b7a8c608f3053d32136569a34c897c09cea1230b5f8a0aee977e6caac3e22bea39c63c30bfc955fe344d2cbabf640dc75039c63b33c88c5f33e6b01f2b282047bfb0e05c8f8eb7af08f2cc5b0c906d2060f92fea65f73ce063bf6d87bd8ac4d03d1f9fc0d7b6bf56b1eb152575ef559d95f89fc4f0090124630ae292633b4e08cfee38cee533eb8abe151a7d9c47ed84366a5dd0e241242b809300f84b9bb2; expires=Thu, 20-Jun-2019 09:18:27 GMT; Max-Age=1728000; path=/; domain=example.com; secure; HttpOnly', 'Vary': 'Authorization', 'MS-Author-Via': 'DAV'}

b'<?xml version="1.0" encoding="UTF-8"?>
\n<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
   \n<errors>
        \n<error>
            \n<code><![CDATA[66]]></code>
            \n<message><![CDATA[Unable to save this image]]></message>
        \n</error>
    \n</errors>
\n</prestashop>\n'
Run Code Online (Sandbox Code Playgroud)

我尝试使用python的日志记录库,但只告诉我这一点:

DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): midominio:443

DEBUG:urllib3.connectionpool:https://midominio:443 "POST /api/images/products/20 HTTP/1.1" 500 None
Run Code Online (Sandbox Code Playgroud)

我还试图将文件config / defines.inc.php更改为活动调试模式,但我在prestashop论坛中阅读了该文件,但有任何不同。

我也探查了prestapyt(和prestapyt3)库,但不适用于python 3,并且我读到与presta 1.7不兼容

编辑:Display_errors和log_errors在我的Plesk面板中被激活: 在此处输入图片说明

但是当我去var / www / vhosts / midominio / logs / error_log时

我看不到任何引用到php的错误或任何行中的500错误。

预先感谢您的任何建议...

编辑:我在响应中探测建议,但返回相同的错误。

kau*_*k94 2

我认为如果后端工作正常的话,问题就出在 post 命令中。data用于发送表单数据和其他文本数据。要上传文件,您应该这样做:

files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)
Run Code Online (Sandbox Code Playgroud)

所以你的代码翻译成:

def addNewImage(product_id):
   file = 'foto.png'
   fd = io.open(file, "rb")
   r = requests.post(urlimg + product_id, auth=(key,""), headers={'Content-Type': 'multipart/form-data'}, files={ 'media' : fd })
   print(r.status_code)
   print(r.headers)
   print(r.content)
Run Code Online (Sandbox Code Playgroud)