首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Python向API Prestashop发出POST请求

使用Python向API Prestashop发出POST请求
EN

Stack Overflow用户
提问于 2019-06-03 23:39:46
回答 1查看 2.3K关注 0票数 6

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

但我有一个问题,试图上传图像,无论是在创建新产品的图像和上传图像到我通过网络服务创建的产品。

我在我的代码中没有看到任何错误,所以我想知道我是否在使用Prestashop API时出错。

我的代码:

代码语言:javascript
运行
复制
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'

我尝试使用python的日志库,但只告诉我:

代码语言:javascript
运行
复制
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

我还尝试将文件config/defes.inc.php更改为active debug模式,这是我在prestashop论坛上读到的,但没有任何区别。

此外,我还探查了类库prestapyt(和prestapyt3),但不能与python3一起工作,并且我读到了与presta1.7不兼容的内容

编辑:在我的Plesk面板中激活Display_errors和log_errors:

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

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

提前感谢您的建议……

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

EN

回答 1

Stack Overflow用户

发布于 2019-06-07 08:29:58

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

代码语言:javascript
运行
复制
files = {'media': open('test.jpg', 'rb')}
requests.post(url, files=files)

因此,您的代码转换为:

代码语言:javascript
运行
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56430543

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档