0

I have demographics information extracted for some people in the form of list of python dictionaries(each dict for an individual). Also I need to upload the document from where I extracted the data (pdf/word). I tried Multipart form submission using Python requests which because of some reason does not seem to work.

The API expects two keys 'files' and 'data' 'files' is a list of file objects 'data' is a list of dicts which is stringified using json.dumps (API requirements)

pay_part= [{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""},{"umr":"","age":"","gender":"","first_name":"","middle_name":"","last_name":"","phone":"","address":"","admission_date":"","lab":"","discharge_date":"","ip_number":"","diagnosis":"","reason":"","treatment":"","medications":"","expired_date":"","instructions":"","review_date":"","procedure":"","notes":"","physician":"","filename":""}]

multipart_data = MultipartEncoder(
fields={
        "file":[('file.docx',open('13427.docx', 'rb'),'text/plain'), 
        ('file.docx',open('13427.docx', 'rb'),'text/plain')],
         "payload": json.dumps(pay_part)
        }
                                  )

response = requests.post(url, data=multipart_data, headers={'Content-Type': 'multipart_data.content_type; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', 'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)

While forming the multipart form object I get an error "AttributeError: 'tuple' object has no attribute 'encode'".

I believe this has to do something with creating file objects as a binary and storing in list.

Thanks in advance!

0

1 Answer 1

4

I got it to work!

Just send your json object using the argument ‘data’ and a list of your file objects using the argument ‘files’ as shown below.

I removed from the header argument “'Content-Type': 'multipart_data.content_type; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW'”

The post request was made as a multipart post

Code:-

fields={'payload': json.dumps(pay_part)})

response = requests.post(url, data=fields,files =[('file',open('13385.docx', 'rb')),('file',open('13385.docx', 'rb'))],  headers={'userid': sUserID,'metaid': metaid,'postman-token':postmanToken})
print(response.text)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.