python - ValueError: cannot encode objects that are that are not 2-tuples -


i'm trying upload file server , error:

valueerror: cannot encode objects are not 2-tuples 

the code:

import requests stringio import stringio buffer = stringio()  url = 'http://example.com/files/' user, password = 'ex', 'ample'  buffer.write(open(r'c:\users\example\desktop\code\de.txt','rb').read())   r = requests.post(url,  auth=(user, password), files=buffer.getvalue()) 

i tried auth=httpbasicauth(user, pass) didn't work either. can solution?

files accepts dictionary or sequence of (key, value) tuples. give file field name:

r = requests.post(url,  auth=(user, password), files={'file': buffer.getvalue()}) 

what name depends on api posting to. encodes data multipart/form-data encoded post body. see post multipart-encoded file section of requests quickstart documentation.

if needed post file data as sole data in body, use data keyword argument:

r = requests.post(url,  auth=(user, password), data=buffer.getvalue()}) 

i'm not sure why using stringio buffer; requests can handle file handle directly, without having read memory front. if do, you'd pass in open(....).read() result in directly without going through in-memory buffer first; that's overkill here.

i'd open file , have requests read , stream us:

with open(r'c:\users\example\desktop\code\de.txt','rb') filedata:     r = requests.post(url,  auth=(user, password), files={'file': filedata}) 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -