-2

How can I sent POST request in Python? Request must be multipart/mixed with json and photo without header. I try send this request with requests in python, but this package adds a description to the Data and the requests breaks the json into several parts. Example of a correct request's structure on photo. It is my code:

photo = open("photo.jpg", "rb")
file = {
    "Data": photo
}
new_card = {
    "AlternateId": "4558021a-4c29-5360-a511-08c59b52265c",
    "CreatedBy": "1",
    "Information": "test",
    "IsActive": True,
    "IsDeleted": False,
    "UserGroupId": 3,
    "PersonCardCategoryId": 3
}
r = requests.post("http://172.16.127.160:34015", auth=("1", "1"), data=new_card, files=file)

Updates:

Code:

r = requests.post("http://172.16.127.160:34015", auth=("1", "1"), json=new_card, files=file)

Now, WireShark shows me it

Kidav
  • 3
  • 1
  • 4
  • Read [post-a-multipart-encoded-file](http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file) – stovfl Aug 02 '17 at 13:10
  • I read this site when I started do this programm. And all examples do not work in my programm... – Kidav Aug 02 '17 at 13:56
  • Read this Answer [how to POST multipart ](https://stackoverflow.com/a/26300042/7414759), last 3 Sections. – stovfl Aug 03 '17 at 16:04

2 Answers2

1

Request with content-type 'multipart/mixed' with json and photo without header.

import requests
import json
from cStringIO import StringIO
headers = {
    '...': "...", 
    '...': "..."}
json = StringIO(json.dumps(new_card))
file = open('C:\\temp\\D.jpg', 'rb').read()
files = {"json": (None, json, "application/json; charset=UTF-8"), None: (None, file)}
r = requests.post('http://127.0.0.1:34015', files=files, headers=headers)

Discussion of this issue https://github.com/requests/requests/issues/1736

Consider next thing - 'multipart/mixed' it is not necessary to specify in the content type in the header. The main thing is that there should be a boundary. You can also build the query yourself, as shown here Python Requests Multipart HTTP POST

muXXmit2X
  • 2,745
  • 3
  • 17
  • 34
0

Question: Request must be multipart/mixed with json and photo without header

Your Questions Example Code doesn't respect how json have to be passed:
To POST json do the following:

more-complicated-post-requests

import json
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload), files=files)

Instead of encoding the dict yourself, you can also pass it directly using the json parameter (added in version 2.4.2) and it will be encoded automatically:

payload = {'some': 'data'}
r = requests.post(url, json=payload, files=files)
stovfl
  • 14,998
  • 7
  • 24
  • 51