首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python请求-无法在有效负载中发送图像

Python请求-无法在有效负载中发送图像
EN

Stack Overflow用户
提问于 2022-01-23 16:22:01
回答 1查看 289关注 0票数 -1

我使用Python库请求创建了一个API测试。当我试图创造一个新产品时,我遇到了一个问题。产品有效载荷包含一个映像。见邮递员的要求:

我试图发送一个图像作为JSON有效负载的一部分。请参阅下面的代码:-

代码语言:javascript
复制
import requests
import json
import base64
from Utilities.resources import *
from Utilities.payloads import *
from Utilities.configurations import *

config = getConfig()

login_user_url = config['API']['productionUrl'] + ApiResources.userLogin
create_product_url = 'https://eshop-backend-101.herokuapp.com/api/v1/products'

print(create_product_url)

### Create a new product ###

## First get a user token - Login and get token
login_response = requests.post(login_user_url, json=userPayload(), headers=headerPayload())
get_login_json_response = login_response.json()
token = get_login_json_response['token']

## Use token to create product
print("CREATE A PRODUCT")

## https://stackoverflow.com/questions/29104107/upload-image-using-post-form-data-in-python-requests
image_file = "D:\\My Training Courses\\Python APUI Testing - Requests\\images\\testImage.jpg"

with open(image_file, "rb") as f:
    im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")

headerWithBearerTokenWithFormDataPayload = {
                'Content-Type': 'multipart/form-data; boundary=<calculated when request is sent>',
                'Authorization': 'Bearer ' + token
        }

bodyPayload = {
                "name": "Product API Test",
                "description": "Product API Test description",
                "richDescription": "Product API Test rich description",
                "image": im_b64,
                "brand": "Product API Test brand",
                "price": 300,
                "category": "5f15d54cf3a046427a1c26e3",
                "countInStock": 10,
                "rating": 4,
                "numReviews": 22,
                "isFeatured": True
        }

## create_product_response = requests.post(create_product_url, json=newProductPayload(im_b64), headers=headerWithBearerTokenPayload(token))
create_product_response = requests.post(create_product_url, json=bodyPayload, headers=headerWithBearerTokenWithFormDataPayload)
print(create_product_response)

我收到以下错误:-

回溯(最近一次调用):文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\connectionpool.py",第703行,在urlopen httplib_response = self._make_request(文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\connectionpool.py",第398行,在_make_request conn.request(方法,url,)文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\connection.py",第239行,请求超级(HTTPConnection,self).request(方法,url,body=body,headers=headers)文件"C:\Python39\lib\http\client.py",第1253行,请求self._send_request(方法,url,正文,标题,encode_chunked)文件"C:\Python39\lib\http\client.py",第1299行,在_send_request self.endheaders(body,encode_chunked=encode_chunked)文件"C:\Python39\lib\http\client.py",第1248行,在endheaders self._send_output(message_body,encode_chunked=encode_chunked)文件“C:\Python39\lib\http\client.py”中,第1047行,在_send_output self.send(块)文件“C:\Python39\lib\http\client.py”中,第969行,在发送self.sock.sendall(数据)文件"C:\Python39\lib\ssl.py“中,第1204行,在sendall v= self.send(byte_viewcount:)文件"C:\Python39\lib\ssl.py“第1173行中,在发送返回self._sslobj.write(数据) ConnectionResetError: WinError 10054中,一个现有连接被远程主机强制关闭 在处理上述异常的过程中,发生了另一个异常: 追溯(最近一次调用):文件"D:\My培训课程\Python测试- Requests\lib\site-packages\requests\adapters.py",第440行,在发送resp =conn.urlopen中“(文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\connectionpool.py",行785,在urlopen retries =retries.increment中)(文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\util\retry.py",第550行,在增量提高six.reraise(类型(错误),错误,_stacktrace)文件“D:\我的培训课程\Python测试- Requests\lib\site-packages\urllib3\connectionpool.py",行769,在reraise six.reraise(Tb)文件"D:\My培训课程\Python测试-Requests\lib\site-packages\urllib3\connectionpool.py”,第703行,在urlopen httplib_response =self._make_request中(文件"D:\My培训课程\Python测试- _make_request conn.request(方法,url,**httplib_request_kw)文件"D:\My培训课程\Python测试- Requests\lib\site-packages\urllib3\connection.py",第239行,请求超级(HTTPConnection,self).request(方法,url,body=body ),headers=headers)文件"C:\Python39\lib\http\client.py",第1253行,在request self._send_request(方法,url,正文,标题,encode_chunked)文件“C:\Python39\lib\http\client.py”中,第1299行,在_send_request self.endheaders(body,encode_chunked=encode_chunked)文件“C:\Python39\lib\http\client.py”中,第1248行,在endheaders self._send_output(message_body,encode_chunked=encode_chunked)文件"C:\Python39\lib\http\client.py",第1047行,_send_output self.send(区块)文件"C:\Python39\lib\http\client.py",第969行,在发送self.sock.sendall(数据)文件"C:\Python39\lib\ssl.py“中,第1204行,在sendall v= self.send(byte_viewcount:)文件"C:\Python39\lib\ssl.py”中,第1173行,在发送返回self._sslobj.write(数据) urllib3.exceptions.ProtocolError:(“连接中止”,ConnectionResetError(10054,“现有连接被远程主机强制关闭”,无,10054,无)) 在处理上述异常的过程中,发生了另一个异常: 回溯(最近一次调用):create_product_response = requests.post(create_product_url,json=bodyPayload,requests.post)中的文件"D:\My培训课程\Python Requests\Automation101EShopAPITests\TEST.py",第55行 文件"D:\My培训课程\Python测试- request \lib\site-packages\requestesapi.py“,第117行,在post返回请求(‘post’,url,data=data,json=json,**kwargs)文件"D:\My培训课程\Python测试-请求\lib\site-packages\api.py”,第61行,在请求返回session.request(method=method,url=url,**kwargs)文件"D:\My培训课程\Python测试-请求\lib\api.py“,第61行,请求返回session.request(method=method,url=url,**kwargs)文件D:\My培训课程\Python测试-第529行,在request resp = self.send(prep,**send_kwargs) File "D:\My培训课程\Python测试-第645行,在send = adapter.send(request,**kwargs) File "D:\My培训课程\Python测试- Requests\lib\site-packages\requests\adapters.py",line 501中,在send (err,request=request) requests.exceptions.ConnectionError:(‘连接中止’,ConnectionResetError(10054 ),一个现有的连接被远程主机强行关闭‘,无,10054,无)

EN

回答 1

Stack Overflow用户

发布于 2022-01-23 18:28:43

根据请求的文档,您需要将字典作为json参数传递,而不是字符串。headers参数也是如此。因此,将json.dumps

代码语言:javascript
复制
bodyPayload = json.dumps(
        {
                "name": "Product API Test",
                "description": "Product API Test description",
                "richDescription": "Product API Test rich description",
                "image": im_b64,
                "brand": "Product API Test brand",
                "price": 300,
                "category": "5f15d54cf3a046427a1c26e3",
                "countInStock": 10,
                "rating": 4,
                "numReviews": 22,
                "isFeatured": True
        }
)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70824122

复制
相关文章

相似问题

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