发送带有请求和美味派的 json 文件
Posted
技术标签:
【中文标题】发送带有请求和美味派的 json 文件【英文标题】:Sending a file with json with requests and tastypie 【发布时间】:2021-12-19 12:49:36 【问题描述】:我正在尝试将一些 zip 文件和一些 json 发送到我的美味派端点。
我明白了:
The format indicated \'multipart/form-data\' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer."
在我的客户端上。
这是我的客户端代码:
def sendLogs():
url = "api/ziprel/"
payload = "param_1": "value_1","param_2": "value_2"
files =
'JSON': (None, json.dumps(payload), 'application/json'),
'Console': (os.path.basename('/home/pi/Desktop/Console.zip'), open('/home/pi/Desktop/Console.zip','rb'), 'application/zip')
r = requests.post(url,files=files)
print(r.content)
打印时出现错误,r.content
。
这是我的美味代码:
class MultipartResource(object):
def deserialize(self, request, data, format=None):
try:
if not format:
format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded')
if format == 'application/x-www-form-urlencoded':
return request.POST
if 'multipart' in format:
data = request.POST.copy()
data.update(request.FILES)
# Get the error here
json.loads(request.body)
zip = TestZipModel()
zip.ADB = request.FILES['ADB']
zip.save()
return data
except Exception as e:
print("Error ".format(e))
return super(MultipartResource, self).deserialize(request, data, format)
# overriding the save method to prevent the object getting saved twice
def obj_create(self, bundle, request=None, **kwargs):
pass
服务器正在获取:
Error 'utf-8' codec can't decode byte 0x95 in position 350: invalid start byte
我可以发送带有multipart/form-data
内容类型的 JSON 吗?有一个更好的方法吗?将数据与 zip 一起发送将非常有帮助。
【问题讨论】:
总是将完整的错误消息(从单词“Traceback”开始)作为文本(不是截图,不是链接到外部门户)有问题(不是评论)。还有其他有用的信息。 【参考方案1】:你可以这样做:
files = 'file': ('download_name.zip', open('file_name.zip', 'rb'), 'application/zip')
payload = 'key1': 'value1', 'key2': 'value2'
r = requests.post(url, data=payload, files=files) # could do params=payload instead data=payload (URL params)
烧瓶中的示例处理:
data = request.form
file = request.files['file']
【讨论】:
以上是关于发送带有请求和美味派的 json 文件的主要内容,如果未能解决你的问题,请参考以下文章
使用 alamofire 将带有 JSON 对象和查询参数的 POST 请求发送到 REST Web 服务
使用 Volley 发送带有 JSON 数据的 POST 请求
是否可以在 Axios 中发送带有 JSON 正文的 get 请求?