I am trying to append text to a file programmatically via API.
Here is my code:
def updateFile(fileId):
headers = {
'Content-Type': 'application/json',
'token': token
}
url = 'https://example.com/api/file/' + str(fileId) + '/upload'
te = """
this
is
text
sdfs
"""
te= json.dumps(te)
return requests.put(url, headers=headers, data=te)
r = updateFile(id)
print r.json()
This is working, But when I download the file, I have some string like this:
"\n this\n is\n text\n sdfs\n "
As you can see, all the text is on the same line (\n
is not interpreted correctly), The "
still exists.
What can I be doing wrong?
Update
Send the raw file content without JSON encoding it, but don't specify Content-Type: application/json
.
By setting that header you're telling the server that the body of the request will be in JSON format which, if you upload the file as is, it will not be. The server is expecting JSON but is unhappy when it does not get JSON data. Conversely, if you send JSON data with that header, the server accepts the data and writes it to the file without decoding it.
You might need to set the content type. Assuming a plain text file you could use text/plain
.
If you take a look at the result of json.dumps()
:
import json
te = """
this
is
text
sdfs
"""
>>> json.dumps(te)
'"\\n this\\n is\\n text\\n sdfs\\n "'
you'll see that the new lines are escaped so that they are preserved. That's why they appear in your file. If you don't want them in your file then don't treat the string as JSON data, just upload it as is.
BTW, you can avoid the hassle of converting to JSON yourself if you use the json
parameter instead of the data
parameter:
# do not manually convert to JSON, use json parameter instead
return requests.put(url, headers=headers, json=te)