Forums

Save text to file via requests POST, flask

How to get the text from file to save? Using Requests and Flask - don't want to go down the file upload function.

View:

@app.route('/postit2', methods=['GET', 'POST'])
def postit2():

        x = request.files.getlist('textfile')
        #gives empty dict: x = request.files.getlist('textfile')


        with open('/home/MadMartin/datapostfiles/EFL9.txt', 'w') as f:
            f.write(str(x))
            return '''ok'''

as it stands, this just save an empty list

script:

import requests
import json


url = 'https://madmartin.pythonanywhere.com/postit2'
#url = 'http://httpbin.org/post'
textfile = {'file': open('why.txt', 'rb')}

response = requests.post(url, files=textfile)

response.status_code

if response.status_code == 200:
    print('Success - file delivered! Raffik')
    print(response.content)
else:
    print('Got unexpected status code {}: {!r}'.format(response.status_code, response.headers))

note: if I use the httpbin.org/post route, it works fine, so guess there is something wrong with my route code?

a slight change has allowed me to save a representation of the file, but not the contents themselves. So, am I right in thinking that the actual file cannot be sent in this way?

@app.route('/postit2', methods=['GET', 'POST'])
def postit2():

        d = request.files.to_dict()
        with open('/home/MadMartin/datapostfiles/EFL9.txt', 'w') as f:           
            f.write(str(d))           
            return '''ok'''

this saves:

{'file': <FileStorage: 'why.txt' (None)>}

Check out the "Processing files" section of this tutorial, I think it has the information that you need.

ok, cheers, that tutorial looks useful - I'll check it out!